screentime: timers budget what is left; midnight reconcile; restore wind-down
- Commit
e461136a6c0a7dd2d5060b6f82fd06a6b4bc74fe- Author
- Vayun Mathur <[email protected]>
- When
- 2026-11-21 15:42 UTC (15 days ago)
- Parents
23f0e9d
The read path was accurate but the write path had four real bugs. App timers registered their full minute budget instead of budget-minus-already-used, so a partially used app got a fresh budget. Nothing reset state at midnight unless wind-down was on, and timezone changes were unhandled - now a next-midnight reconcile alarm always arms, time-set/timezone receivers reconcile, and dashboard resume reconciles throttled. The day chart keyed usage intervals by package only (multi-activity apps merged) and dropped cross-midnight sessions - intervals now key by (package, class) over a two-day window. Wind-down exit used the current schedule flags, stranding grayscale/DND on when toggled mid-window and clobbering the user's prior state - enter() now persists what it applied and the user's prior values, and exit restores exactly that. Suspender honours the failure array instead of remembering failed packages as paused. Verified: screentime 112 tests pass incl. new write-path tests.
Diff
screentime/src/main/AndroidManifest.xml
diff --git a/screentime/src/main/AndroidManifest.xml b/screentime/src/main/AndroidManifest.xmlindex 8b3f955971..00b67c62ce 100644--- a/screentime/src/main/AndroidManifest.xml+++ b/screentime/src/main/AndroidManifest.xml@@ -153,6 +153,17 @@ android:name=".platform.ScheduleReceiver" android:exported="false" /> + <!-- Time/timezone changes move midnight and wind-down boundaries. -->+ <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>+ <receiver android:name=".platform.BootReceiver" android:exported="true">
screentime/src/main/java/com/vayunmathur/screentime/MainActivity.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/MainActivity.kt b/screentime/src/main/java/com/vayunmathur/screentime/MainActivity.ktindex 270ae52583..395f10257a 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/MainActivity.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/MainActivity.kt@@ -49,7 +49,7 @@ class MainActivity : MaActivity() { override fun onResume() { super.onResume()- viewModel.refresh()+ viewModel.onDashboardResume() } /** Intent actions and extras for launching [MainActivity] screens. */
screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.ktindex 1a50885cde..a0f458fc4e 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/AppTimers.kt@@ -50,7 +50,8 @@ class AppTimers(private val context: Context) { private fun register(usage: UsageStatsManager, packageName: String, minutes: Int) { val method = registerMethod ?: return val usedMs = timeUsedToday(packageName).toMillis()- if (usedMs >= Duration.ofMinutes(minutes.toLong()).toMillis()) {+ val remainingMs = remainingMillis(minutes, usedMs)+ if (remainingMs <= 0L) { // Already over budget - enforce now rather than arming an observer that would // fire immediately with no useful callback context. TimerReachedReceiver.enforceNow(context, packageName)@@ -63,12 +64,14 @@ class AppTimers(private val context: Context) { PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE, ) runCatching {+ // Remaining budget only, at millis precision: registering the full+ // minutes would hand a partially-used app a fresh full budget. method.invoke( usage, observerId(packageName), arrayOf(packageName),- minutes.toLong(),- java.util.concurrent.TimeUnit.MINUTES,+ remainingMs,+ java.util.concurrent.TimeUnit.MILLISECONDS, pending, ) }.onFailure { Log.status(TAG, "could not register an observer for $packageName", it) }@@ -170,3 +173,10 @@ class AppTimers(private val context: Context) { /** The package a [TimerReachedReceiver] broadcast refers to. Ours, not the platform's. */ const val EXTRA_PACKAGE_NAME = "com.vayunmathur.screentime.extra.PACKAGE_NAME"++/**+ * Budget left today: `limitMinutes * 60_000 - usedMs`, floored at 0.+ * Millis precision so a partially-used app does not regain whole minutes.+ */+internal fun remainingMillis(limitMinutes: Int, usedMs: Long): Long =+ (limitMinutes.toLong() * 60_000L - usedMs).coerceAtLeast(0L)
screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.ktindex 0fd2d2a4e7..b162228631 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/Coordinator.kt@@ -60,7 +60,7 @@ class Coordinator(private val context: Context) { // toggles flipped) takes effect without waiting for the next boundary. val winding = windDownSchedule.activeAt(now) if (winding) windDown.enter(windDownSchedule.grayscale, windDownSchedule.doNotDisturb)- else windDown.exit(windDownSchedule.grayscale, windDownSchedule.doNotDisturb)+ else windDown.exit() scheduler.armAll(windDownSchedule)
screentime/src/main/java/com/vayunmathur/screentime/platform/Receivers.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/Receivers.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/Receivers.ktindex 518eb805ee..021792d41d 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/Receivers.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/Receivers.kt@@ -83,6 +83,41 @@ class ScheduleReceiver : BroadcastReceiver() { } } +/**+ * Reconciles when wall-clock time or timezone changes.+ *+ * A timezone/time change moves midnight and every wind-down boundary, and+ * invalidates alarms armed against the old zone. Following [BootReceiver]'s+ * pattern: funnel through [Coordinator.reconcile], which re-prunes spent+ * state, re-arms observers and re-arms alarms (including next-midnight).+ */+class TimeChangedReceiver : BroadcastReceiver() {++ @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(SupervisorJob() + Dispatchers.IO).launch {+ try {+ Coordinator(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,+ )+ }+}+ /** * Re-establishes enforcement after a reboot. *
screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.ktindex 170af7c39d..45138f9444 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt@@ -176,6 +176,22 @@ class ScreenTimeViewModel(app: Application) : AndroidViewModel(app) { refresh() } + @Volatile private var lastReconcileMs: Long = 0L++ /**+ * Dashboard resume: always refresh reads, but reconcile (spent-prune,+ * timer/suspender/wind-down/alarm re-arm) at most once per+ * [RECONCILE_THROTTLE_MS] so a midnight/time change crossed while the+ * dashboard was backgrounded is picked up without re-running the full+ * enforcement pass on every resume.+ */+ fun onDashboardResume(nowMs: Long = System.currentTimeMillis()) {+ refresh()+ if (!shouldReconcile(lastReconcileMs, nowMs, RECONCILE_THROTTLE_MS)) return+ lastReconcileMs = nowMs+ viewModelScope.launch { reconcile() }+ }+ /** Re-reads permission state and usage history; called on resume and after mutations. */ fun refresh() { viewModelScope.launch(Dispatchers.IO) {@@ -277,8 +293,9 @@ class ScreenTimeViewModel(app: Application) : AndroidViewModel(app) { } } - private suspend fun reconcile() = withContext(Dispatchers.IO) {- Coordinator(getApplication()).reconcile()+ private suspend fun reconcile() {+ lastReconcileMs = System.currentTimeMillis()+ withContext(Dispatchers.IO) { Coordinator(getApplication()).reconcile() } } private suspend fun loadLaunchableApps(): List<Pair<String, String>> =@@ -311,5 +328,10 @@ class ScreenTimeViewModel(app: Application) : AndroidViewModel(app) { private companion object { const val STOP_TIMEOUT_MS = 5_000L+ const val RECONCILE_THROTTLE_MS = 30_000L } }++/** Whether a throttled reconcile is due; a backwards clock (time change) is always due. */+internal fun shouldReconcile(lastMs: Long, nowMs: Long, throttleMs: Long): Boolean =+ lastMs == 0L || nowMs < lastMs || nowMs - lastMs >= throttleMs
screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.ktindex 8b5c456027..6518242e55 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/Suspender.kt@@ -53,8 +53,16 @@ class Suspender(private val context: Context) { // 5-arg overload: (String[], boolean, PersistableBundle, PersistableBundle, // SuspendDialogInfo). Null extras and null dialog: the platform shows its default // paused treatment, whose details button resolves to our AppDetails route.- method.invoke(pm, packages, suspended, null, null, null)- if (suspended) rememberPaused(packages.toSet()) else forgetPaused(packages.toSet())+ // It returns the packages it could NOT change; honour that — remembering+ // a failed suspend as paused (or forgetting a failed resume) would lie+ // to the next sync about what the platform actually holds.+ val result = method.invoke(pm, packages, suspended, null, null, null)+ val failed = (result as? Array<*>)?.mapNotNull { it as? String }?.toSet().orEmpty()+ if (failed.isNotEmpty()) {+ Log.status(TAG, "setPackagesSuspended failed for $failed (suspended=$suspended)")+ }+ val succeeded = packages.toSet() - failed+ if (suspended) rememberPaused(succeeded) else forgetPaused(succeeded) }.onFailure { Log.status(TAG, "could not set suspended=$suspended for ${packages.toList()}", it) } }
screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.ktindex c5e6885e17..00706ac582 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/UsageHistory.kt@@ -106,7 +106,11 @@ class UsageHistory(private val context: Context) { val hours = LongArray(HOURS_PER_DAY) if (end > dayStart) {- for ((pkg, from, to) in foregroundIntervals(usage, dayStart, end)) {+ // Query one day back so a session that crossed midnight (resumed+ // yesterday, paused today) is seen; buildIntervals clips it to+ // [dayStart, end).+ val queryStart = anchor.minusDays(1).atStartOfDay(zone).toInstant().toEpochMilli()+ for ((pkg, from, to) in foregroundIntervals(usage, queryStart, dayStart, end)) { if (forPackage != null && pkg != forPackage) continue HourBuckets.addInterval(hours, dayStart, dayEnd, from, to) }@@ -143,67 +147,30 @@ class UsageHistory(private val context: Context) { @Suppress("DEPRECATION") // MOVE_TO_* still fires on some builds; handled alongside ACTIVITY_*. private fun foregroundIntervals( usage: UsageStatsManager,+ queryStart: Long, start: Long, end: Long, ): List<Triple<String, Long, Long>> {- val events = runCatching { usage.queryEvents(start, end) }.getOrElse {+ val events = runCatching { usage.queryEvents(queryStart, end) }.getOrElse { Log.status(TAG, "no usage events; is PACKAGE_USAGE_STATS granted?", it) return emptyList() }- val open = HashMap<String, Long>()- val intervals = ArrayList<Triple<String, Long, Long>>()+ val raw = ArrayList<FgEvent>() val event = UsageEvents.Event() while (events.hasNextEvent()) { events.getNextEvent(event)- applyEvent(event, open, intervals, start, end)- }- // Anything still foreground at the window edge is closed there.- open.forEach { (pkg, from) -> intervals.add(Triple(pkg, from, end)) }- return intervals- }-- @Suppress("DEPRECATION")- private fun applyEvent(- event: UsageEvents.Event,- open: HashMap<String, Long>,- intervals: ArrayList<Triple<String, Long, Long>>,- start: Long,- end: Long,- ) {- val pkg = event.packageName ?: return- val stamp = event.timeStamp- // queryEvents may return events outside the requested window on some builds.- // A foreground that began before [start] means the app was already in front at- // midnight, so open it there (e.g. overnight sessions count from midnight, not- // from yesterday); anything else out of window is dropped so another day's- // usage can never land in this day's buckets.- if (stamp > end) return- val atEdge = stamp < start- when (event.eventType) {- UsageEvents.Event.MOVE_TO_FOREGROUND, UsageEvents.Event.ACTIVITY_RESUMED -> {- if (atEdge) open.putIfAbsent(pkg, start) else open.putIfAbsent(pkg, stamp)+ val pkg = event.packageName ?: continue+ val isResume = when (event.eventType) {+ UsageEvents.Event.MOVE_TO_FOREGROUND, UsageEvents.Event.ACTIVITY_RESUMED -> true+ UsageEvents.Event.MOVE_TO_BACKGROUND,+ UsageEvents.Event.ACTIVITY_PAUSED,+ UsageEvents.Event.ACTIVITY_STOPPED,+ -> false+ else -> continue }- UsageEvents.Event.MOVE_TO_BACKGROUND,- UsageEvents.Event.ACTIVITY_PAUSED,- UsageEvents.Event.ACTIVITY_STOPPED,- -> closeInterval(open, intervals, pkg, stamp, atEdge)- }- }-- private fun closeInterval(- open: HashMap<String, Long>,- intervals: ArrayList<Triple<String, Long, Long>>,- pkg: String,- stamp: Long,- atEdge: Boolean,- ) {- if (atEdge) {- open.remove(pkg)- return- }- open.remove(pkg)?.let { from ->- if (stamp > from) intervals.add(Triple(pkg, from, stamp))+ raw.add(FgEvent(pkg, event.className.orEmpty(), isResume, event.timeStamp)) }+ return buildIntervals(raw, start, end) } private fun hourLabel(hour: Int): String = when {@@ -220,3 +187,48 @@ class UsageHistory(private val context: Context) { const val NOON_HOUR = 12 } }++/** One foreground/background transition, decoupled from [UsageEvents.Event] for testing. */+internal data class FgEvent(+ val packageName: String,+ val className: String,+ val isResume: Boolean,+ val timeStamp: Long,+)++/**+ * Reconstructs (package, startMs, endMs) intervals in [start, end) from [events].+ *+ * Open intervals are keyed by (package, class): keying by package alone merges+ * a multi-activity app's overlapping activities — the first activity's pause+ * would close the second's session and its later pause would be dropped.+ * Events before [start] (the caller queries one day back) open at [start] if+ * still foreground then, so cross-midnight sessions count from midnight; a+ * pause before [start] cancels such a provisional open.+ */+internal fun buildIntervals(+ events: List<FgEvent>,+ start: Long,+ end: Long,+): List<Triple<String, Long, Long>> {+ val open = HashMap<Pair<String, String>, Long>()+ val intervals = ArrayList<Triple<String, Long, Long>>()+ for (event in events.sortedBy { it.timeStamp }) {+ if (event.timeStamp > end) continue+ val key = event.packageName to event.className+ val atEdge = event.timeStamp < start+ if (event.isResume) {+ open.putIfAbsent(key, if (atEdge) start else event.timeStamp)+ } else if (atEdge) {+ open.remove(key)+ } else {+ open.remove(key)?.let { from ->+ if (event.timeStamp > from) {+ intervals.add(Triple(event.packageName, from, event.timeStamp))+ }+ }+ }+ }+ open.forEach { (key, from) -> intervals.add(Triple(key.first, from, end)) }+ return intervals+}
screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.ktindex 1d3e085b79..b8376a7a32 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindDownApplier.kt@@ -4,6 +4,7 @@ import android.app.NotificationManager import android.content.Context import android.provider.Settings import com.vayunmathur.library.log.Log+import androidx.core.content.edit import androidx.core.content.getSystemService private const val TAG = "ScreenTimeWindDown"@@ -23,66 +24,120 @@ private const val TAG = "ScreenTimeWindDown" * grants the policy access once, after which schedules toggle it directly through * `NotificationManager`. If access was never granted, wind-down still grayscales - a missing * quiet mode must never block the visible half.+ *+ * Applied-state: [enter] persists exactly what it changed plus the user's+ * prior daltonizer/DND values. [exit] restores that persisted record — never+ * the schedule's *current* flags — so toggling grayscale/DND off mid-window+ * cannot strand them ON, and a user who already had grayscale/DND on before+ * wind-down gets that state back instead of having it clobbered off. */ class WindDownApplier(private val context: Context) { private val notifications = context.getSystemService<NotificationManager>()+ private val prefs+ get() = context.applicationContext.getSharedPreferences(PREFS, Context.MODE_PRIVATE) /** Enter wind-down: grayscale on (if configured), DND on (if configured and allowed). */ fun enter(grayscale: Boolean, doNotDisturb: Boolean) {- if (grayscale) setGrayscale(true)- if (doNotDisturb) setDnd(true)+ if (grayscale) applyGrayscale() else if (appliedGrayscale()) restoreGrayscale()+ if (doNotDisturb) applyDnd() else if (appliedDnd()) restoreDnd() } - /** Leave wind-down: restore exactly what [enter] changed, nothing else. */- fun exit(grayscale: Boolean, doNotDisturb: Boolean) {- if (grayscale) setGrayscale(false)- if (doNotDisturb) setDnd(false)+ /** Leave wind-down: restore exactly what [enter] applied, nothing else. */+ fun exit() {+ if (appliedGrayscale()) restoreGrayscale()+ if (appliedDnd()) restoreDnd() } - private fun setGrayscale(on: Boolean) {+ private fun appliedGrayscale(): Boolean = prefs.getBoolean(KEY_APPLIED_GRAYSCALE, false)+ private fun appliedDnd(): Boolean = prefs.getBoolean(KEY_APPLIED_DND, false)++ private fun applyGrayscale() {+ if (appliedGrayscale()) return // keep the original prior values val resolver = context.contentResolver+ val priorEnabled = runCatching {+ Settings.Secure.getInt(resolver, DALTONIZER_ENABLED, 0)+ }.getOrDefault(0)+ val priorMode = runCatching {+ Settings.Secure.getString(resolver, DALTONIZER_MODE)+ }.getOrNull() runCatching {- // String keys, not Settings.Secure constants: the daltonizer constants are absent- // from this SDK's Settings.Secure, and the keys are stable AOSP surface.- Settings.Secure.putInt(- resolver,- "accessibility_display_daltonizer_enabled",- if (on) 1 else 0,- )- if (on) {- Settings.Secure.putString(- resolver,- "accessibility_display_daltonizer_mode",- daltonizerMode(),- )+ Settings.Secure.putInt(resolver, DALTONIZER_ENABLED, 1)+ Settings.Secure.putString(resolver, DALTONIZER_MODE, MONOCHROMACY_MODE)+ }.onSuccess {+ prefs.edit {+ putBoolean(KEY_APPLIED_GRAYSCALE, true)+ putInt(KEY_PRIOR_DALTONIZER_ENABLED, priorEnabled)+ if (priorMode != null) putString(KEY_PRIOR_DALTONIZER_MODE, priorMode)+ else remove(KEY_PRIOR_DALTONIZER_MODE) }- }.onFailure { Log.status(TAG, "could not set grayscale=$on", it) }+ }.onFailure { Log.status(TAG, "could not set grayscale=true", it) } } - /**- * The daltonizer mode value for full monochromacy.- *- * This is always the documented monochromacy constant: wind-down grayscale must- * desaturate fully, not reapply whatever transform the key currently holds.- */- private fun daltonizerMode(): String = MONOCHROMACY_MODE+ private fun restoreGrayscale() {+ val resolver = context.contentResolver+ val priorEnabled = prefs.getInt(KEY_PRIOR_DALTONIZER_ENABLED, 0)+ val priorMode = prefs.getString(KEY_PRIOR_DALTONIZER_MODE, null)+ runCatching {+ Settings.Secure.putInt(resolver, DALTONIZER_ENABLED, priorEnabled)+ if (priorMode != null) Settings.Secure.putString(resolver, DALTONIZER_MODE, priorMode)+ }.onSuccess {+ prefs.edit {+ putBoolean(KEY_APPLIED_GRAYSCALE, false)+ remove(KEY_PRIOR_DALTONIZER_ENABLED)+ remove(KEY_PRIOR_DALTONIZER_MODE)+ }+ }.onFailure { Log.status(TAG, "could not restore grayscale", it) }+ } - private fun setDnd(on: Boolean) {+ private fun applyDnd() {+ if (appliedDnd()) return val nm = notifications ?: return if (!nm.isNotificationPolicyAccessGranted) { Log.status(TAG, "no DND policy access; skipping DND change") return }- runCatching {- nm.setInterruptionFilter(- if (on) NotificationManager.INTERRUPTION_FILTER_PRIORITY- else NotificationManager.INTERRUPTION_FILTER_ALL,- )- }.onFailure { Log.status(TAG, "could not set DND=$on", it) }+ val prior = nm.currentInterruptionFilter+ runCatching { nm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_PRIORITY) }+ .onSuccess {+ prefs.edit {+ putBoolean(KEY_APPLIED_DND, true)+ putInt(KEY_PRIOR_FILTER, prior)+ }+ }+ .onFailure { Log.status(TAG, "could not set DND=true", it) }+ }++ private fun restoreDnd() {+ val nm = notifications ?: run {+ Log.status(TAG, "no NotificationManager; cannot restore DND")+ return+ }+ val prior = prefs.getInt(KEY_PRIOR_FILTER, NotificationManager.INTERRUPTION_FILTER_ALL)+ // Do not gate on isNotificationPolicyAccessGranted: access revoked+ // mid-window must not strand DND on. Attempt the restore anyway;+ // failure is logged and the applied flag is kept so the next+ // reconcile retries.+ runCatching { nm.setInterruptionFilter(prior) }+ .onSuccess {+ prefs.edit {+ putBoolean(KEY_APPLIED_DND, false)+ remove(KEY_PRIOR_FILTER)+ }+ }+ .onFailure { Log.status(TAG, "could not restore DND to $prior (policy access=${nm.isNotificationPolicyAccessGranted})", it) } } private companion object {+ const val PREFS = "screentime_winddown_applied"+ const val KEY_APPLIED_GRAYSCALE = "applied_grayscale"+ const val KEY_APPLIED_DND = "applied_dnd"+ const val KEY_PRIOR_DALTONIZER_ENABLED = "prior_daltonizer_enabled"+ const val KEY_PRIOR_DALTONIZER_MODE = "prior_daltonizer_mode"+ const val KEY_PRIOR_FILTER = "prior_filter"+ const val DALTONIZER_ENABLED = "accessibility_display_daltonizer_enabled"+ const val DALTONIZER_MODE = "accessibility_display_daltonizer_mode"+ /** `AccessibilityManager` monochromacy mode. Documented AOSP value. */ const val MONOCHROMACY_MODE = "0" }
screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt
diff --git a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.ktindex 2f38a92dc3..bdb488ace4 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/WindowScheduler.kt@@ -30,6 +30,22 @@ class WindowScheduler(private val context: Context) { fun armAll(windDown: WindDownSchedule) { armWindow(windDown.enabled, windDown::activeAt, REQUEST_WINDDOWN)+ armMidnight()+ }++ /**+ * Daily reconcile at next local midnight, regardless of wind-down.+ *+ * Timers/spent marks/day totals only reset when [Coordinator.reconcile]+ * runs (it prunes [SpentState] to today and re-arms observers). Without+ * this, a device with wind-down off would keep yesterday's spent pauses+ * until some unrelated reconcile happened.+ */+ private fun armMidnight() {+ val alarms = alarms ?: return+ val pending = pendingIntent(REQUEST_MIDNIGHT)+ alarms.cancel(pending)+ armAlarm(alarms, nextMidnight(ZonedDateTime.now(ZoneId.systemDefault())).toInstant().toEpochMilli(), pending) } private fun armWindow(@@ -43,7 +59,10 @@ class WindowScheduler(private val context: Context) { if (!enabled) return val next = nextBoundary(activeAt) ?: return- val at = next.toInstant().toEpochMilli()+ armAlarm(alarms, next.toInstant().toEpochMilli(), pending)+ }++ private fun armAlarm(alarms: AlarmManager, at: Long, pending: PendingIntent) { val canExact = alarms.canScheduleExactAlarms() runCatching { if (canExact) {@@ -85,10 +104,15 @@ class WindowScheduler(private val context: Context) { private companion object { const val REQUEST_WINDDOWN = 12+ const val REQUEST_MIDNIGHT = 13 const val MINUTES_IN_WEEK = 7 * 24 * 60 } } +/** Next local midnight strictly after [from] (start of the next calendar day in its zone). */+internal fun nextMidnight(from: ZonedDateTime): ZonedDateTime =+ from.toLocalDate().plusDays(1).atStartOfDay(from.zone)+ /** Whether wind-down is active at [at], in the device's current timezone. */ fun WindDownSchedule.activeAt(at: LocalDateTime): Boolean { if (!enabled) return false
screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.ktindex 4148a8ce35..f85d9264a3 100644--- a/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.kt+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformDeepTest.kt@@ -114,37 +114,38 @@ class PlatformDeepTest { "0", Settings.Secure.getString(ctx.contentResolver, "accessibility_display_daltonizer_mode"), )- applier.exit(grayscale = true, doNotDisturb = false)+ applier.exit() assertEquals( 0, Settings.Secure.getInt(ctx.contentResolver, "accessibility_display_daltonizer_enabled", 1), ) // Without policy access, DND calls are a no-op rather than a crash. applier.enter(grayscale = false, doNotDisturb = true)- applier.exit(grayscale = false, doNotDisturb = true)+ applier.exit() val nm = ctx.getSystemService(NotificationManager::class.java) Shadows.shadowOf(nm).setNotificationPolicyAccessGranted(true) applier.enter(grayscale = false, doNotDisturb = true) assertEquals(NotificationManager.INTERRUPTION_FILTER_PRIORITY, nm.currentInterruptionFilter)- applier.exit(grayscale = false, doNotDisturb = true)+ applier.exit() assertEquals(NotificationManager.INTERRUPTION_FILTER_ALL, nm.currentInterruptionFilter) Shadows.shadowOf(nm).setNotificationPolicyAccessGranted(false) } - @Test fun windowSchedulerArmsOnlyWhenEnabled() {+ @Test fun windowSchedulerArmsMidnightEvenWhenWindDownDisabled() { val alarms = ctx.getSystemService(AlarmManager::class.java) val shadow = Shadows.shadowOf(alarms) val scheduler = WindowScheduler(ctx)+ // Daily reconcile is armed regardless of wind-down. scheduler.armAll(WindDownSchedule(enabled = false))- assertEquals(null, shadow.nextScheduledAlarm)+ assertNotNull(shadow.nextScheduledAlarm) scheduler.armAll( WindDownSchedule(enabled = true, startMinute = 22 * 60, endMinute = 7 * 60), ) assertNotNull(shadow.nextScheduledAlarm)- // Re-arming replaces rather than stacks; disabling cancels outright.+ // Disabling wind-down cancels its boundary but keeps the midnight alarm. scheduler.armAll(WindDownSchedule(enabled = false))- assertEquals(null, shadow.nextScheduledAlarm)+ assertNotNull(shadow.nextScheduledAlarm) } @Test fun rulesFlowGettersAreColdAndSingletonIsStable() {
screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformServicesTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformServicesTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformServicesTest.ktindex 4fd8299a08..a31f0b56d9 100644--- a/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformServicesTest.kt+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/PlatformServicesTest.kt@@ -73,8 +73,8 @@ class PlatformServicesTest { @Test fun windDownApplier_enterExit() { val applier = WindDownApplier(ctx()) applier.enter(grayscale = true, doNotDisturb = true)- applier.exit(grayscale = true, doNotDisturb = true)+ applier.exit() applier.enter(grayscale = false, doNotDisturb = false)- applier.exit(grayscale = false, doNotDisturb = false)+ applier.exit() } }
screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.ktindex e84c06c71e..6efe85bc81 100644--- a/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.kt+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/UsageHistoryDeepTest.kt@@ -113,6 +113,18 @@ class UsageHistoryDeepTest { assertEquals(1_800_000L / 24, forA.averageMillis) } + @Test fun dayCountsSessionCrossingMidnightFromPreviousDay() {+ val day = LocalDate.now().minusDays(1)+ val start = dayStart(day)+ // Resumed 23:00 the previous day, paused 00:30 on `day`: only the+ // post-midnight half (30 min in hour 0) belongs to `day`.+ shadow.addEvent("com.cross.app", start - 3_600_000, UsageEvents.Event.ACTIVITY_RESUMED)+ shadow.addEvent("com.cross.app", start + 1_800_000, UsageEvents.Event.ACTIVITY_PAUSED)+ val data = UsageHistory(ctx).forPackage(UsagePeriod.Day, day, "com.cross.app")+ assertEquals(1_800_000L, data.bars[0].millis, "bars=${data.bars}")+ assertEquals(1_800_000L, data.totalMillis)+ }+ @Test fun dayForYesterdayWithNoEventsIsZeroed() { val data = UsageHistory(ctx).aggregate(UsagePeriod.Day, LocalDate.now().minusDays(1)) assertEquals(24, data.bars.size)
screentime/src/test/java/com/vayunmathur/screentime/platform/WritePathFixesTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/WritePathFixesTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/WritePathFixesTest.ktnew file mode 100644index 0000000000..2892024b2b--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/WritePathFixesTest.kt@@ -0,0 +1,144 @@+package com.vayunmathur.screentime.platform++import android.app.NotificationManager+import android.content.Context+import android.provider.Settings+import androidx.test.core.app.ApplicationProvider+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import java.time.ZoneId+import java.time.ZonedDateTime+import kotlin.test.Test+import kotlin.test.assertEquals+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/** Regression tests for the write-path review fixes (timers, wind-down, intervals, reconcile). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class WritePathFixesTest {++ private val ctx: Context get() = ApplicationProvider.getApplicationContext()++ // --- Timer remainder (item 2) ---++ @Test fun remainingIsFullBudgetWhenUnused() {+ assertEquals(60 * 60_000L, remainingMillis(60, 0L))+ }++ @Test fun remainingSubtractsUsedAtMillisPrecision() {+ assertEquals(60 * 60_000L - 90_500L, remainingMillis(60, 90_500L))+ assertEquals(1L, remainingMillis(1, 59_999L))+ }++ @Test fun remainingFloorsAtZeroWhenExhaustedOrOver() {+ assertEquals(0L, remainingMillis(30, 30 * 60_000L))+ assertEquals(0L, remainingMillis(30, 31 * 60_000L))+ assertEquals(0L, remainingMillis(0, 0L))+ }++ // --- Next-midnight + throttled reconcile (item 1) ---++ @Test fun nextMidnightIsStartOfNextDay() {+ val zone = ZoneId.of("America/New_York")+ val from = ZonedDateTime.of(2026, 11, 21, 15, 30, 0, 0, zone)+ assertEquals(ZonedDateTime.of(2026, 11, 22, 0, 0, 0, 0, zone), nextMidnight(from))+ val atMidnight = ZonedDateTime.of(2026, 11, 21, 0, 0, 0, 0, zone)+ assertEquals(ZonedDateTime.of(2026, 11, 22, 0, 0, 0, 0, zone), nextMidnight(atMidnight))+ }++ @Test fun shouldReconcileHonoursThrottleAndClockChanges() {+ assertTrue(shouldReconcile(0L, 1_000L, 30_000L))+ assertFalse(shouldReconcile(1_000L, 20_000L, 30_000L))+ assertTrue(shouldReconcile(1_000L, 31_000L, 30_000L))+ assertTrue(shouldReconcile(50_000L, 10_000L, 30_000L)) // clock went backwards+ }++ // --- Interval keying (item 3) ---++ @Test fun intervalsKeyByPackageAndClass() {+ val events = listOf(+ FgEvent("com.multi", "A", isResume = true, timeStamp = 0L),+ FgEvent("com.multi", "B", isResume = true, timeStamp = 10_000L),+ FgEvent("com.multi", "A", isResume = false, timeStamp = 20_000L),+ FgEvent("com.multi", "B", isResume = false, timeStamp = 40_000L),+ )+ val intervals = buildIntervals(events, start = 0L, end = 100_000L)+ assertEquals(+ listOf(+ Triple("com.multi", 0L, 20_000L),+ Triple("com.multi", 10_000L, 40_000L),+ ),+ intervals,+ )+ }++ @Test fun intervalsCrossMidnightOpenAtWindowStart() {+ val events = listOf(+ // Fully before the window: opens provisionally, cancelled by its pause.+ FgEvent("com.old", "A", isResume = true, timeStamp = 100L),+ FgEvent("com.old", "A", isResume = false, timeStamp = 200L),+ // Crossed midnight: resumed before, paused inside.+ FgEvent("com.cross", "A", isResume = true, timeStamp = 500L),+ FgEvent("com.cross", "A", isResume = false, timeStamp = 1_500L),+ // Still foreground at the end: closed at the edge.+ FgEvent("com.open", "A", isResume = true, timeStamp = 1_800L),+ )+ val intervals = buildIntervals(events, start = 1_000L, end = 2_000L)+ assertEquals(+ setOf(+ Triple("com.cross", 1_000L, 1_500L),+ Triple("com.open", 1_800L, 2_000L),+ ),+ intervals.toSet(),+ )+ }++ // --- Wind-down applied-state restore (item 4) ---++ @Test fun windDownExitRestoresPriorGrayscaleNotOff() {+ ctx.getSharedPreferences("screentime_winddown_applied", Context.MODE_PRIVATE)+ .edit().clear().apply()+ val resolver = ctx.contentResolver+ Settings.Secure.putInt(resolver, "accessibility_display_daltonizer_enabled", 1)+ Settings.Secure.putString(resolver, "accessibility_display_daltonizer_mode", "2")+ val applier = WindDownApplier(ctx)+ applier.enter(grayscale = true, doNotDisturb = false)+ assertEquals("0", Settings.Secure.getString(resolver, "accessibility_display_daltonizer_mode"))+ // Exit takes no schedule flags: even if grayscale was toggled off in+ // the schedule mid-window, the prior user state (on, mode 2) returns.+ applier.exit()+ assertEquals(1, Settings.Secure.getInt(resolver, "accessibility_display_daltonizer_enabled", 0))+ assertEquals("2", Settings.Secure.getString(resolver, "accessibility_display_daltonizer_mode"))+ }++ @Test fun windDownExitRestoresPriorDndEvenIfPolicyRevokedMidWindow() {+ ctx.getSharedPreferences("screentime_winddown_applied", Context.MODE_PRIVATE)+ .edit().clear().apply()+ val nm = ctx.getSystemService(NotificationManager::class.java)+ val shadow = Shadows.shadowOf(nm)+ shadow.setNotificationPolicyAccessGranted(true)+ nm.setInterruptionFilter(NotificationManager.INTERRUPTION_FILTER_NONE)+ val applier = WindDownApplier(ctx)+ applier.enter(grayscale = false, doNotDisturb = true)+ assertEquals(NotificationManager.INTERRUPTION_FILTER_PRIORITY, nm.currentInterruptionFilter)+ shadow.setNotificationPolicyAccessGranted(false)+ applier.exit()+ assertEquals(NotificationManager.INTERRUPTION_FILTER_NONE, nm.currentInterruptionFilter)+ shadow.setNotificationPolicyAccessGranted(false)+ }++ @Test fun windDownReEnterDoesNotOverwritePriorValues() {+ ctx.getSharedPreferences("screentime_winddown_applied", Context.MODE_PRIVATE)+ .edit().clear().apply()+ val resolver = ctx.contentResolver+ Settings.Secure.putInt(resolver, "accessibility_display_daltonizer_enabled", 0)+ val applier = WindDownApplier(ctx)+ applier.enter(grayscale = true, doNotDisturb = false)+ applier.enter(grayscale = true, doNotDisturb = false) // re-enter must keep prior=0+ applier.exit()+ assertEquals(0, Settings.Secure.getInt(resolver, "accessibility_display_daltonizer_enabled", 1))+ }+}