Modern Apps git

← Modern-Apps.git

wear: calendar companion module

Commit
cbbf7ec3571f18284db222c5678585fa55c14ae9
Author
Vayun Mathur <[email protected]>
When
2026-11-24 18:06 UTC (11 days ago)
Parents
213a0b3
New :calendar-wear module (same package/signing as the
phone Calendar): today agenda + upcoming-by-day list +
event detail rendered purely from a persisted Data
Layer snapshot (today -> +30 days, 200-event cap, 90 KB
JSON cap dropping latest-first, honest truncation).
Watch is read-only by design (no attendee model to RSVP
against); its only write is requesting a fresh sync.
Phone publishes on change (coalesced), on capability
appearance, or manually from the Settings Watch row.

Verified: wear assemble + 8 wear tests; phone calendar
320 tests with one pre-existing baseline failure
(verified at 3a5ccd94c).

Diff

calendar-wear/AGENTS.md
diff --git a/calendar-wear/AGENTS.md b/calendar-wear/AGENTS.mdnew file mode 100644index 0000000000..147b7c0558--- /dev/null+++ b/calendar-wear/AGENTS.md@@ -0,0 +1,37 @@+# AGENTS.md — calendar-wear/ (':calendar:wear')++> Scoped supplement. Global rules in root `AGENTS.md` apply. Stay inside+> `calendar-wear/` + `calendar/` (the phone side of the same feature).++- Gradle: :calendar:wear (dir calendar-wear/) / dir: calendar-wear/ (convention: `common-conventions-wear`)+- Package roots present: ui, data, domain, service+- Entry file: ui/WearMainActivity.kt++## Why this module exists (read before changing identity)+Wear OS companion of the phone Calendar (`:calendar`). The Wearable Data+Layer only connects apps sharing a **package name and signing certificate**,+so this module deliberately uses `applicationId = "com.vayunmathur.calendar"`+(the phone app's) with the shared dev/release signing from the convention+plugins. Changing either breaks phone<->watch sync silently. Bootstrap is a+one-time ADB sideload of this APK onto the watch.++## Protocol+`domain/WearCalendarProtocol.kt` is a copy of the phone's file (Gradle cannot+depend on another app module). Change both copies together; each side's+`WearCalendarProtocolTest` pins the same golden JSON.++- Snapshot + watch-state sync: DataClient (`/calendar/snapshot`, `/calendar/watch-state`)+- Sync request: MessageClient (`/calendar/request-sync`), watch -> phone only++## What the watch can and cannot do+Read-only. It renders today's agenda, upcoming events and event detail from+its locally stored snapshot, offline. There is no event editing or RSVP:+the phone model has no attendee/self-status for local calendars, so no+watch action claims to change an event. The one watch-originated write is+asking the phone for a fresh snapshot.++## Verify (this module only)+```+./gradlew :calendar:wear:assembleDev+./gradlew :calendar:wear:testDebugUnitTest+```
calendar-wear/build.gradle.kts
diff --git a/calendar-wear/build.gradle.kts b/calendar-wear/build.gradle.ktsnew file mode 100644index 0000000000..b12bbbfa7a--- /dev/null+++ b/calendar-wear/build.gradle.kts@@ -0,0 +1,31 @@+plugins {+    id("common-conventions-wear")+}++launcherIcon {+    symbol = "calendar_month"+}++android {+    // The Wearable Data Layer only connects apps that share a package name and+    // signing certificate, so this module MUST ship as the phone app's package:+    // same applicationId (below) and the same signing config the convention+    // plugins already apply to both (debug key for dev, release key for+    // release). The namespace only names this module's own R/resources.+    namespace = "com.vayunmathur.calendar.wear"+    defaultConfig {+        applicationId = "com.vayunmathur.calendar"+        // Convention defaults to 30, but :library:log (pulled in by the wear+        // convention) requires 31, so the watch floor is 31.+        minSdk = 31+    }+}++dependencies {+    // Watch side of the Wear OS sync (see domain/WearCalendarProtocol.kt, the+    // copy of the phone protocol it must stay in step with).+    implementation(libs.play.services.wearable)+    implementation(libs.kotlinx.coroutines.android)+    testImplementation(libs.kotlin.test)+    testImplementation(libs.kotlin.test.junit)+}
calendar-wear/src/main/AndroidManifest.xml
diff --git a/calendar-wear/src/main/AndroidManifest.xml b/calendar-wear/src/main/AndroidManifest.xmlnew file mode 100644index 0000000000..3dbf77358f--- /dev/null+++ b/calendar-wear/src/main/AndroidManifest.xml@@ -0,0 +1,49 @@+<?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>++        <!-- Receives snapshot updates from the phone, including while the+             UI is not running. -->+        <service+            android:name=".service.WearCalendarListenerService"+            android:exported="true">+            <intent-filter>+                <action android:name="com.google.android.gms.wearable.DATA_CHANGED" />+                <data android:scheme="wear" android:host="*" android:pathPrefix="/calendar/snapshot" />+            </intent-filter>+        </service>+    </application>+</manifest>
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.ktnew file mode 100644index 0000000000..7cf3134cee--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/data/WearCalendarStore.kt@@ -0,0 +1,72 @@+package com.vayunmathur.calendar.wear.data++import android.content.Context+import com.google.android.gms.wearable.PutDataMapRequest+import com.google.android.gms.wearable.Wearable+import com.vayunmathur.calendar.wear.domain.WearCalendarProtocol+import com.vayunmathur.calendar.wear.domain.WearCalendarSnapshot+import com.vayunmathur.calendar.wear.domain.WearWatchState+import com.vayunmathur.library.log.Log+import java.io.File+import kotlinx.coroutines.flow.MutableStateFlow+import kotlinx.coroutines.flow.StateFlow+import kotlinx.coroutines.flow.asStateFlow+import kotlinx.serialization.encodeToString++/**+ * The watch's local truth: the last snapshot the phone published, persisted+ * as JSON in app-private storage so the UI renders offline (phone absent,+ * process cold-started) from whatever it already has.+ */+class WearCalendarStore private constructor(private val context: Context) {++    /** Holds singleton access. */+    companion object {+        private const val TAG = "WearCalendarStore"+        private const val KEY_JSON = "json"+        private const val KEY_SENT_AT = "sent_at"++        @Volatile+        private var instance: WearCalendarStore? = null++        /** The process-wide store (listener service and UI must agree on one). */+        fun get(context: Context): WearCalendarStore = instance ?: synchronized(this) {+            instance ?: WearCalendarStore(context.applicationContext).also { instance = it }+        }+    }++    private val snapshotFile = File(context.filesDir, "wear-calendar-snapshot.json")++    private val _snapshot = MutableStateFlow(loadSnapshot())++    /** Last snapshot from the phone; empty until the first sync. */+    val snapshot: StateFlow<WearCalendarSnapshot> = _snapshot.asStateFlow()++    /** Replace the stored snapshot (DataClient push from the phone) and tell the phone it landed. */+    fun setSnapshot(snapshot: WearCalendarSnapshot) {+        _snapshot.value = snapshot+        runCatching { snapshotFile.writeText(WearCalendarProtocol.json.encodeToString(snapshot)) }+            .onFailure { Log.status(TAG, "persist snapshot failed: ${it.message}") }+        publishWatchState()+    }++    /** Publish what this watch is rendering from, so the phone can show last-sync truth. */+    fun publishWatchState() {+        val current = _snapshot.value+        val state = WearWatchState(+            appliedGeneratedAtMillis = current.generatedAtMillis,+            eventCount = current.events.size,+        )+        runCatching {+            val request = PutDataMapRequest.create(WearCalendarProtocol.WATCH_STATE_PATH).apply {+                dataMap.putString(KEY_JSON, WearCalendarProtocol.json.encodeToString(state))+                dataMap.putLong(KEY_SENT_AT, System.currentTimeMillis())+            }.asPutDataRequest().setUrgent()+            Wearable.getDataClient(context).putDataItem(request)+        }.onFailure { Log.status(TAG, "publish watch state failed: ${it.message}") }+    }++    private fun loadSnapshot(): WearCalendarSnapshot = runCatching {+        WearCalendarProtocol.json.decodeFromString<WearCalendarSnapshot>(snapshotFile.readText())+    }.getOrDefault(WearCalendarSnapshot())+}
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearAgenda.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearAgenda.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearAgenda.ktnew file mode 100644index 0000000000..f38eed6a2b--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearAgenda.kt@@ -0,0 +1,35 @@+package com.vayunmathur.calendar.wear.domain++import kotlinx.datetime.LocalDate+import kotlinx.datetime.TimeZone+import kotlinx.datetime.toLocalDateTime+import kotlin.time.Instant++/** Events split for the watch's two list sections. */+data class WearAgenda(+    val today: List<WearCalendarEvent>,+    val upcoming: List<WearCalendarEvent>,+)++/**+ * Splits [snapshot] into today's agenda and everything after it, in the+ * watch's own time zone. Events already over are dropped (a multi-day event+ * still running counts as today's). Pure so the section logic is unit-tested+ * without a device.+ */+fun wearAgenda(snapshot: WearCalendarSnapshot, nowMillis: Long, zone: TimeZone): WearAgenda {+    val today = Instant.fromEpochMilliseconds(nowMillis).toLocalDateTime(zone).date+    val live = snapshot.events.filter { it.endMillis > nowMillis }+    fun startDate(event: WearCalendarEvent): LocalDate =+        Instant.fromEpochMilliseconds(event.startMillis)+            .toLocalDateTime(if (event.allDay) TimeZone.UTC else zone).date+    return WearAgenda(+        today = live.filter { startDate(it) <= today },+        upcoming = live.filter { startDate(it) > today },+    )+}++/** Day label for grouping upcoming events, e.g. the date an event starts on. */+fun wearEventDay(event: WearCalendarEvent, zone: TimeZone): LocalDate =+    Instant.fromEpochMilliseconds(event.startMillis)+        .toLocalDateTime(if (event.allDay) TimeZone.UTC else zone).date
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.ktnew file mode 100644index 0000000000..25628e4e01--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocol.kt@@ -0,0 +1,150 @@+package com.vayunmathur.calendar.wear.domain++import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json++/**+ * Phone <-> watch sync protocol for the Wear OS Calendar companion.+ *+ * SINGLE SOURCE OF TRUTH, DELIBERATELY DUPLICATED: the Wearable Data Layer only+ * connects apps that share a package name and signing certificate, but Gradle+ * cannot let one application module depend on another, so the wear module+ * (`:calendar:wear`, applicationId `com.vayunmathur.calendar`) carries a copy+ * of this file under `com.vayunmathur.calendar.wear.domain`. Change both+ * copies together; each side's unit tests pin the same golden JSON so a+ * one-sided edit fails loudly on the side that was not updated.+ *+ * Transport split:+ * - Capability advertisement (res string-array `android_wear_capabilities` on+ *   the watch) tells the phone the wear companion is present at all.+ * - DataClient carries the durable snapshot: [SNAPSHOT_PATH] phone -> watch+ *   and [WATCH_STATE_PATH] watch -> phone. DataItems survive disconnects and+ *   reconcile the two sides when they meet again.+ * - MessageClient carries one ephemeral command, [REQUEST_SYNC_PATH]+ *   watch -> phone: the watch asks for a fresh snapshot. That is the only+ *   watch-originated write. There is no event editing or RSVP: the phone's+ *   calendar model has no attendee/self-status for its local calendars, so+ *   inventing an RSVP write would fake a change the provider never made.+ */+object WearCalendarProtocol {+    /** Capability the wear companion advertises; the phone looks for it on connected nodes. */+    const val CAPABILITY = "calendar_wear_companion"++    /** DataClient path (phone -> watch): the [WearCalendarSnapshot] JSON. */+    const val SNAPSHOT_PATH = "/calendar/snapshot"++    /** DataClient path (watch -> phone): the [WearWatchState] JSON. */+    const val WATCH_STATE_PATH = "/calendar/watch-state"++    /** MessageClient path (watch -> phone): ask the phone to publish a fresh snapshot. */+    const val REQUEST_SYNC_PATH = "/calendar/request-sync"++    /** Days ahead of the window start included in a snapshot. */+    const val WINDOW_DAYS = 30++    /** Most events in one snapshot; a watch has little storage and a tiny screen. */+    const val MAX_EVENTS = 200++    /**+     * Largest snapshot JSON, in UTF-8 bytes. DataClient caps a DataItem at+     * 100 KB; staying under it keeps the snapshot on DataClient (durable,+     * reconciled on reconnect) instead of needing a channel.+     */+    const val MAX_JSON_BYTES = 90_000++    /** Field caps applied when a snapshot is built, so one huge event cannot crowd out the rest. */+    const val MAX_TITLE_CHARS = 120+    const val MAX_LOCATION_CHARS = 120+    const val MAX_DESCRIPTION_CHARS = 280+    const val MAX_CALENDAR_NAME_CHARS = 60++    /** Wire JSON: unknown keys ignored so a newer side never breaks an older one. */+    val json: Json = Json { ignoreUnknownKeys = true }+}++/** One event occurrence in a [WearCalendarSnapshot], trimmed to watch size. */+@Serializable+data class WearCalendarEvent(+    /** Phone provider event id; with [startMillis] it identifies one occurrence. */+    val eventId: Long,+    val title: String,+    val location: String = "",+    val description: String = "",+    val calendarName: String = "",+    /** ARGB display colour of the owning calendar, 0 when unknown. */+    val color: Int = 0,+    val startMillis: Long,+    val endMillis: Long,+    val allDay: Boolean = false,+    val timezone: String = "UTC",+)++/** The phone's bounded calendar snapshot for the watch ([WearCalendarProtocol.SNAPSHOT_PATH]). */+@Serializable+data class WearCalendarSnapshot(+    /** When the phone built this snapshot, epoch millis. */+    val generatedAtMillis: Long = 0L,+    /** Inclusive window start, epoch millis; the watch renders only inside the window. */+    val windowStartMillis: Long = 0L,+    /** Exclusive window end, epoch millis (window start + [WearCalendarProtocol.WINDOW_DAYS] days). */+    val windowEndMillis: Long = 0L,+    val events: List<WearCalendarEvent> = emptyList(),+    /** True when the window/size caps dropped events the window actually contained. */+    val truncated: Boolean = false,+)++/** What the watch last applied, published at [WearCalendarProtocol.WATCH_STATE_PATH]. */+@Serializable+data class WearWatchState(+    /** generatedAtMillis of the snapshot the watch is rendering from, 0 when none yet. */+    val appliedGeneratedAtMillis: Long = 0L,+    val eventCount: Int = 0,+)++/**+ * Builds a bounded snapshot from [candidates]: keeps occurrences that overlap+ * [[windowStartMillis], [windowEndMillis]), sorts by start, applies the field+ * caps, then enforces [WearCalendarProtocol.MAX_EVENTS] and+ * [WearCalendarProtocol.MAX_JSON_BYTES] (dropping latest-first, which keeps+ * today's agenda — the watch's main screen — intact longest).+ */+fun buildWearSnapshot(+    candidates: List<WearCalendarEvent>,+    generatedAtMillis: Long,+    windowStartMillis: Long,+    windowEndMillis: Long,+): WearCalendarSnapshot {+    val inWindow = candidates+        .filter { it.endMillis > windowStartMillis && it.startMillis < windowEndMillis }+        .sortedWith(compareBy({ it.startMillis }, { it.eventId }))+        .map { event ->+            event.copy(+                title = event.title.take(WearCalendarProtocol.MAX_TITLE_CHARS),+                location = event.location.take(WearCalendarProtocol.MAX_LOCATION_CHARS),+                description = event.description.take(WearCalendarProtocol.MAX_DESCRIPTION_CHARS),+                calendarName = event.calendarName.take(WearCalendarProtocol.MAX_CALENDAR_NAME_CHARS),+            )+        }+    var kept = inWindow.take(WearCalendarProtocol.MAX_EVENTS)+    var truncated = kept.size < inWindow.size+    var snapshot = WearCalendarSnapshot(+        generatedAtMillis = generatedAtMillis,+        windowStartMillis = windowStartMillis,+        windowEndMillis = windowEndMillis,+        events = kept,+        truncated = truncated,+    )+    while (kept.isNotEmpty() &&+        WearCalendarProtocol.json.encodeToString(snapshot).encodeToByteArray().size >+        WearCalendarProtocol.MAX_JSON_BYTES+    ) {+        kept = kept.dropLast(1)+        truncated = true+        snapshot = snapshot.copy(events = kept, truncated = true)+    }+    return snapshot+}++/** True when [nodeIdsWithCapability] is non-empty: a watch companion is present. */+fun wearCompanionPresent(nodeIdsWithCapability: Collection<String>): Boolean =+    nodeIdsWithCapability.isNotEmpty()
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.ktnew file mode 100644index 0000000000..e2d91869a4--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/service/WearCalendarListenerService.kt@@ -0,0 +1,38 @@+package com.vayunmathur.calendar.wear.service++import com.google.android.gms.wearable.DataEvent+import com.google.android.gms.wearable.DataEventBuffer+import com.google.android.gms.wearable.DataMapItem+import com.google.android.gms.wearable.WearableListenerService+import com.vayunmathur.calendar.wear.data.WearCalendarStore+import com.vayunmathur.calendar.wear.domain.WearCalendarProtocol+import com.vayunmathur.calendar.wear.domain.WearCalendarSnapshot+import com.vayunmathur.library.log.Log++/** Receives the phone's snapshot DataItem, including while the UI is not running. */+class WearCalendarListenerService : WearableListenerService() {++    override fun onDataChanged(dataEvents: DataEventBuffer) {+        for (event in dataEvents) {+            if (event.type != DataEvent.TYPE_CHANGED) continue+            val item = event.dataItem+            if (item.uri.path != WearCalendarProtocol.SNAPSHOT_PATH) continue+            val raw = runCatching {+                DataMapItem.fromDataItem(item).dataMap.getString(KEY_JSON)+            }.getOrNull() ?: continue+            val snapshot = runCatching {+                WearCalendarProtocol.json.decodeFromString<WearCalendarSnapshot>(raw)+            }.getOrNull()+            if (snapshot == null) {+                Log.status(TAG, "ignoring malformed snapshot")+                continue+            }+            WearCalendarStore.get(this).setSnapshot(snapshot)+        }+    }++    private companion object {+        const val TAG = "WearCalendarListener"+        const val KEY_JSON = "json"+    }+}
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.ktnew file mode 100644index 0000000000..07b1807515--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/sync/WearSyncRequest.kt@@ -0,0 +1,36 @@+package com.vayunmathur.calendar.wear.sync++import android.content.Context+import com.google.android.gms.wearable.Wearable+import com.vayunmathur.calendar.wear.domain.WearCalendarProtocol+import com.vayunmathur.library.log.Log+import kotlin.coroutines.resume+import kotlin.coroutines.resumeWithException+import kotlinx.coroutines.suspendCancellableCoroutine+import com.google.android.gms.tasks.Task++/** Await a Play services [Task] without taking a coroutines-play-services dependency. */+private suspend fun <T> Task<T>.awaitTask(): T = suspendCancellableCoroutine { cont ->+    addOnSuccessListener { cont.resume(it) }+    addOnFailureListener { cont.resumeWithException(it) }+}++/**+ * Asks every connected phone node for a fresh snapshot. Returns false when no+ * phone is reachable — the watch keeps rendering its last synced copy, and+ * the UI says exactly that instead of pretending a sync happened.+ */+suspend fun requestWearSync(context: Context): Boolean = runCatching {+    val nodes = Wearable.getNodeClient(context).connectedNodes.awaitTask()+    if (nodes.isEmpty()) return false+    var sent = false+    for (node in nodes) {+        runCatching {+            Wearable.getMessageClient(context)+                .sendMessage(node.id, WearCalendarProtocol.REQUEST_SYNC_PATH, ByteArray(0))+                .awaitTask()+            sent = true+        }.onFailure { Log.status("WearSyncRequest", "request to ${node.id} failed: ${it.message}") }+    }+    sent+}.getOrDefault(false)
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearAgendaScreen.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearAgendaScreen.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearAgendaScreen.ktnew file mode 100644index 0000000000..718a5acfb2--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearAgendaScreen.kt@@ -0,0 +1,170 @@+package com.vayunmathur.calendar.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.calendar.wear.R+import com.vayunmathur.calendar.wear.data.WearCalendarStore+import com.vayunmathur.calendar.wear.domain.WearCalendarEvent+import com.vayunmathur.calendar.wear.domain.wearAgenda+import com.vayunmathur.calendar.wear.domain.wearEventDay+import com.vayunmathur.calendar.wear.sync.requestWearSync+import kotlinx.coroutines.launch+import kotlinx.datetime.TimeZone+import kotlinx.datetime.format+import kotlinx.datetime.format.MonthNames+import kotlinx.datetime.format.char+import kotlin.time.Instant+import kotlinx.datetime.LocalDate+import kotlinx.datetime.LocalDateTime+import kotlinx.datetime.toLocalDateTime++/** Round-screen agenda: today's events first, then upcoming grouped by day. */+@Composable+fun WearAgendaScreen(store: WearCalendarStore, onOpenEvent: (WearCalendarEvent) -> Unit) {+    val snapshot by store.snapshot.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)+    val zone = remember { TimeZone.currentSystemDefault() }+    val agenda = remember(snapshot) {+        wearAgenda(snapshot, System.currentTimeMillis(), zone)+    }+    val listState = rememberScalingLazyListState()++    ScalingLazyColumn(state = listState) {+        item {+            Text(+                stringResource(R.string.app_name),+                style = MaterialTheme.typography.title3,+                textAlign = TextAlign.Center,+                modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+            )+        }+        syncNote?.let { note ->+            item {+                Text(+                    note,+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+        }+        if (snapshot.events.isEmpty()) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            if (agenda.today.isNotEmpty()) {+                item { WearSectionHeader(stringResource(R.string.wear_today)) }+                items(agenda.today, key = { "${it.eventId}:${it.startMillis}" }) { event ->+                    WearEventChip(event, zone, onClick = { onOpenEvent(event) })+                }+            }+            if (agenda.upcoming.isNotEmpty()) {+                item { WearSectionHeader(stringResource(R.string.wear_upcoming)) }+                agenda.upcoming.groupBy { wearEventDay(it, zone) }.forEach { (day, dayEvents) ->+                    item(key = "day:$day") { WearSectionHeader(formatWearDay(day)) }+                    items(dayEvents, key = { "${it.eventId}:${it.startMillis}" }) { event ->+                        WearEventChip(event, zone, onClick = { onOpenEvent(event) })+                    }+                }+            }+            if (snapshot.truncated) {+                item {+                    Text(+                        stringResource(R.string.wear_truncated),+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+        }+        item {+            Chip(+                onClick = {+                    scope.launch {+                        syncNote = if (requestWearSync(context)) requestedText else noPhoneText+                    }+                },+                label = { Text(stringResource(R.string.wear_request_sync), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}++/** One section label in the agenda list. */+@Composable+private fun WearSectionHeader(text: String) {+    Text(+        text,+        style = MaterialTheme.typography.caption1,+        textAlign = TextAlign.Center,+        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+    )+}++/** One tappable event row: title plus its time (or All day). */+@Composable+private fun WearEventChip(event: WearCalendarEvent, zone: TimeZone, onClick: () -> Unit) {+    Chip(+        onClick = onClick,+        label = { Text(event.title, maxLines = 1) },+        secondaryLabel = { Text(formatWearEventTime(event, zone), maxLines = 1) },+        colors = ChipDefaults.secondaryChipColors(),+        modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+    )+}++private val wearDayFormat = LocalDate.Format {+    monthName(MonthNames.ENGLISH_ABBREVIATED)+    char(' ')+    day()+}++/** "Nov 25" style day label. */+fun formatWearDay(date: LocalDate): String = date.format(wearDayFormat)++private val wearTimeFormat = LocalDateTime.Format {+    hour()+    char(':')+    minute()+    char(' ')+    amPmMarker("AM", "PM")+}++/** "All day" or "2:30 PM" for one event in [zone]. */+fun formatWearEventTime(event: WearCalendarEvent, zone: TimeZone): String {+    if (event.allDay) return "All day"+    val local = Instant.fromEpochMilliseconds(event.startMillis).toLocalDateTime(zone)+    return local.format(wearTimeFormat)+}
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearEventScreen.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearEventScreen.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearEventScreen.ktnew file mode 100644index 0000000000..1b1651073f--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearEventScreen.kt@@ -0,0 +1,114 @@+package com.vayunmathur.calendar.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.remember+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.calendar.wear.R+import com.vayunmathur.calendar.wear.data.WearCalendarStore+import kotlinx.datetime.TimeZone+import kotlin.time.Instant+import kotlinx.datetime.toLocalDateTime++/** Read-only detail for one occurrence: title, time, location, notes. No editing — see AGENTS.md. */+@Composable+fun WearEventScreen(+    store: WearCalendarStore,+    eventId: Long,+    startMillis: Long,+    onBack: () -> Unit,+) {+    val snapshot by store.snapshot.collectAsState()+    val event = snapshot.events.firstOrNull {+        it.eventId == eventId && it.startMillis == startMillis+    }+    val zone = remember { TimeZone.currentSystemDefault() }+    val listState = rememberScalingLazyListState()++    ScalingLazyColumn(state = listState) {+        if (event == null) {+            item {+                Text(+                    stringResource(R.string.wear_empty),+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+        } else {+            item {+                Text(+                    event.title,+                    style = MaterialTheme.typography.title3,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp),+                )+            }+            item {+                val day = Instant.fromEpochMilliseconds(event.startMillis)+                    .toLocalDateTime(if (event.allDay) TimeZone.UTC else zone).date+                val timeText = if (event.allDay) {+                    stringResource(R.string.wear_all_day)+                } else {+                    val endEvent = event.copy(startMillis = event.endMillis)+                    "${formatWearEventTime(event, zone)} – ${formatWearEventTime(endEvent, zone)}"+                }+                Text(+                    "${formatWearDay(day)} · $timeText",+                    style = MaterialTheme.typography.body2,+                    textAlign = TextAlign.Center,+                    modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                )+            }+            if (event.location.isNotBlank()) {+                item {+                    Text(+                        event.location,+                        style = MaterialTheme.typography.body2,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+            if (event.calendarName.isNotBlank()) {+                item {+                    Text(+                        event.calendarName,+                        style = MaterialTheme.typography.caption1,+                        textAlign = TextAlign.Center,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+            if (event.description.isNotBlank()) {+                item {+                    Text(+                        event.description,+                        style = MaterialTheme.typography.body2,+                        modifier = Modifier.fillMaxWidth().padding(horizontal = 12.dp, vertical = 4.dp),+                    )+                }+            }+        }+        item {+            Chip(+                onClick = onBack,+                label = { Text(stringResource(R.string.wear_back), maxLines = 1) },+                colors = ChipDefaults.secondaryChipColors(),+                modifier = Modifier.fillMaxWidth().padding(horizontal = 8.dp),+            )+        }+    }+}
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.ktnew file mode 100644index 0000000000..2126a993fa--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearMainActivity.kt@@ -0,0 +1,43 @@+package com.vayunmathur.calendar.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.calendar.wear.data.WearCalendarStore++/**+ * Watch calendar entry: agenda list and event detail, rendered only from the+ * locally stored snapshot so it works standalone (phone absent, cold start).+ */+class WearMainActivity : ComponentActivity() {++    override fun onCreate(savedInstanceState: Bundle?) {+        super.onCreate(savedInstanceState)+        val store = WearCalendarStore.get(this)+        store.publishWatchState()+        setContent {+            MaterialTheme {+                var route by remember { mutableStateOf<WearRoute>(WearRoute.Agenda) }+                when (val current = route) {+                    WearRoute.Agenda -> WearAgendaScreen(+                        store = store,+                        onOpenEvent = { event ->+                            route = WearRoute.Event(event.eventId, event.startMillis)+                        },+                    )+                    is WearRoute.Event -> WearEventScreen(+                        store = store,+                        eventId = current.eventId,+                        startMillis = current.startMillis,+                        onBack = { route = WearRoute.Agenda },+                    )+                }+            }+        }+    }+}
calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearRoute.kt
diff --git a/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearRoute.kt b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearRoute.ktnew file mode 100644index 0000000000..177462ed7f--- /dev/null+++ b/calendar-wear/src/main/java/com/vayunmathur/calendar/wear/ui/WearRoute.kt@@ -0,0 +1,10 @@+package com.vayunmathur.calendar.wear.ui++/** Watch navigation destinations: detail is a route carrying the event key, never selection state. */+sealed interface WearRoute {+    /** Today's agenda + upcoming list. */+    data object Agenda : WearRoute++    /** One occurrence's detail, identified by phone event id + occurrence start. */+    data class Event(val eventId: Long, val startMillis: Long) : WearRoute+}
calendar-wear/src/main/res/values/colors.xml
diff --git a/calendar-wear/src/main/res/values/colors.xml b/calendar-wear/src/main/res/values/colors.xmlnew file mode 100644index 0000000000..bfc7025d71--- /dev/null+++ b/calendar-wear/src/main/res/values/colors.xml@@ -0,0 +1,5 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Background for the generated adaptive launcher icon (see LauncherIconGen). -->+<resources>+    <color name="ic_launcher_background">#FFFFFF</color>+</resources>
calendar-wear/src/main/res/values/strings.xml
diff --git a/calendar-wear/src/main/res/values/strings.xml b/calendar-wear/src/main/res/values/strings.xmlnew file mode 100644index 0000000000..645a223e49--- /dev/null+++ b/calendar-wear/src/main/res/values/strings.xml@@ -0,0 +1,13 @@+<?xml version="1.0" encoding="utf-8"?>+<resources>+    <string name="app_name">Calendar</string>+    <string name="wear_empty">No events synced yet. Open Calendar on your phone to sync this watch.</string>+    <string name="wear_today">Today</string>+    <string name="wear_upcoming">Upcoming</string>+    <string name="wear_all_day">All day</string>+    <string name="wear_request_sync">Sync now</string>+    <string name="wear_sync_requested">Asked your phone for a fresh copy</string>+    <string name="wear_no_phone">Phone not reachable — showing the last synced copy</string>+    <string name="wear_truncated">Showing the first part of your calendar; the rest stays on your phone</string>+    <string name="wear_back">Back</string>+</resources>
calendar-wear/src/main/res/values/wear_capabilities.xml
diff --git a/calendar-wear/src/main/res/values/wear_capabilities.xml b/calendar-wear/src/main/res/values/wear_capabilities.xmlnew file mode 100644index 0000000000..6faaa91373--- /dev/null+++ b/calendar-wear/src/main/res/values/wear_capabilities.xml@@ -0,0 +1,9 @@+<?xml version="1.0" encoding="utf-8"?>+<!-- Capability the phone's CapabilityClient looks for: advertising it is+     what makes the phone show this watch as present at all. Must match+     WearCalendarProtocol.CAPABILITY in domain/WearCalendarProtocol.kt. -->+<resources>+    <string-array name="android_wear_capabilities">+        <item>calendar_wear_companion</item>+    </string-array>+</resources>
calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearAgendaTest.kt
diff --git a/calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearAgendaTest.kt b/calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearAgendaTest.ktnew file mode 100644index 0000000000..b4b79db0ea--- /dev/null+++ b/calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearAgendaTest.kt@@ -0,0 +1,42 @@+package com.vayunmathur.calendar.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlinx.datetime.TimeZone++class WearAgendaTest {++    private fun event(id: Long, start: Long, end: Long) = WearCalendarEvent(+        eventId = id,+        title = "Event $id",+        startMillis = start,+        endMillis = end,+        timezone = "UTC",+    )++    @Test+    fun splitsTodayUpcomingAndDropsFinished() {+        // 2026-11-24T12:00:00Z+        val now = 1_795_521_600_000L+        val hour = 3_600_000L+        val day = 24 * hour+        val snapshot = WearCalendarSnapshot(+            events = listOf(+                event(1L, now - hour, now + hour), // running today+                event(2L, now + hour, now + 2 * hour), // later today+                event(3L, now + day, now + day + hour), // tomorrow+                event(4L, now - 2 * hour, now - hour), // finished+            ),+        )+        val agenda = wearAgenda(snapshot, now, TimeZone.UTC)+        assertEquals(listOf(1L, 2L), agenda.today.map { it.eventId })+        assertEquals(listOf(3L), agenda.upcoming.map { it.eventId })+    }++    @Test+    fun emptySnapshotHasEmptyAgenda() {+        val agenda = wearAgenda(WearCalendarSnapshot(), 0L, TimeZone.UTC)+        assertEquals(emptyList(), agenda.today)+        assertEquals(emptyList(), agenda.upcoming)+    }+}
calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocolTest.kt
diff --git a/calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocolTest.kt b/calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocolTest.ktnew file mode 100644index 0000000000..1acee044e4--- /dev/null+++ b/calendar-wear/src/test/java/com/vayunmathur/calendar/wear/domain/WearCalendarProtocolTest.kt@@ -0,0 +1,112 @@+package com.vayunmathur.calendar.wear.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue+import kotlinx.serialization.encodeToString++class WearCalendarProtocolTest {++    private fun event(+        id: Long,+        start: Long,+        end: Long = start + 3_600_000L,+        title: String = "Event $id",+        description: String = "",+    ) = WearCalendarEvent(+        eventId = id,+        title = title,+        location = "Room $id",+        description = description,+        calendarName = "Personal",+        color = 7,+        startMillis = start,+        endMillis = end,+        timezone = "UTC",+    )++    @Test+    fun goldenSnapshotJson() {+        val snapshot = WearCalendarSnapshot(+            generatedAtMillis = 1_000L,+            windowStartMillis = 2_000L,+            windowEndMillis = 3_000L,+            events = listOf(event(42L, 2_500L)),+            truncated = false,+        )+        assertEquals(+            """{"generatedAtMillis":1000,"windowStartMillis":2000,"windowEndMillis":3000,""" ++                """"events":[{"eventId":42,"title":"Event 42","location":"Room 42",""" ++                """"calendarName":"Personal","color":7,"startMillis":2500,""" ++                """"endMillis":3602500}]}""",+            WearCalendarProtocol.json.encodeToString(snapshot),+        )+    }++    @Test+    fun snapshotRoundTrips() {+        val snapshot = WearCalendarSnapshot(+            generatedAtMillis = 9L,+            windowStartMillis = 10L,+            windowEndMillis = 20L,+            events = listOf(event(1L, 12L), event(2L, 14L)),+            truncated = true,+        )+        val decoded = WearCalendarProtocol.json.decodeFromString<WearCalendarSnapshot>(+            WearCalendarProtocol.json.encodeToString(snapshot),+        )+        assertEquals(snapshot, decoded)+    }++    @Test+    fun buildKeepsOnlyWindowAndSortsByStart() {+        val snapshot = buildWearSnapshot(+            candidates = listOf(+                event(3L, 5_000L),+                event(1L, 3_000L),+                event(9L, 500L, end = 900L), // over before window+                event(8L, 9_500L), // starts after window+            ),+            generatedAtMillis = 1_000L,+            windowStartMillis = 1_000L,+            windowEndMillis = 9_000L,+        )+        assertEquals(listOf(1L, 3L), snapshot.events.map { it.eventId })+        assertFalse(snapshot.truncated)+    }++    @Test+    fun buildCapsEventCountAndMarksTruncated() {+        val candidates = (1L..(WearCalendarProtocol.MAX_EVENTS + 50L)).map {+            event(it, 1_000L + it * 1_000L)+        }+        val snapshot = buildWearSnapshot(candidates, 0L, 0L, Long.MAX_VALUE)+        assertEquals(WearCalendarProtocol.MAX_EVENTS, snapshot.events.size)+        assertTrue(snapshot.truncated)+        // Earliest kept: today's agenda survives longest.+        assertEquals(1L, snapshot.events.first().eventId)+    }++    @Test+    fun buildCapsFieldLengthsAndTotalBytes() {+        val longTitle = "x".repeat(WearCalendarProtocol.MAX_TITLE_CHARS + 100)+        val candidates = (1L..300L).map {+            event(it, 1_000L + it * 1_000L, title = longTitle, description = "d".repeat(500))+        }+        val snapshot = buildWearSnapshot(candidates, 0L, 0L, Long.MAX_VALUE)+        assertTrue(snapshot.events.all {+            it.title.length == WearCalendarProtocol.MAX_TITLE_CHARS &&+                it.description.length == WearCalendarProtocol.MAX_DESCRIPTION_CHARS+        })+        val bytes = WearCalendarProtocol.json.encodeToString(snapshot).encodeToByteArray().size+        assertTrue(bytes <= WearCalendarProtocol.MAX_JSON_BYTES, "snapshot $bytes bytes over cap")+        assertTrue(snapshot.truncated)+    }++    @Test+    fun capabilityAbsentMeansNoCompanion() {+        assertFalse(wearCompanionPresent(emptyList()))+        assertTrue(wearCompanionPresent(listOf("node-1")))+    }+}