parentalcontrols: make limits actually enforce instead of suspending apps
- Commit
7bae09c36fdc07a1cb42da63e81e82c152054595- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 15:42 UTC (14 days ago)
- Parents
4dd2924
Total review against the SDK model: a normal app cannot block other apps; this app's real tier is the supervision role (real on MAOS). The implementation was near-theatre: capped apps were written a TYPE_TIME_LIMIT policy that suspends on write - instantly and permanently; downtime, school and device limits only iterated the rules table, so unruled apps were never blocked; bonus time could never reopen an app because the spent mark was never cleared. New pure Enforcement decision (allow-list blocks every launchable unapproved app; precedence Bedtime > Downtime > School > DailyLimit > AppLimit, exempting self/Settings/ home/dialer); the suspending policy write is gone - observers do the timing. Bonuses clear the spent mark, midnight and 15-minute reconcile alarms exist, stale observers unregister, deleted rules stop stranding apps, bedtime/school editors are reachable from the dashboard, availability is probed honestly with a not-enforcing banner on builds where nothing can enforce, and time-change/locked-boot handling is fixed. Tier-inherent limits (force-stop, safe mode, uninstall) and the Device Owner enrolment decision are documented in the review artifact for the owner; not guessed at here. Verified: parentalcontrols 86 tests pass.
Diff
parentalcontrols/src/main/AndroidManifest.xml
diff --git a/parentalcontrols/src/main/AndroidManifest.xml b/parentalcontrols/src/main/AndroidManifest.xmlindex 2b54f8bae6..c3e7d38611 100644--- a/parentalcontrols/src/main/AndroidManifest.xml+++ b/parentalcontrols/src/main/AndroidManifest.xml@@ -281,6 +281,19 @@ </intent-filter> </activity-alias> + <!-- Clock, date and timezone changes: re-derive windows and re-arm alarms in the+ new local time instead of leaving boundaries armed in the old one. System+ broadcasts only; not exported. -->+ <receiver+ android:name=".platform.TimeChangedReceiver"+ android:exported="false">+ <intent-filter>+ <action android:name="android.intent.action.TIME_SET" />+ <action android:name="android.intent.action.TIMEZONE_CHANGED" />+ <action android:name="android.intent.action.DATE_CHANGED" />+ </intent-filter>+ </receiver>+ <!-- Fired by UsageStatsService when an app spends its daily budget. Not exported: the PendingIntent we hand the platform is what delivers it. --> <receiver@@ -298,7 +311,6 @@ android:permission="android.permission.BIND_SUPERVISION_APP_SERVICE"> <intent-filter> <action android:name="android.intent.action.BOOT_COMPLETED" />- <action android:name="android.intent.action.LOCKED_BOOT_COMPLETED" /> </intent-filter> </receiver>
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/Enforcement.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/Enforcement.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/Enforcement.ktnew file mode 100644index 0000000000..ea357e10a3--- /dev/null+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/domain/Enforcement.kt@@ -0,0 +1,69 @@+package com.vayunmathur.parentalcontrols.domain++/** Why an app is blocked. Order is precedence order (first holding reason wins). */+enum class EnforcementReason {+ Bedtime,+ Downtime,+ SchoolTime,+ DailyLimit,+ AppLimit,+}++/** The restriction one app carries, without any storage framework attached. */+data class AppRestriction(+ val packageName: String,+ val dailyLimitMinutes: Int? = null,+ val blockedAtBedtime: Boolean = false,+ val allowedInDowntime: Boolean = false,+)++/** Everything one enforcement decision is made from. Pure: no Android, no storage. */+data class EnforcementInput(+ /** Every package a child can launch (already minus exclusions such as our own app). */+ val launchablePackages: Set<String> = emptySet(),+ val restrictions: List<AppRestriction> = emptyList(),+ val bedtimeActive: Boolean = false,+ val downtimeActive: Boolean = false,+ val schoolTimeActive: Boolean = false,+ val deviceOverBudget: Boolean = false,+ /** Packages whose per-app daily budget has already been observed as spent today. */+ val reachedPackages: Set<String> = emptySet(),+)++/**+ * Decide, for every package in scope, whether it is blocked and why.+ *+ * Scope is launchable packages plus every restricted package (a restricted app stays+ * governed even if it currently has no launcher entry). The crucial property — the one the+ * old enforcer got wrong — is that downtime, school time and the device-wide daily limit+ * are *allow-list* features: they block every launchable app that is not explicitly+ * approved, including apps the parent has never touched and therefore has no restriction+ * row for. Bedtime and per-app limits stay block-list features, applying only where set.+ */+fun decideEnforcement(input: EnforcementInput): Map<String, EnforcementReason> {+ val byPackage = input.restrictions.associateBy { it.packageName }+ val scope = input.launchablePackages + byPackage.keys+ val result = LinkedHashMap<String, EnforcementReason>()+ for (packageName in scope) {+ val rule = byPackage[packageName]+ val allowedInWindow = rule?.allowedInDowntime == true+ val reason = when {+ rule?.blockedAtBedtime == true && input.bedtimeActive -> EnforcementReason.Bedtime+ input.downtimeActive && !allowedInWindow -> EnforcementReason.Downtime+ input.schoolTimeActive && !allowedInWindow -> EnforcementReason.SchoolTime+ input.deviceOverBudget -> EnforcementReason.DailyLimit+ packageName in input.reachedPackages -> EnforcementReason.AppLimit+ else -> null+ }+ if (reason != null) result[packageName] = reason+ }+ return result+}++/** Effective daily budget in minutes for [baseMinutes] plus today's bonus minutes. */+fun effectiveBudgetMinutes(baseMinutes: Int, bonusMinutes: List<Int>): Int =+ baseMinutes + bonusMinutes.sum()++/** Whether [usedMinutes] has spent a budget of [budgetMinutes]. */+fun budgetSpent(usedMinutes: Long, budgetMinutes: Int): Boolean =+ budgetMinutes >= 0 && usedMinutes >= budgetMinutes.toLong()
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.ktindex aaab48f2ab..f003f7045d 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/AppLimits.kt@@ -3,6 +3,7 @@ package com.vayunmathur.parentalcontrols.platform import android.app.PendingIntent import android.app.usage.UsageStatsManager import android.content.Context+import androidx.core.content.edit import com.vayunmathur.library.log.Log import androidx.core.content.getSystemService import com.vayunmathur.parentalcontrols.data.AppRule@@ -64,11 +65,30 @@ class AppLimits(private val context: Context) { val bonusByPackage = bonuses.filter { it.packageName != null } .groupBy { it.packageName!! } .mapValues { (_, grants) -> grants.sumOf { it.bonusMinutes } }- for (rule in rules) {+ val desired = rules.filter { it.dailyLimitMinutes != null }+ // Unregister observers whose cap was removed, whose app became blocked for another+ // reason, or that the master switch turned off (sync with an empty list). The old+ // register-only sync left those observers armed: a removed cap could still fire,+ // mark the app spent and block it for the rest of the day.+ val stale = registeredPackages() - desired.map { it.packageName }.toSet()+ for (packageName in stale) unregister(packageName)+ for (rule in desired) { val minutes = rule.dailyLimitMinutes ?: continue val budget = minutes + (bonusByPackage[rule.packageName] ?: 0) register(usage, rule.packageName, budget) }+ rememberRegistered(desired.map { it.packageName }.toSet())+ }++ private fun registeredPackages(): Set<String> =+ context.applicationContext+ .getSharedPreferences(OBSERVER_PREFS, Context.MODE_PRIVATE)+ .getStringSet(KEY_REGISTERED, emptySet()) ?: emptySet()++ private fun rememberRegistered(packages: Set<String>) {+ context.applicationContext+ .getSharedPreferences(OBSERVER_PREFS, Context.MODE_PRIVATE)+ .edit { putStringSet(KEY_REGISTERED, packages) } } /**@@ -158,6 +178,9 @@ class AppLimits(private val context: Context) { private fun observerId(packageName: String): Int = packageName.hashCode() private companion object {+ const val OBSERVER_PREFS = "parentalcontrols_observers"+ const val KEY_REGISTERED = "registered"+ val registerMethod: Method? by lazy { systemApi("registerAppUsageLimitObserver", Int::class.javaPrimitiveType!!, Array<String>::class.java, Duration::class.java, Duration::class.java, PendingIntent::class.java) }
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.ktindex cb1fdaeef2..705621b090 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/BedtimeScheduler.kt@@ -48,12 +48,73 @@ class BedtimeScheduler(private val context: Context) { bedtime: BedtimeSchedule, downtime: DowntimeSchedule, schoolTime: SchoolTimeSchedule,+ ) = armAll(bedtime, downtime, schoolTime, deviceLimitActive = false)++ /**+ * Arms every recurring trigger: the three window boundaries, the midnight reset and —+ * while a device-wide daily limit exists — a periodic budget check.+ *+ * The midnight alarm is not optional decoration. Per-app spent marks and usage+ * observers are day-scoped, but nothing else is guaranteed to run at midnight: without+ * it an app that spent its budget stayed blocked into the next day until some unrelated+ * trigger happened to reconcile. The periodic check is the device limit's only trigger+ * of its own (the platform has no device-total observer); it is inexact and re-armed by+ * every reconcile, so a spent device budget is noticed within one interval instead of+ * only at the next window boundary.+ */+ fun armAll(+ bedtime: BedtimeSchedule,+ downtime: DowntimeSchedule,+ schoolTime: SchoolTimeSchedule,+ deviceLimitActive: Boolean, ) { armWindow(bedtime.enabled, bedtime::activeAt, REQUEST_BEDTIME) armWindow(downtime.enabled, downtime::activeAt, REQUEST_DOWNTIME) armWindow(schoolTime.enabled, schoolTime::activeAt, REQUEST_SCHOOLTIME)+ armMidnight()+ armPeriodicCheck(deviceLimitActive)+ }++ private fun armMidnight() {+ val alarms = alarms ?: return+ val pending = pendingIntent(REQUEST_MIDNIGHT)+ alarms.cancel(pending)+ val nextMidnight = ZonedDateTime.now(ZoneId.systemDefault())+ .toLocalDate().plusDays(1).atStartOfDay(ZoneId.systemDefault())+ .plusSeconds(MIDNIGHT_GRACE_SECONDS)+ runCatching {+ if (alarms.canScheduleExactAlarms()) {+ alarms.setExactAndAllowWhileIdle(+ AlarmManager.RTC_WAKEUP, nextMidnight.toInstant().toEpochMilli(), pending,+ )+ } else {+ alarms.setAndAllowWhileIdle(+ AlarmManager.RTC_WAKEUP, nextMidnight.toInstant().toEpochMilli(), pending,+ )+ }+ }.onFailure { Log.status(TAG, "could not arm the midnight alarm", it) }+ }++ private fun armPeriodicCheck(enabled: Boolean) {+ val alarms = alarms ?: return+ val pending = periodicIntent()+ alarms.cancel(pending)+ if (!enabled) return+ val at = System.currentTimeMillis() + DEVICE_CHECK_INTERVAL_MINUTES * 60_000L+ // Deliberately inexact: an approximate quarter-hourly budget check is the honest+ // trade for not holding a wakeup all day. Doze may defer it further; observers and+ // window boundaries still enforce in the meantime.+ runCatching { alarms.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending) }+ .onFailure { Log.status(TAG, "could not arm the device-limit check", it) } } + private fun periodicIntent(): PendingIntent = PendingIntent.getBroadcast(+ context,+ REQUEST_DEVICE_CHECK,+ BedtimeReceiver.periodicIntent(context),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE,+ )+ private fun armWindow( enabled: Boolean, activeAt: (ZonedDateTime) -> Boolean,@@ -117,7 +178,11 @@ class BedtimeScheduler(private val context: Context) { const val REQUEST_BEDTIME = 1 const val REQUEST_DOWNTIME = 2 const val REQUEST_SCHOOLTIME = 3+ const val REQUEST_MIDNIGHT = 4+ const val REQUEST_DEVICE_CHECK = 5 const val MINUTES_IN_WEEK = 7 * 24 * 60+ const val MIDNIGHT_GRACE_SECONDS = 30L+ const val DEVICE_CHECK_INTERVAL_MINUTES = 15L } }
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.ktindex f77d9e675a..2b6a6a0f28 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Enforcer.kt@@ -1,6 +1,9 @@ package com.vayunmathur.parentalcontrols.platform import android.content.Context+import android.content.Intent+import android.content.pm.PackageManager+import android.os.Build import androidx.core.content.edit import com.vayunmathur.library.log.Log import com.vayunmathur.parentalcontrols.data.AppRule@@ -9,6 +12,10 @@ import com.vayunmathur.parentalcontrols.data.BonusGrant import com.vayunmathur.parentalcontrols.data.DowntimeSchedule import com.vayunmathur.parentalcontrols.data.SchoolTimeSchedule import com.vayunmathur.parentalcontrols.data.SupervisionRules+import com.vayunmathur.parentalcontrols.domain.AppRestriction+import com.vayunmathur.parentalcontrols.domain.EnforcementInput+import com.vayunmathur.parentalcontrols.domain.EnforcementReason+import com.vayunmathur.parentalcontrols.domain.decideEnforcement import com.vayunmathur.parentalcontrols.notifications.LockNotifier import java.time.LocalDate import java.time.LocalDateTime@@ -21,24 +28,31 @@ private const val BOUNDARY_LOOKBACK_MINUTES = 1L /** * Decides what each supervised app's state should be, and makes it so. *- * Everything that can change an outcome funnels through [reconcile]: the bedtime alarm, a usage- * observer firing, a rule edit, and boot. Recomputing the whole picture each time is what keeps- * the four of them from disagreeing - an incremental "block this one app" path would have to- * know whether bedtime was also active, and would get it wrong at exactly the boundary where it- * matters.+ * Everything that can change an outcome funnels through [reconcile]: the bedtime alarm, a+ * usage observer firing, a rule edit, a clock/timezone change and boot. The decision itself+ * is the pure [decideEnforcement] in `domain/`, so it can be tested without the platform+ * supervision service (whose compile-only stub cannot even load on a host JVM). *- * ## Precedence+ * ## What changed, and why (audit fixes) *- * Bedtime > downtime > school time > device-wide daily limit > per-app limit. All are reasons- * to block and none is a reason to unblock while another holds, so the state is simply the OR- * of them; the ordering only matters for the *reason* shown to the user.- *- * ## Why a limit trip is remembered- *- * The platform observer fires once when the budget runs out and does not fire again. If we- * treated "blocked" as derived purely from live usage, the next [reconcile] - a bedtime- * boundary, say - would unblock the app because nothing in the current state says the limit was- * reached. [LimitState] records the trip for the rest of the local day, and midnight clears it.+ * 1. Downtime, school time and the device-wide limit are allow-list features: they now block+ * every *launchable* app that is not approved — including apps with no rule row, which+ * the previous iterate-the-rules-table implementation never blocked at all.+ * 2. The parent's per-app cap is no longer also written as a `TYPE_TIME_LIMIT` policy after+ * the block/allow write. Upstream suspends a package the moment such a policy lands+ * (standing `TODO(b/482425646)`), so that write silently replaced the real decision and+ * permanently suspended every capped app. Timing is ours (usage observers); see+ * [SupervisionPolicies].+ * 3. Packages we previously blocked but that are no longer in scope (rule deleted, app no+ * longer launchable, master switched off) are explicitly allowed once — [ManagedPackages]+ * remembers the set across reconciles, so a deleted rule cannot leave an app blocked+ * forever.+ * 4. A per-app bonus grant now clears that package's spent mark ([onBonusGranted]): the old+ * code extended only the observer budget while [LimitState] still said "reached", so a+ * granted bonus could never actually reopen the app.+ * 5. The device-wide budget has a trigger of its own: [BedtimeScheduler] arms a periodic+ * check while a device limit exists, and the spent transition is notified exactly once+ * (marked in [LimitState]) instead of only being noticed on unrelated window boundaries. */ class Enforcer(private val context: Context) { @@ -47,6 +61,7 @@ class Enforcer(private val context: Context) { private val limits = AppLimits(context) private val bedtime = BedtimeScheduler(context) private val limitState = LimitState(context)+ private val managed = ManagedPackages(context) /** Note that [packageName] has used up its daily budget, then reconcile. */ suspend fun onLimitReached(packageName: String) {@@ -57,18 +72,29 @@ class Enforcer(private val context: Context) { LockNotifier.notifyLocked(context, BlockReason.AppLimit, packageName) } - /** Whether [rule] is blocked by school-time right now, given the other windows. */- private fun AppRule.schoolBlockedNow(bedtimeNow: Boolean, downtimeNow: Boolean): Boolean {- if (allowedInDowntime) return false- if (blockedAtBedtime && bedtimeNow) return false- return !downtimeNow+ /**+ * Grant [minutes] of bonus time for [packageName] (null = device-wide), then reconcile.+ *+ * For a per-app grant the spent mark must be cleared: the extended budget is re-armed+ * with the usage observer by [reconcile], and the observer re-marks the package if the+ * extended budget is also spent. A device-wide grant needs no mark clearing — the+ * over-budget test is computed live against the extended budget.+ */+ suspend fun onBonusGranted(packageName: String?, minutes: Int) {+ rules.grantBonus(+ BonusGrant(+ packageName = packageName,+ bonusMinutes = minutes,+ day = LocalDate.now().toString(),+ ),+ )+ if (packageName != null) limitState.clearReached(packageName)+ reconcile() } /**- * Bring the device in line with the stored rules.- * Notifies only for windows that just *opened* (closed a minute ago, open now), and only- * the apps that window blocks - so a boundary that ends a window stays silent, and an- * already-crying child is not re-notified for apps blocked all along by another reason.+ * Bring the device in line with the stored rules, notifying for windows that just+ * *opened*. A boundary that ends a window stays silent. */ suspend fun onWindowBoundary() { reconcile()@@ -81,7 +107,16 @@ class Enforcer(private val context: Context) { notifyBedtimeOpened(bedtime, now, minuteAgo, all) notifyDowntimeOpened(bedtime, downtime, now, minuteAgo, all) notifySchoolOpened(bedtime, downtime, school, now, minuteAgo, all)- notifyDeviceBudgetCrossed()+ }++ private fun notifyWindowOpened(+ activeNow: Boolean,+ activeMinuteAgo: Boolean,+ packages: List<String>,+ reason: BlockReason,+ ) {+ if (!activeNow || activeMinuteAgo) return+ for (packageName in packages) LockNotifier.notifyLocked(context, reason, packageName) } private suspend fun notifyBedtimeOpened(@@ -89,14 +124,10 @@ class Enforcer(private val context: Context) { now: LocalDateTime, minuteAgo: LocalDateTime, all: List<AppRule>,- ) {- if (!bedtime.activeAt(now) || bedtime.activeAt(minuteAgo)) return- for (rule in all) {- if (rule.blockedAtBedtime) {- LockNotifier.notifyLocked(context, BlockReason.Bedtime, rule.packageName)- }- }- }+ ) = notifyWindowOpened(+ bedtime.activeAt(now), bedtime.activeAt(minuteAgo),+ all.filter { it.blockedAtBedtime }.map { it.packageName }, BlockReason.Bedtime,+ ) private suspend fun notifyDowntimeOpened( bedtime: BedtimeSchedule,@@ -107,11 +138,15 @@ class Enforcer(private val context: Context) { ) { if (!downtime.activeAt(now) || downtime.activeAt(minuteAgo)) return val bedtimeNow = bedtime.activeAt(now)- for (rule in all) {- if (!rule.allowedInDowntime && !(rule.blockedAtBedtime && bedtimeNow)) {- LockNotifier.notifyLocked(context, BlockReason.Downtime, rule.packageName)+ val byPackage = all.associateBy { it.packageName }+ // Downtime blocks every launchable unapproved app, not just apps with a rule row —+ // the notice set must match the blocked set or the child is never told why.+ val targets = (launchablePackages() + all.map { it.packageName })+ .filter { pkg ->+ val rule = byPackage[pkg]+ rule?.allowedInDowntime != true && !(rule?.blockedAtBedtime == true && bedtimeNow) }- }+ for (pkg in targets) LockNotifier.notifyLocked(context, BlockReason.Downtime, pkg) } private suspend fun notifySchoolOpened(@@ -123,23 +158,15 @@ class Enforcer(private val context: Context) { all: List<AppRule>, ) { if (!school.activeAt(now) || school.activeAt(minuteAgo)) return+ if (downtime.activeAt(now)) return // downtime's notices already cover this minute val bedtimeNow = bedtime.activeAt(now)- val downtimeNow = downtime.activeAt(now)- for (rule in all) {- if (rule.schoolBlockedNow(bedtimeNow, downtimeNow)) {- LockNotifier.notifyLocked(context, BlockReason.SchoolTime, rule.packageName)+ val byPackage = all.associateBy { it.packageName }+ val targets = (launchablePackages() + all.map { it.packageName })+ .filter { pkg ->+ val rule = byPackage[pkg]+ rule?.allowedInDowntime != true && !(rule?.blockedAtBedtime == true && bedtimeNow) }- }- }-- private suspend fun notifyDeviceBudgetCrossed() {- val day = LocalDate.now().toString()- if (!deviceOverBudgetNow(rules.bonusesToday(day))) return- // Device-wide budget crossing is detected here rather than by an observer (the- // platform has no device-total primitive). This runs only on window-boundary alarms,- // so while the budget stays spent the child gets at most one notice per boundary.- // Per-app trips already notified via onLimitReached.- LockNotifier.notifyLocked(context, BlockReason.DailyLimit, null)+ for (pkg in targets) LockNotifier.notifyLocked(context, BlockReason.SchoolTime, pkg) } /**@@ -153,16 +180,17 @@ class Enforcer(private val context: Context) { Log.status(TAG, "no supervision policy channel; nothing will be enforced") return }- // Master switch off ("Controls for this phone"): lift every block, stop timing, and- // arm nothing. The child's device behaves as if unsupervised until it is turned on.+ // Master switch off ("Controls for this phone"): lift every block we manage, stop+ // timing, and arm nothing but the midnight reset. if (!SupervisionMaster.isEnabled(context)) {- val all = rules.allRulesNow()- for (rule in all) policies.allow(rule.packageName)+ val stale = managed.replace(emptySet())+ for (packageName in stale) policies.allow(packageName) limits.sync(emptyList(), emptyList()) bedtime.armAll( rules.scheduleNow().copy(enabled = false), rules.downtimeNow().copy(enabled = false), rules.schoolTimeNow().copy(enabled = false),+ deviceLimitActive = false, ) return }@@ -171,9 +199,6 @@ class Enforcer(private val context: Context) { val downtimeSchedule = rules.downtimeNow() val schoolSchedule = rules.schoolTimeNow() val all = rules.allRulesNow()- val bedtimeNow = bedtimeSchedule.activeAt(now)- val downtimeNow = downtimeSchedule.activeAt(now)- val schoolNow = schoolSchedule.activeAt(now) val day = LocalDate.now().toString() val bonuses = rules.bonusesToday(day) limitState.pruneToToday()@@ -183,59 +208,86 @@ class Enforcer(private val context: Context) { Log.status(TAG, "usage-stats op denied; limits measure from arm time until it is granted") } - val deviceOverBudget = deviceOverBudgetNow(bonuses)+ val launchable = launchablePackages()+ val deviceLimitMinutes = rules.dailyLimitNow()+ val deviceOverBudget = deviceOverBudgetNow(bonuses, deviceLimitMinutes)+ // Notify the spent transition exactly once per day; a bonus that brings the device+ // back under budget re-arms the notice.+ if (deviceOverBudget && !limitState.hasDeviceReached()) {+ limitState.markDeviceReached()+ LockNotifier.notifyLocked(context, BlockReason.DailyLimit, null)+ } else if (!deviceOverBudget) {+ limitState.clearDeviceReached()+ } - for (rule in all) {- val reason = blockReason(- rule = rule,- bedtimeNow = bedtimeNow,- downtimeNow = downtimeNow,- schoolNow = schoolNow,+ val plan = decideEnforcement(+ EnforcementInput(+ launchablePackages = launchable,+ restrictions = all.map {+ AppRestriction(it.packageName, it.dailyLimitMinutes, it.blockedAtBedtime, it.allowedInDowntime)+ },+ bedtimeActive = bedtimeSchedule.activeAt(now),+ downtimeActive = downtimeSchedule.activeAt(now),+ schoolTimeActive = schoolSchedule.activeAt(now), deviceOverBudget = deviceOverBudget,- )- if (reason != null) policies.block(rule.packageName)- else policies.allow(rule.packageName)- }+ reachedPackages = limitState.reachedPackages(),+ ),+ ) - // Record the parent's caps in the platform's own policy store. Does not enforce - see- // SupervisionPolicies.limit - but makes the intent visible to getPolicies and to anything- // that inspects supervision state later.- for (rule in all) {- rule.dailyLimitMinutes?.let { policies.limit(rule.packageName, it) }+ val inScope = launchable + all.map { it.packageName }+ for (packageName in inScope) {+ if (packageName in plan) policies.block(packageName) else policies.allow(packageName) }+ // Anything we blocked before that has fallen out of scope (rule deleted, app+ // uninstalled/replaced, no longer launchable) is allowed exactly once.+ val stale = managed.replace(inScope.filter { it in plan }.toSet())+ for (packageName in stale) policies.allow(packageName) - limits.sync(all.filter { blockReason(- rule = it,- bedtimeNow = bedtimeNow,- downtimeNow = downtimeNow,- schoolNow = schoolNow,- deviceOverBudget = deviceOverBudget,- ) == null }, bonuses)- bedtime.armAll(bedtimeSchedule, downtimeSchedule, schoolSchedule)+ // Observers arm only for capped apps that are not already blocked for another+ // reason; a blocked app needs no timer, and arming one would re-fire on reopen.+ limits.sync(+ all.filter { it.dailyLimitMinutes != null && it.packageName !in plan },+ bonuses,+ )+ bedtime.armAll(+ bedtimeSchedule, downtimeSchedule, schoolSchedule,+ deviceLimitActive = deviceLimitMinutes != null,+ ) } /**- * Why [rule]'s app is currently blocked, or null when it may run.- *- * Order is bedtime > downtime > school time > device daily limit > per-app limit; the first- * holding reason wins so the lock screen can name it.+ * Launchable packages a child could open, minus packages blocking would break:+ * ourselves (the parent must always be able to reach the controls), Settings, the+ * home/launcher package and the default dialer (calls stay available in every window,+ * matching the lock screens' promise). */- private fun blockReason(- rule: AppRule,- bedtimeNow: Boolean,- downtimeNow: Boolean,- schoolNow: Boolean,- deviceOverBudget: Boolean,- ): BlockReason? {- if (rule.blockedAtBedtime && bedtimeNow) return BlockReason.Bedtime- if (downtimeNow && !rule.allowedInDowntime) return BlockReason.Downtime- if (schoolNow && !rule.allowedInDowntime) return BlockReason.SchoolTime- if (deviceOverBudget) return BlockReason.DailyLimit- if (limitState.hasReached(rule.packageName)) return BlockReason.AppLimit- return null+ internal fun launchablePackages(): Set<String> {+ val pm = context.packageManager+ val launcherIntent = Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_LAUNCHER)+ val resolved = if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ pm.queryIntentActivities(launcherIntent, PackageManager.ResolveInfoFlags.of(0))+ } else {+ @Suppress("DEPRECATION") pm.queryIntentActivities(launcherIntent, 0)+ }+ val packages = resolved.mapNotNull { it.activityInfo?.packageName }.toMutableSet()+ packages.remove(context.packageName)+ packages.remove(SETTINGS_PACKAGE)+ resolveSinglePackage(+ Intent(Intent.ACTION_MAIN).addCategory(Intent.CATEGORY_HOME),+ )?.let { packages.remove(it) }+ resolveSinglePackage(Intent(Intent.ACTION_DIAL))?.let { packages.remove(it) }+ return packages } - /** The user-facing reason an app is blocked. Ordering matches [blockReason] precedence. */+ private fun resolveSinglePackage(intent: Intent): String? = runCatching {+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.TIRAMISU) {+ context.packageManager.resolveActivity(intent, PackageManager.ResolveInfoFlags.of(0))+ } else {+ @Suppress("DEPRECATION") context.packageManager.resolveActivity(intent, 0)+ }?.activityInfo?.packageName+ }.getOrNull()++ /** The user-facing reason an app is blocked. Ordering matches precedence. */ enum class BlockReason { Bedtime, Downtime,@@ -249,11 +301,52 @@ class Enforcer(private val context: Context) { * * Takes the already-loaded bonuses so [reconcile] does not read the table twice. */- private suspend fun deviceOverBudgetNow(bonuses: List<BonusGrant>): Boolean {+ private fun deviceOverBudgetNow(+ bonuses: List<BonusGrant>,+ deviceLimitMinutes: Int?,+ ): Boolean { val deviceBonus = bonuses.filter { it.packageName == null }.sumOf { it.bonusMinutes }- val deviceLimit = rules.dailyLimitNow()?.let { it + deviceBonus } ?: return false+ val deviceLimit = deviceLimitMinutes?.let { it + deviceBonus } ?: return false return limits.totalUsedToday() >= java.time.Duration.ofMinutes(deviceLimit.toLong()) }++ private companion object {+ const val SETTINGS_PACKAGE = "com.android.settings"+ }+}++/** Maps the pure decision reason onto the user-facing [Enforcer.BlockReason]. */+fun EnforcementReason.toBlockReason(): Enforcer.BlockReason = when (this) {+ EnforcementReason.Bedtime -> Enforcer.BlockReason.Bedtime+ EnforcementReason.Downtime -> Enforcer.BlockReason.Downtime+ EnforcementReason.SchoolTime -> Enforcer.BlockReason.SchoolTime+ EnforcementReason.DailyLimit -> Enforcer.BlockReason.DailyLimit+ EnforcementReason.AppLimit -> Enforcer.BlockReason.AppLimit+}++/**+ * Packages this app has blocked and not yet un-blocked.+ *+ * Persisted so a rule deleted (or an app uninstalled) between reconciles cannot leave the+ * package suspended forever: the next reconcile allows anything recorded here that is no+ * longer meant to be blocked, then stores the new blocked set.+ */+class ManagedPackages(context: Context) {++ private val prefs =+ context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE)++ /** Store [blocked] as the managed set; returns the previously managed packages now stale. */+ fun replace(blocked: Set<String>): Set<String> {+ val previous = prefs.getStringSet(KEY_BLOCKED, emptySet()) ?: emptySet()+ prefs.edit { putStringSet(KEY_BLOCKED, blocked) }+ return previous - blocked+ }++ private companion object {+ const val PREFS = "parentalcontrols_managed"+ const val KEY_BLOCKED = "blocked"+ } } /**@@ -277,13 +370,31 @@ class LimitState(context: Context) { } } + /** Forget a spent mark (a bonus grant reopens the app under its extended budget). */+ fun clearReached(packageName: String) {+ prefs.edit { putStringSet(KEY_REACHED, reached() - packageName) }+ }+ fun hasReached(packageName: String): Boolean = packageName in reached() + /** Every package marked spent today; the decision input for [Enforcer.reconcile]. */+ fun reachedPackages(): Set<String> {+ pruneToToday()+ return reached()+ }++ fun markDeviceReached() = prefs.edit { putBoolean(KEY_DEVICE_REACHED, true) }++ fun clearDeviceReached() = prefs.edit { putBoolean(KEY_DEVICE_REACHED, false) }++ fun hasDeviceReached(): Boolean = prefs.getBoolean(KEY_DEVICE_REACHED, false)+ /** Drop yesterday's trips. This is the daily reset; there is no other. */ fun pruneToToday() { if (prefs.getString(KEY_DAY, null) == today()) return prefs.edit { remove(KEY_REACHED)+ putBoolean(KEY_DEVICE_REACHED, false) putString(KEY_DAY, today()) } }@@ -295,6 +406,7 @@ class LimitState(context: Context) { private companion object { const val PREFS = "parentalcontrols_limits" const val KEY_REACHED = "reached"+ const val KEY_DEVICE_REACHED = "device_reached" const val KEY_DAY = "day" } }
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Receivers.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Receivers.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Receivers.ktindex 777f3e89d6..b6949c8d0e 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Receivers.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/Receivers.kt@@ -57,7 +57,10 @@ class LimitReachedReceiver : BroadcastReceiver() { } } -/** Fired at each supervised-window boundary. Re-arms the next one through [Enforcer]. */+/**+ * Fired at each supervised-window boundary, at midnight, and by the periodic+ * device-limit check. Re-arms the next one through [Enforcer].+ */ class BedtimeReceiver : BroadcastReceiver() { // Broad catch is deliberate: onReceive must not throw, and the enforcer path@@ -65,12 +68,21 @@ class BedtimeReceiver : BroadcastReceiver() { @Suppress("TooGenericExceptionCaught") override fun onReceive(context: Context, intent: Intent) { val app = context.applicationContext+ val periodic = intent.getBooleanExtra(EXTRA_PERIODIC_CHECK, false) val pending = goAsync() CoroutineScope(Dispatchers.IO).launch { try {- // reconcile plus entry notifications for windows that just opened - not a bare- // reconcile, or the child would never learn why apps just closed.- Enforcer(app).onWindowBoundary()+ if (periodic) {+ // Budget check only: a plain reconcile (the device-spent transition is+ // notified inside it), never window-entry notices for a non-boundary.+ Enforcer(app).reconcile()+ } else {+ // reconcile plus entry notifications for windows that just opened - not a+ // bare reconcile, or the child would never learn why apps just closed.+ // The midnight alarm also arrives here: reconcile prunes yesterday's+ // spent marks and re-arms observers for the new day.+ Enforcer(app).onWindowBoundary()+ } } catch (e: Exception) { Log.error(TAG, "window boundary failed", e) } finally {@@ -79,9 +91,56 @@ class BedtimeReceiver : BroadcastReceiver() { } } - /** Intent factory for [BedtimeReceiver]. */+ /** Intent factories for [BedtimeReceiver]. */ companion object { fun intent(context: Context): Intent = Intent(context, BedtimeReceiver::class.java)++ /** The periodic device-limit check intent (see [BedtimeScheduler]). */+ fun periodicIntent(context: Context): Intent =+ Intent(context, BedtimeReceiver::class.java).putExtra(EXTRA_PERIODIC_CHECK, true)+ }+}++/** Extra marking a [BedtimeReceiver] broadcast as the periodic device-limit check. */+const val EXTRA_PERIODIC_CHECK = "com.vayunmathur.parentalcontrols.extra.PERIODIC_CHECK"++/**+ * Fired when the wall clock, date or timezone changes.+ *+ * Window alarms are armed as absolute instants computed in the then-current timezone, and+ * day-scoped state is keyed by local date — so a clock or timezone change (a routine travel+ * event, and also the obvious way for a child with Settings access to try to walk a bedtime+ * backwards) left every armed boundary stale until something else reconciled. Reconciling+ * re-derives windows, re-arms alarms in the new zone and prunes spent marks by the new date.+ * It cannot stop a determined child changing the clock — only removing their Settings+ * access does that, which is a supervision-policy decision for the OS, not this app — but it+ * removes the "change the clock and nothing notices" hole.+ */+class TimeChangedReceiver : BroadcastReceiver() {++ // Broad catch is deliberate: onReceive must not throw.+ @Suppress("TooGenericExceptionCaught")+ override fun onReceive(context: Context, intent: Intent) {+ if (intent.action !in TIME_CHANGE_ACTIONS) return+ val app = context.applicationContext+ val pending = goAsync()+ CoroutineScope(Dispatchers.IO).launch {+ try {+ Enforcer(app).reconcile()+ } catch (e: Exception) {+ Log.error(TAG, "time-change reconcile failed", e)+ } finally {+ pending.finish()+ }+ }+ }++ private companion object {+ val TIME_CHANGE_ACTIONS = setOf(+ Intent.ACTION_TIME_CHANGED,+ Intent.ACTION_TIMEZONE_CHANGED,+ Intent.ACTION_DATE_CHANGED,+ ) } } @@ -99,9 +158,12 @@ class BootReceiver : BroadcastReceiver() { // throws undocumented RuntimeExceptions (not just SQLiteException). @Suppress("TooGenericExceptionCaught") override fun onReceive(context: Context, intent: Intent) {- if (intent.action != Intent.ACTION_BOOT_COMPLETED &&- intent.action != Intent.ACTION_LOCKED_BOOT_COMPLETED- ) {+ // BOOT_COMPLETED only, deliberately not LOCKED_BOOT_COMPLETED: before the first+ // unlock this app's credential-protected storage (the Room rules database and the+ // SharedPreferences state) is unavailable, so a locked-boot reconcile could only+ // fail. BOOT_COMPLETED is delivered after unlock, when enforcement can actually+ // be re-established.+ if (intent.action != Intent.ACTION_BOOT_COMPLETED) { return } val app = context.applicationContext
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionPolicies.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionPolicies.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionPolicies.ktindex 3af2a5339e..42c229096f 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionPolicies.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionPolicies.kt@@ -5,7 +5,6 @@ import android.app.supervision.SupervisionManager import android.content.Context import com.vayunmathur.library.log.Log import androidx.core.content.getSystemService-import java.time.Duration private const val TAG = "ParentalControlsPolicy" @@ -28,41 +27,38 @@ private const val TAG = "ParentalControlsPolicy" * * So [block] and [allow] are what actually gate an app, and the decision of *when* to call them * comes from `UsageStatsManager` observers ([AppLimits]) and from the bedtime alarm- * ([BedtimeScheduler]). [limit] exists to record the parent's intent in the platform's own store- * so it survives us and shows up in `getPolicies`, not because it enforces anything.+ * ([BedtimeScheduler]).+ *+ * There is deliberately no `limit()` writer any more. The previous implementation wrote a+ * `TYPE_TIME_LIMIT` policy *after* the block/allow decision on every reconcile, intending it+ * as a record of the parent's cap. Because the platform suspends on that write, the record+ * replaced the decision: every capped app ended every reconcile suspended, whatever its+ * usage. A policy type that enforces on write cannot be used as a notebook. */ class SupervisionPolicies(context: Context) { private val manager = context.getSystemService<SupervisionManager>() - /** False when the role is unheld or the platform service is missing; nothing will enforce. */- val isAvailable: Boolean get() = manager != null-- fun block(packageName: String) = write(packageName, PackageUsagePolicy.TYPE_BLOCKED)-- fun allow(packageName: String) = write(packageName, PackageUsagePolicy.TYPE_ALLOWED)- /**- * Records the parent's daily cap in the platform policy store.+ * False when nothing will enforce: no platform service, or supervision is not enabled. *- * Enforcement does not follow from this; see the class note. Rejected by the platform above- * 24 h, on a negative duration, and entirely unless the- * `enable_supervision_package_usage_apis` aconfig flag is on - which MAOS enables from- * `build/release/aconfig/cp2a/`.+ * Merely obtaining the manager is not evidence — the service can exist on a build where+ * this app does not hold the supervision role or supervision was never switched on, and+ * then every `setPolicy` is rejected. `isSupervisionEnabled` is the platform's own answer;+ * a probe failure is treated as unavailable rather than optimistic. */- fun limit(packageName: String, minutes: Int) {- val policy = runCatching {- PackageUsagePolicy.Builder(packageName, PackageUsagePolicy.TYPE_TIME_LIMIT)- .setTimeLimit(Duration.ofMinutes(minutes.toLong()))- .build()- }.getOrElse {- // IllegalStateException from performBuild when the flag is off or the duration is- // out of range. Not fatal: the cap still works, because we time it ourselves.- Log.status(TAG, "could not build a time-limit policy for $packageName", it)- return+ val isAvailable: Boolean+ get() {+ val manager = manager ?: return false+ return runCatching { manager.isSupervisionEnabled() }+ .onFailure { Log.status(TAG, "could not probe supervision state", it) }+ .getOrDefault(false) }- set(policy)- }+++ fun block(packageName: String) = write(packageName, PackageUsagePolicy.TYPE_BLOCKED)++ fun allow(packageName: String) = write(packageName, PackageUsagePolicy.TYPE_ALLOWED) private fun write(packageName: String, type: Int) { val policy = runCatching {@@ -83,3 +79,21 @@ class SupervisionPolicies(context: Context) { .onFailure { Log.status(TAG, "setPolicy rejected for ${policy.packageName}", it) } } }++/**+ * Whether supervision enforcement is available on this device, probed reflectively.+ *+ * UI and other host-adjacent code must use this rather than touching [SupervisionPolicies]:+ * `SupervisionManager` is a compile-only stub that does not exist on a stock device (or a+ * host JVM), so loading the class that names it throws instead of answering false. Here a+ * missing class, a missing service and a negative answer all mean the same truthful thing:+ * controls can be configured but nothing will be blocked.+ */+object SupervisionAvailability {++ fun isAvailable(context: Context): Boolean = runCatching {+ val managerClass = Class.forName("android.app.supervision.SupervisionManager")+ val manager = context.getSystemService(managerClass) ?: return false+ managerClass.getMethod("isSupervisionEnabled").invoke(manager) as? Boolean ?: false+ }.getOrDefault(false)+}
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.ktindex 4c2361596f..e51207dd6f 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/platform/SupervisionViewModel.kt@@ -38,12 +38,21 @@ data class SupervisionUiState( val dailyLimitMinutes: Int? = null, val apps: List<SupervisableApp> = emptyList(), val loading: Boolean = true,+ /**+ * Whether the platform will actually enforce any of this (supervision role held and+ * supervision enabled). False on a build without the MAOS supervision plumbing — the+ * dashboard must say so instead of presenting controls that do nothing.+ */+ val enforcementAvailable: Boolean = false, ) /** ViewModel combining supervision rules and installed apps into screen state. */ class SupervisionViewModel(app: Application) : AndroidViewModel(app) { private val rules = SupervisionRules.get(app)+ // Probed on every state emission rather than cached: completing the platform setup+ // flow in another activity must be reflected when the parent lands back here.+ private fun enforcementAvailable(): Boolean = SupervisionAvailability.isAvailable(getApplication()) private val installed = MutableStateFlow<List<Pair<String, String>>>(emptyList()) private val controlsEnabled = MutableStateFlow(SupervisionMaster.isEnabled(app)) @@ -74,6 +83,7 @@ class SupervisionViewModel(app: Application) : AndroidViewModel(app) { dailyLimitMinutes = dailyLimit, apps = apps.map { (pkg, label) -> SupervisableApp(pkg, label, byPackage[pkg]) }, loading = apps.isEmpty(),+ enforcementAvailable = enforcementAvailable(), ) }.stateIn(viewModelScope, SharingStarted.WhileSubscribed(STOP_TIMEOUT_MS), SupervisionUiState())
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardScreen.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardScreen.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardScreen.ktindex 8028ea9246..4b81c648a6 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardScreen.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/DashboardScreen.kt@@ -8,6 +8,7 @@ import androidx.compose.ui.Modifier import androidx.compose.ui.res.stringResource import androidx.compose.ui.unit.dp import com.vayunmathur.library.ui.IconBedtime+import com.vayunmathur.library.ui.IconBook import com.vayunmathur.library.ui.IconGlobe import com.vayunmathur.library.ui.IconHourglass import com.vayunmathur.library.ui.IconKey@@ -26,7 +27,9 @@ data class DashboardActions( val onSetControls: (Boolean) -> Unit, val onOpenDailyLimit: () -> Unit, val onOpenAppLimits: () -> Unit,+ val onOpenBedtime: () -> Unit, val onOpenDowntime: () -> Unit,+ val onOpenSchoolTime: () -> Unit, val onOpenWebFilters: () -> Unit, val onOpenPin: () -> Unit, )@@ -55,6 +58,17 @@ fun DashboardScreen(state: SupervisionUiState, actions: DashboardActions) { } } + if (!state.enforcementAvailable) {+ item {+ SettingsSection {+ SettingsRow(+ title = stringResource(R.string.enforcement_unavailable),+ supportingText = stringResource(R.string.enforcement_unavailable_hint),+ )+ }+ }+ }+ item { SettingsSection { SettingsRow(@@ -69,12 +83,24 @@ fun DashboardScreen(state: SupervisionUiState, actions: DashboardActions) { leadingContent = { IconHourglass() }, onClick = actions.onOpenAppLimits, )+ SettingsRow(+ title = stringResource(R.string.bedtime_title),+ supportingText = bedtimeSummary(state),+ leadingContent = { IconBedtime() },+ onClick = actions.onOpenBedtime,+ ) SettingsRow( title = stringResource(R.string.downtime_title), supportingText = downtimeSummary(state), leadingContent = { IconBedtime() }, onClick = actions.onOpenDowntime, )+ SettingsRow(+ title = stringResource(R.string.school_title),+ supportingText = schoolSummary(state),+ leadingContent = { IconBook() },+ onClick = actions.onOpenSchoolTime,+ ) SettingsRow( title = stringResource(R.string.dashboard_web_filters), supportingText = stringResource(R.string.summary_web_filters),@@ -109,6 +135,22 @@ private fun appLimitsSummary(state: SupervisionUiState): String = stringResource(R.string.summary_no_app_limits) } +@Composable+private fun bedtimeSummary(state: SupervisionUiState): String =+ if (state.schedule.enabled) {+ "${clock(state.schedule.startMinute)} – ${clock(state.schedule.endMinute)}"+ } else {+ stringResource(R.string.summary_off)+ }++@Composable+private fun schoolSummary(state: SupervisionUiState): String =+ if (state.schoolTime.enabled) {+ "${clock(state.schoolTime.startMinute)} – ${clock(state.schoolTime.endMinute)}"+ } else {+ stringResource(R.string.summary_off)+ }+ @Composable private fun downtimeSummary(state: SupervisionUiState): String = if (state.downtime.enabled) {
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.ktindex 93f35d032e..5fde87c817 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/LockActivities.kt@@ -8,10 +8,7 @@ import androidx.activity.compose.setContent import androidx.activity.enableEdgeToEdge import androidx.lifecycle.lifecycleScope import com.vayunmathur.library.ui.DynamicTheme-import com.vayunmathur.parentalcontrols.data.BonusGrant-import com.vayunmathur.parentalcontrols.data.SupervisionRules import com.vayunmathur.parentalcontrols.platform.Enforcer-import java.time.LocalDate import kotlinx.coroutines.Dispatchers import kotlinx.coroutines.launch @@ -72,15 +69,9 @@ abstract class BaseLockActivity : ComponentActivity() { private fun grantBonus() { lifecycleScope.launch(Dispatchers.IO) {- val rules = SupervisionRules.get(this@BaseLockActivity)- rules.grantBonus(- BonusGrant(- packageName = blockedPackage,- bonusMinutes = BONUS_MINUTES,- day = LocalDate.now().toString(),- ),- )- Enforcer(this@BaseLockActivity).reconcile()+ // Enforcer.onBonusGranted also clears the package's spent mark — without that+ // the extended budget was armed but the app stayed blocked (audit fix).+ Enforcer(this@BaseLockActivity).onBonusGranted(blockedPackage, BONUS_MINUTES) finish() } }
parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/NavigationEntries.kt
diff --git a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/NavigationEntries.kt b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/NavigationEntries.ktindex 338cbdd894..8ad5636bc8 100644--- a/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/NavigationEntries.kt+++ b/parentalcontrols/src/main/java/com/vayunmathur/parentalcontrols/ui/NavigationEntries.kt@@ -51,9 +51,15 @@ internal fun EntryProviderScope<Route>.dashboardEntry( onOpenAppLimits = { requestGated(backStack, pin, pinVerified, pendingAfterSetup, PinGateTarget.AppLimits) },+ onOpenBedtime = {+ requestGated(backStack, pin, pinVerified, pendingAfterSetup, PinGateTarget.Bedtime)+ }, onOpenDowntime = { requestGated(backStack, pin, pinVerified, pendingAfterSetup, PinGateTarget.Downtime) },+ onOpenSchoolTime = {+ requestGated(backStack, pin, pinVerified, pendingAfterSetup, PinGateTarget.SchoolTime)+ }, onOpenWebFilters = { requestGated(backStack, pin, pinVerified, pendingAfterSetup, PinGateTarget.WebFilters) },
parentalcontrols/src/main/res/values/strings.xml
diff --git a/parentalcontrols/src/main/res/values/strings.xml b/parentalcontrols/src/main/res/values/strings.xmlindex b57b7320d8..706ccc7509 100644--- a/parentalcontrols/src/main/res/values/strings.xml+++ b/parentalcontrols/src/main/res/values/strings.xml@@ -141,4 +141,8 @@ <string name="daily_explainer_hint">Everything locks once the day\'s budget is used up, and unlocks again at midnight.</string> <!-- Daily limit screen: row showing the current budget. Noun phrase. --> <string name="daily_budget">Daily budget</string>+ <!-- Dashboard: shown when the platform cannot enforce (no supervision role / supervision off). -->+ <string name="enforcement_unavailable">Controls are not enforcing on this device</string>+ <!-- Dashboard: explanation under the not-enforcing notice. -->+ <string name="enforcement_unavailable_hint">This device has not granted this app supervision, so limits and schedules are saved but nothing is blocked. On a supported device, turn on parental controls in Settings first.</string> </resources>
parentalcontrols/src/screenshotTest/kotlin/com/vayunmathur/parentalcontrols/ui/MetadataPreviews.kt
diff --git a/parentalcontrols/src/screenshotTest/kotlin/com/vayunmathur/parentalcontrols/ui/MetadataPreviews.kt b/parentalcontrols/src/screenshotTest/kotlin/com/vayunmathur/parentalcontrols/ui/MetadataPreviews.ktindex 7703101370..95bdec0981 100644--- a/parentalcontrols/src/screenshotTest/kotlin/com/vayunmathur/parentalcontrols/ui/MetadataPreviews.kt+++ b/parentalcontrols/src/screenshotTest/kotlin/com/vayunmathur/parentalcontrols/ui/MetadataPreviews.kt@@ -76,7 +76,9 @@ class MetadataPreviews { onSetControls = {}, onOpenDailyLimit = {}, onOpenAppLimits = {},+ onOpenBedtime = {}, onOpenDowntime = {},+ onOpenSchoolTime = {}, onOpenWebFilters = {}, onOpenPin = {}, )
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/EnforcementTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/EnforcementTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/EnforcementTest.ktnew file mode 100644index 0000000000..665d2ed325--- /dev/null+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/domain/EnforcementTest.kt@@ -0,0 +1,119 @@+package com.vayunmathur.parentalcontrols.domain++import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertNull+import kotlin.test.assertTrue++class EnforcementTest {++ private val launchable = setOf("com.example.game", "com.example.video", "com.example.reader")++ @Test+ fun downtimeBlocksLaunchableAppsWithNoRuleRow() {+ // The pre-fix enforcer iterated only the rules table, so an app the parent+ // had never touched was never blocked by downtime. It must be.+ val plan = decideEnforcement(+ EnforcementInput(launchablePackages = launchable, downtimeActive = true),+ )+ assertEquals(launchable, plan.keys)+ assertTrue(plan.values.all { it == EnforcementReason.Downtime })+ }++ @Test+ fun downtimeAndSchoolExemptOnlyApprovedApps() {+ val rules = listOf(+ AppRestriction("com.example.reader", allowedInDowntime = true),+ AppRestriction("com.example.game", dailyLimitMinutes = 30),+ )+ val downtime = decideEnforcement(+ EnforcementInput(launchable, rules, downtimeActive = true),+ )+ assertNull(downtime["com.example.reader"])+ assertEquals(EnforcementReason.Downtime, downtime["com.example.game"])+ assertEquals(EnforcementReason.Downtime, downtime["com.example.video"])++ val school = decideEnforcement(+ EnforcementInput(launchable, rules, schoolTimeActive = true),+ )+ assertNull(school["com.example.reader"])+ assertEquals(EnforcementReason.SchoolTime, school["com.example.video"])+ }++ @Test+ fun bedtimeBlocksOnlyFlaggedApps() {+ val rules = listOf(AppRestriction("com.example.game", blockedAtBedtime = true))+ val plan = decideEnforcement(+ EnforcementInput(launchable, rules, bedtimeActive = true),+ )+ assertEquals(mapOf("com.example.game" to EnforcementReason.Bedtime), plan)+ }++ @Test+ fun deviceLimitBlocksEveryLaunchableApp() {+ val plan = decideEnforcement(+ EnforcementInput(launchablePackages = launchable, deviceOverBudget = true),+ )+ assertEquals(launchable, plan.keys)+ assertTrue(plan.values.all { it == EnforcementReason.DailyLimit })+ }++ @Test+ fun precedenceIsBedtimeThenDowntimeThenSchoolThenDeviceThenApp() {+ val rules = listOf(+ AppRestriction("com.example.game", blockedAtBedtime = true),+ AppRestriction("com.example.reader", allowedInDowntime = true),+ )+ val all = EnforcementInput(+ launchablePackages = launchable,+ restrictions = rules,+ bedtimeActive = true,+ downtimeActive = true,+ schoolTimeActive = true,+ deviceOverBudget = true,+ reachedPackages = setOf("com.example.video", "com.example.reader"),+ )+ val plan = decideEnforcement(all)+ assertEquals(EnforcementReason.Bedtime, plan["com.example.game"])+ assertEquals(EnforcementReason.Downtime, plan["com.example.video"])+ // Approved for windows but over the device budget: device limit still applies.+ assertEquals(EnforcementReason.DailyLimit, plan["com.example.reader"])++ val noWindows = decideEnforcement(+ all.copy(+ bedtimeActive = false, downtimeActive = false,+ schoolTimeActive = false, deviceOverBudget = false,+ ),+ )+ assertEquals(EnforcementReason.AppLimit, noWindows["com.example.video"])+ assertEquals(EnforcementReason.AppLimit, noWindows["com.example.reader"])+ assertNull(noWindows["com.example.game"])+ }++ @Test+ fun restrictedAppOutsideLaunchableListStaysGoverned() {+ val rules = listOf(AppRestriction("com.example.hidden", blockedAtBedtime = true))+ val plan = decideEnforcement(+ EnforcementInput(launchablePackages = launchable, restrictions = rules, bedtimeActive = true),+ )+ assertEquals(EnforcementReason.Bedtime, plan["com.example.hidden"])+ }++ @Test+ fun nothingActiveBlocksNothing() {+ val rules = listOf(+ AppRestriction("com.example.game", dailyLimitMinutes = 30, blockedAtBedtime = true),+ )+ assertTrue(+ decideEnforcement(EnforcementInput(launchable, rules)).isEmpty(),+ )+ }++ @Test+ fun bonusExtendsBudgetAndSpentTestUsesIt() {+ assertEquals(45, effectiveBudgetMinutes(30, listOf(15)))+ assertEquals(30, effectiveBudgetMinutes(30, emptyList()))+ assertTrue(budgetSpent(usedMinutes = 45, budgetMinutes = 45))+ assertTrue(!budgetSpent(usedMinutes = 44, budgetMinutes = 45))+ }+}
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.ktindex 999b83f42a..1ae64f1884 100644--- a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.kt+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/ParentPinTest.kt@@ -63,6 +63,9 @@ class ParentPinTest { @Test fun parentPinInstancesShareStorageAndShortPinGuard() {+ // Previously this relied on another test having installed the fake+ // keystore provider first — order-dependent and failing standalone.+ FakeAndroidKeyStore.install() val pin = ParentPin.get(app) // No static instance is retained (ParentPin holds a Context); a second instance // reads the same keystore-wrapped verifier and preferences.
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.ktindex b62719ce5c..15ddc5f0f1 100644--- a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.kt+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/platform/PlatformStateTest.kt@@ -74,14 +74,15 @@ class PlatformStateTest { val scheduler = BedtimeScheduler(ctx) val alarmManager = ctx.getSystemService(AlarmManager::class.java) val shadow = shadowOf(alarmManager)- // Disabled schedules cancel and arm nothing.+ // Disabled schedules cancel their window alarms; armAll still arms exactly the+ // midnight reset, which is what makes spent limits reopen the next day. scheduler.arm(BedtimeSchedule(enabled = false)) scheduler.armAll( BedtimeSchedule(enabled = false), DowntimeSchedule(enabled = false), SchoolTimeSchedule(enabled = false), )- assertTrue(shadow.scheduledAlarms.isEmpty())+ assertEquals(1, shadow.scheduledAlarms.size) // An enabled cross-midnight window always has a next boundary within a week. scheduler.arm(BedtimeSchedule(enabled = true)) assertTrue(shadow.scheduledAlarms.isNotEmpty())@@ -96,6 +97,45 @@ class PlatformStateTest { assertTrue(shadow.scheduledAlarms.isNotEmpty()) } + @Test+ fun limitStateClearReachedReopensAfterBonus() {+ val state = LimitState(ctx)+ state.pruneToToday()+ state.markReached("com.example.game")+ assertTrue(state.hasReached("com.example.game"))+ // A bonus grant clears the spent mark so reconcile can reopen the app+ // under its extended budget (previously the mark made bonuses unusable).+ state.clearReached("com.example.game")+ assertFalse(state.hasReached("com.example.game"))+ assertFalse(state.reachedPackages().contains("com.example.game"))+ // Device-spent transition mark: set once, cleared when back under budget,+ // and reset by the day rollover.+ assertFalse(state.hasDeviceReached())+ state.markDeviceReached()+ assertTrue(state.hasDeviceReached())+ state.clearDeviceReached()+ assertFalse(state.hasDeviceReached())+ }++ @Test+ fun bedtimeSchedulerArmsMidnightAndPeriodicCheck() {+ val scheduler = BedtimeScheduler(ctx)+ val alarmManager = ctx.getSystemService(AlarmManager::class.java)+ val shadow = shadowOf(alarmManager)+ val before = shadow.scheduledAlarms.size+ // Even with every window off, the midnight reset must be armed.+ scheduler.armAll(+ BedtimeSchedule(enabled = false),+ DowntimeSchedule(enabled = false),+ SchoolTimeSchedule(enabled = false),+ deviceLimitActive = true,+ )+ assertTrue(+ shadow.scheduledAlarms.size >= before + 2,+ "expected midnight + periodic alarms, got ${shadow.scheduledAlarms.size - before}",+ )+ }+ @Test fun appLimitsWithNoUsageAccessMeasureZero() { val limits = AppLimits(ctx)
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.ktindex 18416416d5..a7916fa9f3 100644--- a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalActivitiesTest.kt@@ -5,6 +5,9 @@ import android.content.Intent import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.junit4.createEmptyComposeRule import androidx.compose.ui.test.onNodeWithText+import androidx.compose.ui.test.onRoot+import androidx.compose.ui.test.performTouchInput+import androidx.compose.ui.test.swipeUp import androidx.compose.ui.test.performClick import androidx.compose.ui.test.performTextInput import androidx.room3.Room@@ -65,6 +68,8 @@ class ParentalActivitiesTest { waitForText("App limits") composeRule.onNodeWithText("App limits").assertIsDisplayed() scenario.onActivity { it.onBackPressedDispatcher.onBackPressed() }+ // Bedtime/downtime/school rows now sit above this one; scroll it into view.+ composeRule.onRoot().performTouchInput { swipeUp() } composeRule.onNodeWithText("Web content filters").performClick() composeRule.onNodeWithText("PIN").performTextInput("1234") composeRule.onNodeWithText("Unlock").performClick()
parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.kt
diff --git a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.kt b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.ktindex 27bfd59d9c..4d272d8aee 100644--- a/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.kt+++ b/parentalcontrols/src/test/java/com/vayunmathur/parentalcontrols/ui/ParentalControlsScreensTest.kt@@ -1,5 +1,6 @@ package com.vayunmathur.parentalcontrols.ui +import androidx.compose.ui.test.assertCountEquals import androidx.compose.ui.test.assertIsDisplayed import androidx.compose.ui.test.assertIsNotEnabled import androidx.compose.ui.test.junit4.createComposeRule@@ -138,7 +139,9 @@ class ParentalControlsScreensTest { onSetControls = { record.add("controls:$it") }, onOpenDailyLimit = { record.add("daily") }, onOpenAppLimits = { record.add("apps") },+ onOpenBedtime = { record.add("bedtime") }, onOpenDowntime = { record.add("downtime") },+ onOpenSchoolTime = { record.add("school") }, onOpenWebFilters = { record.add("web") }, onOpenPin = { record.add("pin") }, )@@ -148,6 +151,7 @@ class ParentalControlsScreensTest { val record = mutableListOf<String>() val state = SupervisionUiState( controlsEnabled = true,+ enforcementAvailable = true, dailyLimitMinutes = 90, downtime = DowntimeSchedule(enabled = true, startMinute = 12 * 60, endMinute = 14 * 60), apps = listOf(SupervisableApp("com.a", "Alpha", AppRule("com.a", dailyLimitMinutes = 30))),@@ -162,20 +166,31 @@ class ParentalControlsScreensTest { rule.onNodeWithText("Daily limit").performClick() rule.onNodeWithText("App limits").performClick() rule.onRoot().performTouchInput { swipeUp() }+ rule.onNodeWithText("Child bedtime").performClick() rule.onNodeWithText("Downtime").performClick()+ rule.onRoot().performTouchInput { swipeUp() }+ rule.onNodeWithText("School time").performClick() rule.onNodeWithText("Web content filters").performClick() rule.onRoot().performTouchInput { swipeUp() } rule.onNodeWithText("Manage your PIN").performClick()- assertEquals(listOf("daily", "apps", "downtime", "web", "pin"), record)+ assertEquals(listOf("daily", "apps", "bedtime", "downtime", "school", "web", "pin"), record) } @Test fun dashboardDefaultsSummaries() { val record = mutableListOf<String>()- rule.setContent { DynamicTheme { DashboardScreen(SupervisionUiState(loading = false), dashboardActions(record)) } }+ rule.setContent {+ DynamicTheme {+ DashboardScreen(+ SupervisionUiState(loading = false, enforcementAvailable = true),+ dashboardActions(record),+ )+ }+ } rule.onNodeWithText("Not set").assertIsDisplayed() rule.onNodeWithText("No app limits").assertIsDisplayed()- rule.onNodeWithText("Off").assertIsDisplayed()+ // Bedtime, downtime and school time each summarise as Off.+ rule.onAllNodesWithText("Off").assertCountEquals(3) rule.onNodeWithText("Controls for this phone").performClick() assertEquals(listOf("controls:false"), record) }