screentime: add OpenAssistant usage-summary tool
- Commit
cfaac1f9da264fb3f0ad8b42d491569816a96d83- Author
- Vayun Mathur <[email protected]>
- When
- 2026-12-02 04:25 UTC (3 days ago)
- Parents
407a805
Adds the screentime_get_usage OpenAssistant tool (READ): DTOs in library/intents/screentime (ScreentimeUsageQuery/AppUsageData/ ScreentimeUsageData), a validated provider contract in screentime/intents/GetUsageIntent (signature-guarded NoDisplay activity, provider-side clamp to top 5, label truncation, typed USAGE_ACCESS_NOT_GRANTED empty result), and host registration in AssistantToolSpecs + AssistantTools with a summarizeScreentimeUsage host summarizer in AssistantToolIntents. Aggregates only by design: today's total foreground time plus the top 5 apps with durations, built by the pure domain/ScreentimeUsageSummary from UsageHistory per-package totals. No per-event, per-hour, or per-session data is in the DTO, the wire shape, or the host summary; ScreentimeUsageSummaryTest pins the cap, the total, and the exact wire field names, and SummarizeScreentimeTest pins the host output. Tool count 54 -> 55; prompt budget kept at 24,500 chars by shortening the new spec row and three long food/shop descriptions without changing their meaning. Verified: :screentime:lint :screentime:lintVitalRelease :screentime:testDevUnitTest :openassistant:lint :openassistant:testDevUnitTest :library:lint all green.
Diff
library/AGENTS.md
diff --git a/library/AGENTS.md b/library/AGENTS.mdindex 293711a472..a801046121 100644--- a/library/AGENTS.md+++ b/library/AGENTS.md@@ -29,6 +29,7 @@ - com/vayunmathur/library/intents/music/MusicData.kt - com/vayunmathur/library/intents/taxi/RideEstimateData.kt - com/vayunmathur/library/intents/weather/WeatherData.kt+- com/vayunmathur/library/intents/screentime/ScreentimeData.kt — aggregates-only usage summary DTOs (total + top-5 apps) ### util/ — navigation, intents, messenger, storage, games glue - com/vayunmathur/library/util/Navigation.kt — `NavKey` + `MainNavigation` + `rememberNavBackStack` - com/vayunmathur/library/util/NavigationBottomBar.kt
library/src/main/java/com/vayunmathur/library/intents/screentime/ScreentimeData.kt
diff --git a/library/src/main/java/com/vayunmathur/library/intents/screentime/ScreentimeData.kt b/library/src/main/java/com/vayunmathur/library/intents/screentime/ScreentimeData.ktnew file mode 100644index 0000000000..e00dcd80ba--- /dev/null+++ b/library/src/main/java/com/vayunmathur/library/intents/screentime/ScreentimeData.kt@@ -0,0 +1,51 @@+package com.vayunmathur.library.intents.screentime++import kotlinx.serialization.Serializable++/**+ * Cross-app payload for the Screentime app's usage-summary intent.+ *+ * Aggregates only, by design: today's total foreground time plus the top+ * apps by duration. There is deliberately no per-event, per-hour, or+ * per-session field anywhere in this contract — raw usage events never+ * cross to another app.+ */++/** Query for [ScreentimeUsageData]: how many top apps to return (clamped provider-side). */+@Serializable+data class ScreentimeUsageQuery(+ /** Requested top-app count; the provider clamps this to 1..5. */+ val limit: Int = MAX_TOP_APPS,+) {+ /** Bounds for [limit]. */+ companion object {+ /** Hard cap on returned apps, whatever the caller asks for. */+ const val MAX_TOP_APPS = 5++ /** Default and maximum label length the provider emits. */+ const val MAX_LABEL_CHARS = 60+ }+}++/** One app's aggregated foreground time for today. */+@Serializable+data class AppUsageData(+ val packageName: String,+ /** Display label, truncated provider-side to [ScreentimeUsageQuery.MAX_LABEL_CHARS]. */+ val label: String,+ /** Total foreground milliseconds today (aggregate, not individual sessions). */+ val totalMillis: Long,+)++/** Today's screen-time summary: one total plus at most [ScreentimeUsageQuery.MAX_TOP_APPS] apps. */+@Serializable+data class ScreentimeUsageData(+ /** Total foreground milliseconds today across all apps. */+ val totalMillis: Long = 0,+ /** Top apps by [AppUsageData.totalMillis], descending; at most 5 entries. */+ val apps: List<AppUsageData> = emptyList(),+ /** False when usage access is not granted; [apps] and [totalMillis] are then empty/zero. */+ val hasUsageAccess: Boolean = true,+ /** Typed failure (e.g. `USAGE_ACCESS_NOT_GRANTED`), or null on success. */+ val error: String? = null,+)
openassistant/AGENTS.md
diff --git a/openassistant/AGENTS.md b/openassistant/AGENTS.mdindex 63de609ae4..e19c0bda74 100644--- a/openassistant/AGENTS.md+++ b/openassistant/AGENTS.md@@ -70,7 +70,8 @@ _Install: ./install openassistant (dev by default)._ - com/vayunmathur/openassistant/platform/AssistantViewModel.kt - com/vayunmathur/openassistant/platform/MamlChatEngine.kt - com/vayunmathur/openassistant/platform/AssistantDeviceTools.kt-- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+- com/vayunmathur/openassistant/platform/AssistantToolIntents.kt — commerce/communicate/screentime intent back ends + host summarizers (incl. `summarizeScreentimeUsage`)+- com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt — core cross-app intent back ends (notes/todo/contacts/calendar/family/music/email/clock/weather/maps/taxi/screentime) - com/vayunmathur/openassistant/platform/AudioRecorder.kt - com/vayunmathur/openassistant/platform/AssistantTools.kt - com/vayunmathur/openassistant/platform/AssistantCatalog.kt — A2UI component catalog + its prompt section
openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.ktindex 4b272a25de..4af2a4f08d 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/domain/AssistantToolSpecs.kt@@ -93,17 +93,18 @@ send_message_v2|C|Send via Communicate (requires confirmation, EXPLICIT request find_restaurants|-|Find restaurants near a location via the FoodDelivery app, optionally filtered by name or tag.|query^S^0^optional name or tag filter~lat^N^1^latitude~lng^N^1^longitude~limit^N^0^optional max results (default 5) get_restaurant_menu|-|Get the menu of a restaurant (merchant_id from find_restaurants). Items carry ids, prices in cents, availability and modifier groups.|merchant_id^N^1^merchant id from find_restaurants food_get_cart|-|Get the current FoodDelivery cart (items and total)|-food_set_cart|L|Replace the FoodDelivery cart with items_json: a JSON array like [{"itemId":1,"qty":2,"modifierIds":[]}]. The cart is re-validated and shown back to the user right away; no order is placed and no money moves.|merchant_id^N^1^merchant id the items belong to~items_json^S^1^JSON array of {itemId, qty, modifierIds}+food_set_cart|L|Replace the FoodDelivery cart with items_json ([{"itemId":1,"qty":2,"modifierIds":[]}]); re-validated, shown back; no order placed.|merchant_id^N^1^merchant id the items belong to~items_json^S^1^JSON array of {itemId, qty, modifierIds} food_prepare_order|-|Price the current cart (pickup or delivery) without creating an order; returns the summary the user confirms in FoodDelivery.|merchant_id^N^1^merchant id of the cart~is_pickup^N^0^1 for pickup, 0 (default) for delivery~address_id^S^0^optional saved address id~tip_cents^N^0^optional tip in cents~promo^S^0^optional promo code-place_food_order|H|Show the order summary for the current cart. The user places and pays for the order in the FoodDelivery app itself; this never creates an order or charges a card.|merchant_id^N^1^merchant id of the cart+place_food_order|H|Show the cart's order summary; the user pays in FoodDelivery. Never creates an order or charges.|merchant_id^N^1^merchant id of the cart get_food_orders|-|Get the user's past FoodDelivery orders| search_products|-|Search the Shop catalog. Each result is one purchasable variant with its variant_id, store and exact price.|query^S^1^search text~limit^N^0^optional max results (default 5) get_product_detail|-|Get one product's variants with exact prices and availability. Confirm the exact variant with the user before adding it to the cart.|shop_domain^S^1^store domain from search_products~product_id^S^1^product id from search_products~variant_id^S^0^optional variant to price shop_get_cart|-|Get the current Shop cart, grouped by store| shop_add_to_cart|L|Add an exact variant to the Shop cart (re-verified first, shown back; no checkout).|shop_domain^S^1^store domain from search_products~variant_id^S^1^exact variant id from get_product_detail~quantity^N^0^quantity 1-99 (default 1) shop_remove_from_cart|L|Remove a variant from the Shop cart; the cart is shown back to the user.|variant_id^S^1^variant id to remove-start_shop_checkout|H|Show the per-store cart summary for one store. The user checks out in the Shop app itself; this never creates a checkout or charges anything, and opening the cart is not a paid order.|shop_domain^S^1^store domain to check out+start_shop_checkout|H|Show one store's cart summary; the user checks out in Shop. Never charges; opening the cart is not an order.|shop_domain^S^1^store domain to check out get_shop_orders|-|Get the user's Shop order summaries|+screentime_get_usage|-|Get today's screen time: total + top 5 apps with durations.| get_memories|-|Get a list of all memories| remove_memory|C|Remove a memory by its id (requires confirmation)|id^N^1^ add_to_memory|-|Add a new memory to the list of memories|content^S^1^
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.ktindex 88ad568bd1..64713a4def 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantCoreToolIntents.kt@@ -40,6 +40,8 @@ import com.vayunmathur.library.intents.fooddelivery.RestaurantData import com.vayunmathur.library.intents.fooddelivery.SetCart import com.vayunmathur.library.intents.fooddelivery.SetCartItem import com.vayunmathur.library.intents.maps.DirectionsRequest+import com.vayunmathur.library.intents.screentime.ScreentimeUsageData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery import com.vayunmathur.library.intents.shop.AddToCartRequest import com.vayunmathur.library.intents.shop.CartData as ShopCartData import com.vayunmathur.library.intents.shop.GetProductQuery@@ -251,6 +253,13 @@ internal abstract class AssistantCoreToolIntents( return summarizeDirections(result) } + suspend fun getScreentimeUsage(limit: Int): ScreentimeUsageData = launchIntent(+ context,+ "com.vayunmathur.screentime",+ "com.vayunmathur.screentime.intents.GetUsageIntent",+ ScreentimeUsageQuery(limit),+ )+ suspend fun getRideEstimate( pickupLat: Double, pickupLng: Double,
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.ktindex df52989ea1..e36337d4e0 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantToolIntents.kt@@ -52,6 +52,8 @@ import com.vayunmathur.library.intents.maps.DirectionsResult import com.vayunmathur.library.intents.taxi.RideEstimateRequest import com.vayunmathur.library.intents.taxi.RideEstimateResult import com.vayunmathur.library.intents.weather.WeatherData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery import com.vayunmathur.openassistant.data.Memory import com.vayunmathur.openassistant.data.MemoryDao import kotlinx.datetime.TimeZone@@ -92,6 +94,7 @@ internal class AssistantToolIntents(context: Context) : AssistantCoreToolIntents "com.vayunmathur.fooddelivery" to "FoodDelivery", "com.vayunmathur.communicate" to "Communicate", "com.vayunmathur.shop" to "Shop",+ "com.vayunmathur.screentime" to "Screentime", ) fun getMissingAppMessage(packageName: String): String {@@ -480,6 +483,37 @@ fun summarizeShopOrders(list: List<ShopOrderData>, cap: Int = 10): String = } } +/**+ * Host summary for `screentime_get_usage`: today's total plus the top apps+ * with durations. Aggregates only — the provider returns no per-event data,+ * and this caps the list again host-side so the model never sees more.+ */+fun summarizeScreentimeUsage(data: ScreentimeUsageData): String {+ if (!data.hasUsageAccess || data.error != null) {+ return "Screen time unavailable: usage access is not granted in Screentime"+ }+ if (data.apps.isEmpty()) return "No screen time recorded today (0m total)"+ val lines = data.apps.take(ScreentimeUsageQuery.MAX_TOP_APPS)+ .joinToString("\n") { app ->+ "${app.label.take(ScreentimeUsageQuery.MAX_LABEL_CHARS)} " ++ "(${app.packageName}): ${formatUsageDuration(app.totalMillis)}"+ }+ return "Today: ${formatUsageDuration(data.totalMillis)} total\n$lines"+}++/** Compact duration for usage summaries: `2h 15m`, `45m`, or `30s`. */+fun formatUsageDuration(millis: Long): String {+ val totalSeconds = millis / 1_000+ val hours = totalSeconds / 3_600+ val minutes = (totalSeconds % 3_600) / 60+ val seconds = totalSeconds % 60+ return when {+ hours > 0 -> "${hours}h ${minutes}m"+ minutes > 0 -> "${minutes}m"+ else -> "${seconds}s"+ }+}+ /** Maps a provider send outcome to the model-facing string; GV is typed. */ fun summarizeSendResult(result: SendMessageResult): String = when { result.success -> "Success: Message sent"
openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt
diff --git a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.ktindex 670ed24822..c6bbeae7b9 100644--- a/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt+++ b/openassistant/src/main/java/com/vayunmathur/openassistant/platform/AssistantTools.kt@@ -155,6 +155,15 @@ class AssistantTools( intents.runTool { intents.getWeather(a.number("latitude"), a.number("longitude")) } }, "get_weather_by_name" to { a -> intents.runTool { intents.getWeatherByName(a.string("location")) } },+ "screentime_get_usage" to { _ ->+ intents.runTool {+ com.vayunmathur.openassistant.platform.summarizeScreentimeUsage(+ intents.getScreentimeUsage(+ com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery.MAX_TOP_APPS,+ ),+ )+ }+ }, "get_directions" to { a -> intents.runTool { intents.getDirections(
openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.ktindex 65e7385cef..b998ee4ecb 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/domain/PromptBudgetTest.kt@@ -22,7 +22,7 @@ class PromptBudgetTest { val header = declared.length + InferenceService.DEFAULT_SYSTEM_PROMPT.length + AssistantCatalog.PROMPT_SECTION.length println("HEADER declared=${declared.length} prompt=${InferenceService.DEFAULT_SYSTEM_PROMPT.length} a2ui=${AssistantCatalog.PROMPT_SECTION.length} total=$header")- assertEquals(54, ASSISTANT_TOOL_SPECS.size)+ assertEquals(55, ASSISTANT_TOOL_SPECS.size) assertTrue(header <= MAX_HEADER_CHARS, "header=$header over budget $MAX_HEADER_CHARS") }
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.ktindex 4e33234eb8..eec6d828b9 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsInvokeTest.kt@@ -44,7 +44,7 @@ class AssistantToolsInvokeTest { assertEquals("Error: create_note needs title", call("create_note", "content" to "x")) assertTrue( call("set_timer", "seconds" to "abc").contains("must be a number"))- assertEquals(54, tools.declarations.size)+ assertEquals(55, tools.declarations.size) } @Test fun crossAppToolsReportMissingApps() {
openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.ktindex fbf2e89d30..d44eb7985c 100644--- a/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/platform/AssistantToolsTest.kt@@ -14,7 +14,7 @@ class AssistantToolsTest { @Test fun namesAreUniqueSnakeCase() { val names = ASSISTANT_TOOL_SPECS.map { it.name }- assertEquals(54, names.size)+ assertEquals(55, names.size) assertEquals(names.size, names.toSet().size) for (spec in ASSISTANT_TOOL_SPECS) { assertTrue(snake.matches(spec.name), spec.name)
openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeScreentimeTest.kt
diff --git a/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeScreentimeTest.kt b/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeScreentimeTest.ktnew file mode 100644index 0000000000..74b9a9a3c9--- /dev/null+++ b/openassistant/src/test/java/com/vayunmathur/openassistant/util/SummarizeScreentimeTest.kt@@ -0,0 +1,61 @@+package com.vayunmathur.openassistant.util++import com.vayunmathur.library.intents.screentime.AppUsageData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageData+import com.vayunmathur.openassistant.domain.ASSISTANT_TOOL_SPECS+import com.vayunmathur.openassistant.domain.ToolRisk+import com.vayunmathur.openassistant.platform.formatUsageDuration+import com.vayunmathur.openassistant.platform.summarizeScreentimeUsage+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Pins the aggregates-only host summary for `screentime_get_usage`. */+class SummarizeScreentimeTest {++ @Test fun specIsReadOnlySnakeCase() {+ val spec = ASSISTANT_TOOL_SPECS.first { it.name == "screentime_get_usage" }+ assertEquals(ToolRisk.READ, spec.risk)+ assertEquals(emptyList(), spec.params.map { it.name })+ }++ @Test fun summarizesTotalAndTopAppsWithDurations() {+ val text = summarizeScreentimeUsage(+ ScreentimeUsageData(+ totalMillis = 5_400_000,+ apps = listOf(+ AppUsageData("com.a.one", "One", 3_600_000),+ AppUsageData("com.b.two", "Two", 1_800_000),+ ),+ ),+ )+ assertTrue(text.startsWith("Today: 1h 30m total"), text)+ assertTrue("One (com.a.one): 1h 0m" in text, text)+ assertTrue("Two (com.b.two): 30m" in text, text)+ }++ @Test fun hostCapsAtFiveAppsEvenIfProviderSentMore() {+ val apps = (1..8).map { AppUsageData("com.app.$it", "App$it", it * 60_000L) }+ val text = summarizeScreentimeUsage(ScreentimeUsageData(totalMillis = 1_000, apps = apps))+ assertEquals(5, text.lines().count { "(" in it })+ }++ @Test fun deniedAndEmptyAreTypedAndShort() {+ val denied = summarizeScreentimeUsage(+ ScreentimeUsageData(hasUsageAccess = false, error = "USAGE_ACCESS_NOT_GRANTED"),+ )+ assertTrue("usage access is not granted" in denied, denied)+ assertEquals(+ "No screen time recorded today (0m total)",+ summarizeScreentimeUsage(ScreentimeUsageData()),+ )+ assertFalse(denied.contains("event", ignoreCase = true))+ }++ @Test fun durationFormatting() {+ assertEquals("2h 15m", formatUsageDuration(8_100_000))+ assertEquals("45m", formatUsageDuration(2_700_000))+ assertEquals("30s", formatUsageDuration(30_000))+ }+}
screentime/AGENTS.md
diff --git a/screentime/AGENTS.md b/screentime/AGENTS.mdindex 12d926215d..58e16dfd77 100644--- a/screentime/AGENTS.md+++ b/screentime/AGENTS.md@@ -4,7 +4,7 @@ _Install: ./install screentime (dev by default)._ - Gradle: :screentime / dir: screentime/-- Package roots present: ui, data, domain, platform, service, widget, notifications+- Package roots present: ui, data, domain, platform, service, widget, notifications, intents - Entry files: MainActivity.kt + Route.kt + Navigation.kt (single host; FrictionActivity stays a system-triggered activity) - Deps: :library:room, :library:widgets - Metadata: metadata_data/screentime.md (present)@@ -12,7 +12,7 @@ _Install: ./install screentime (dev by default)._ ## Overview **Purpose:** On-device screen-time dashboard — per-app usage, app timers + instant pauses, Wind Down (grayscale + DND), friction nudges, Glance widget. Sibling of `parentalcontrols/` (self-control vs supervised control). No account, nothing uploaded.-**Key features:** `platform/UsageHistory` + `domain/HourBuckets` feed dashboard/charts; `AppTimers`/`Suspender`/`Coordinator` enforce limits; `WindDownApplier` + `WindowScheduler` run bedtime; widget mirrors the dashboard.+**Key features:** `platform/UsageHistory` + `domain/HourBuckets` feed dashboard/charts; `AppTimers`/`Suspender`/`Coordinator` enforce limits; `WindDownApplier` + `WindowScheduler` run bedtime; widget mirrors the dashboard. Assistant read via `intents/GetUsageIntent` (`screentime_get_usage`): aggregates only — today's total + top 5 apps with durations, built by `domain/ScreentimeUsageSummary` from `UsageHistory` per-package totals; no per-event data crosses, and missing usage access returns a typed empty summary. **Entry points:** `MainActivity.kt` → `Navigation.kt` (`Route.Dashboard/AppDetails(packageName)/WindDown`) → `ui/DashboardScreen.kt` → `platform/ScreenTimeViewModel.kt` → `platform/Coordinator.kt` → `data/Rules.kt`. **Gotchas:** - `receiver/` is NOT a closed package root — don't add more files there@@ -25,6 +25,9 @@ _Install: ./install screentime (dev by default)._ - com/vayunmathur/screentime/data/Rules.kt - com/vayunmathur/screentime/data/Migrations.kt - com/vayunmathur/screentime/domain/HourBuckets.kt+- com/vayunmathur/screentime/domain/ScreentimeUsageSummary.kt — aggregates-only assistant summary (today's total + top 5 apps, capped/truncated)+### intents/ — assistant IPC+- com/vayunmathur/screentime/intents/GetUsageIntent.kt — validated `screentime_get_usage` contract (signature-guarded, NoDisplay) ### platform/ — coordination + enforcement - com/vayunmathur/screentime/platform/Coordinator.kt - com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt
screentime/src/main/AndroidManifest.xml
diff --git a/screentime/src/main/AndroidManifest.xml b/screentime/src/main/AndroidManifest.xmlindex 00b67c62ce..aa4491c280 100644--- a/screentime/src/main/AndroidManifest.xml+++ b/screentime/src/main/AndroidManifest.xml@@ -44,6 +44,11 @@ tools:ignore="QueryAllPackagesPermission" /> <!-- Timer/friction notices. A normal runtime permission. --> <uses-permission android:name="android.permission.POST_NOTIFICATIONS" />++ <!-- Guards the assistant usage-summary intent below: same-signature callers only. -->+ <permission+ android:name="com.vayunmathur.screentime.permissions.ACCESS_SCREENTIME"+ android:protectionLevel="signature" /> <!-- Wind-down couples to Do Not Disturb. Normal permission; the user grants the policy access once in Settings, after which the schedule toggles it directly. --> <uses-permission android:name="android.permission.ACCESS_NOTIFICATION_POLICY" />@@ -173,6 +178,13 @@ </intent-filter> </receiver> + <!-- Assistant usage summary: aggregates only (today's total + top apps). -->+ <activity+ android:name=".intents.GetUsageIntent"+ android:exported="true"+ android:permission="com.vayunmathur.screentime.permissions.ACCESS_SCREENTIME"+ android:theme="@android:style/Theme.NoDisplay" />+ <receiver android:name=".widget.ScreenTimeGlanceWidgetReceiver" android:exported="false"
screentime/src/main/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummary.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummary.kt b/screentime/src/main/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummary.ktnew file mode 100644index 0000000000..524a4eb79c--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummary.kt@@ -0,0 +1,52 @@+package com.vayunmathur.screentime.domain++import com.vayunmathur.library.intents.screentime.AppUsageData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery++/**+ * Builds the aggregates-only usage summary the assistant intent returns.+ *+ * Pure aggregation over per-package foreground totals: entries are filtered+ * to positive durations, sorted by duration (package name breaks ties, so+ * the order is deterministic), and capped at+ * [ScreentimeUsageQuery.MAX_TOP_APPS] however large [requestedLimit] is.+ * [totalMillis][ScreentimeUsageData.totalMillis] is today's total across+ * every package, not just the shown top apps. No timestamps, hour buckets,+ * or individual sessions are ever produced.+ */+fun buildUsageSummary(+ perAppMillis: Map<String, Long>,+ labelFor: (String) -> String,+ requestedLimit: Int,+ excludedPackage: String? = null,+): ScreentimeUsageData {+ val limit = requestedLimit.coerceIn(1, ScreentimeUsageQuery.MAX_TOP_APPS)+ val positive = perAppMillis.filterValues { it > 0 }+ val apps = positive.entries+ .filter { it.key != excludedPackage }+ .sortedWith(compareByDescending<Map.Entry<String, Long>> { it.value }.thenBy { it.key })+ .take(limit)+ .map { (packageName, millis) ->+ AppUsageData(+ packageName = packageName,+ label = labelFor(packageName)+ .take(ScreentimeUsageQuery.MAX_LABEL_CHARS)+ .ifBlank { packageName },+ totalMillis = millis,+ )+ }+ return ScreentimeUsageData(+ totalMillis = positive.values.sum(),+ apps = apps,+ hasUsageAccess = true,+ )+}++/** The typed empty summary returned when usage access is not granted. */+fun usageAccessDeniedSummary(): ScreentimeUsageData = ScreentimeUsageData(+ totalMillis = 0,+ apps = emptyList(),+ hasUsageAccess = false,+ error = "USAGE_ACCESS_NOT_GRANTED",+)
screentime/src/main/java/com/vayunmathur/screentime/intents/GetUsageIntent.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/intents/GetUsageIntent.kt b/screentime/src/main/java/com/vayunmathur/screentime/intents/GetUsageIntent.ktnew file mode 100644index 0000000000..2be8ee1e36--- /dev/null+++ b/screentime/src/main/java/com/vayunmathur/screentime/intents/GetUsageIntent.kt@@ -0,0 +1,47 @@+package com.vayunmathur.screentime.intents++import com.vayunmathur.library.intents.screentime.ScreentimeUsageData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery+import com.vayunmathur.library.util.AssistantIntent+import com.vayunmathur.screentime.domain.buildUsageSummary+import com.vayunmathur.screentime.domain.usageAccessDeniedSummary+import com.vayunmathur.screentime.platform.UsageAccess+import com.vayunmathur.screentime.platform.UsageHistory+import com.vayunmathur.screentime.platform.UsagePeriod+import java.time.LocalDate+import kotlinx.serialization.InternalSerializationApi+import kotlinx.serialization.serializer++/**+ * Validated contract for OpenAssistant's `screentime_get_usage` tool.+ *+ * Returns aggregates only: today's total foreground time plus the top apps+ * (at most [ScreentimeUsageQuery.MAX_TOP_APPS], clamped here provider-side)+ * with their durations. The underlying [UsageHistory] per-event stream is+ * reduced to per-package totals inside this app and never crosses the wire.+ * Without usage access this returns a typed empty result+ * (`USAGE_ACCESS_NOT_GRANTED`), matching the dashboard's empty state —+ * never an error and never partial raw data.+ */+@OptIn(InternalSerializationApi::class)+class GetUsageIntent : AssistantIntent<ScreentimeUsageQuery, ScreentimeUsageData>(+ serializer<ScreentimeUsageQuery>(),+ serializer<ScreentimeUsageData>(),+) {+ override suspend fun performCalculation(input: ScreentimeUsageQuery): ScreentimeUsageData {+ if (!UsageAccess.isGranted(this)) return usageAccessDeniedSummary()+ val today = UsageHistory(this).aggregate(UsagePeriod.Day, LocalDate.now())+ return buildUsageSummary(+ perAppMillis = today.perApp,+ labelFor = ::appLabel,+ requestedLimit = input.limit,+ excludedPackage = packageName,+ )+ }++ /** Display label for [packageName], falling back to the package name itself. */+ private fun appLabel(packageName: String): String = runCatching {+ val info = packageManager.getApplicationInfo(packageName, 0)+ packageManager.getApplicationLabel(info).toString()+ }.getOrElse { packageName }+}
screentime/src/test/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummaryTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummaryTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummaryTest.ktnew file mode 100644index 0000000000..d94c43a71f--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/domain/ScreentimeUsageSummaryTest.kt@@ -0,0 +1,84 @@+package com.vayunmathur.screentime.domain++import com.vayunmathur.library.intents.screentime.ScreentimeUsageData+import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.jsonObject+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Pins the aggregates-only contract of the assistant usage summary: today's+ * total plus at most five apps with durations — never per-event raw data.+ */+class ScreentimeUsageSummaryTest {++ private val perApp = mapOf(+ "com.a.one" to 3_600_000L,+ "com.b.two" to 1_800_000L,+ "com.c.three" to 900_000L,+ "com.d.four" to 600_000L,+ "com.e.five" to 300_000L,+ "com.f.six" to 60_000L,+ "com.g.zero" to 0L,+ "com.h.negative" to -5L,+ )++ @Test fun capsTopAppsAtFiveHoweverLargeTheRequest() {+ val summary = buildUsageSummary(perApp, { it }, requestedLimit = 100)+ assertEquals(ScreentimeUsageQuery.MAX_TOP_APPS, summary.apps.size)+ assertEquals(+ listOf("com.a.one", "com.b.two", "com.c.three", "com.d.four", "com.e.five"),+ summary.apps.map { it.packageName },+ )+ }++ @Test fun totalIsTodaysTotalAcrossAllAppsNotJustTopFive() {+ val summary = buildUsageSummary(perApp, { it }, requestedLimit = 5)+ assertEquals(3_600_000L + 1_800_000L + 900_000L + 600_000L + 300_000L + 60_000L, summary.totalMillis)+ }++ @Test fun limitClampsToAtLeastOneAndLabelsTruncate() {+ val one = buildUsageSummary(perApp, { "x".repeat(100) }, requestedLimit = 0)+ assertEquals(1, one.apps.size)+ assertEquals(ScreentimeUsageQuery.MAX_LABEL_CHARS, one.apps[0].label.length)+ val blank = buildUsageSummary(mapOf("com.a.one" to 1L), { "" }, requestedLimit = 5)+ assertEquals("com.a.one", blank.apps[0].label)+ }++ @Test fun excludesSelfAndDropsNonPositiveDurations() {+ val summary = buildUsageSummary(perApp, { it }, requestedLimit = 5, excludedPackage = "com.a.one")+ assertFalse(summary.apps.any { it.packageName == "com.a.one" })+ assertFalse(summary.apps.any { it.totalMillis <= 0 })+ // Total still counts every app's real use, including the excluded one.+ assertTrue(summary.totalMillis > summary.apps.sumOf { it.totalMillis })+ }++ @Test fun wireShapeHasOnlyAggregateFields() {+ val summary = buildUsageSummary(perApp, { "App" }, requestedLimit = 5)+ val root = Json.encodeToJsonElement(+ ScreentimeUsageData.serializer(), summary,+ ).jsonObject+ assertTrue(root.keys.all { it in setOf("totalMillis", "apps", "hasUsageAccess", "error") }, "${root.keys}")+ assertEquals(setOf("totalMillis", "apps"), root.keys intersect setOf("totalMillis", "apps"))+ val app = root.getValue("apps").let {+ (it as kotlinx.serialization.json.JsonArray)[0].jsonObject+ }+ assertEquals(setOf("packageName", "label", "totalMillis"), app.keys)+ // No raw-data field names may ever appear in the wire shape.+ val wire = root.toString()+ for (banned in listOf("event", "timestamp", "startMillis", "endMillis", "hour", "session")) {+ assertFalse(banned in wire.lowercase(), "wire leaks '$banned': $wire")+ }+ }++ @Test fun deniedSummaryIsTypedAndEmpty() {+ val denied = usageAccessDeniedSummary()+ assertFalse(denied.hasUsageAccess)+ assertEquals("USAGE_ACCESS_NOT_GRANTED", denied.error)+ assertEquals(0L, denied.totalMillis)+ assertTrue(denied.apps.isEmpty())+ }+}
screentime/src/test/java/com/vayunmathur/screentime/intents/GetUsageIntentTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/intents/GetUsageIntentTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/intents/GetUsageIntentTest.ktnew file mode 100644index 0000000000..d1f4f9ca23--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/intents/GetUsageIntentTest.kt@@ -0,0 +1,23 @@+package com.vayunmathur.screentime.intents++import com.vayunmathur.library.intents.screentime.ScreentimeUsageQuery+import com.vayunmathur.library.util.AssistantIntent+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertTrue++/** Pins the assistant-intent contract the Screentime handler exposes. */+@RunWith(RobolectricTestRunner::class)+class GetUsageIntentTest {++ @Test fun queryDefaultsToTheFiveAppCap() {+ assertEquals(ScreentimeUsageQuery.MAX_TOP_APPS, ScreentimeUsageQuery().limit)+ assertEquals(5, ScreentimeUsageQuery.MAX_TOP_APPS)+ }++ @Test fun intentIsAnAssistantIntent() {+ assertTrue(GetUsageIntent() is AssistantIntent<*, *>)+ }+}