Modern Apps git

← Modern-Apps.git

screentime: editing a spent timer re-evaluates it instead of pausing until midnight

Commit
620d9b4e2631ffdfd6fd6753079148cb7563b506
Author
Vayun Mathur <[email protected]>
When
2026-12-01 09:17 UTC (5 days ago)
Parents
d53a59e
SpentState is keyed only by package, with no notion that the
limit it was earned against changed — and the edit path
never cleared it while delete did. Timer 30 min, app spends
30 min, observer marks it spent and reconcile pauses it;
the user raises the limit to 60 min (30 min of budget
remaining), but setTimer only upserted the row: reconcile
still saw the spent mark, kept the app in timerPaused, and
excluded it from timers.sync so the observer never re-armed.
Paused until the midnight prune despite budget left.

setTimer now clears the package's spent mark after upserting
(before reconciling), so reconcile re-evaluates from current
usage: raised above use -> unpaused and observer re-arms for
the remainder; still at/over the new limit -> register sees
remaining <= 0 and re-marks spent immediately, so exhausted
apps get no free pass (existing enforcement tests pin this).
New regression test failed pre-fix. Midnight bucketing,
wind-down windows and widget state were audited and cleared.
Verified: :screentime:testDevUnitTest 122 tests pass; lint
error is pre-existing on an untouched file.

Diff

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 45138f9444..fa60d50c27 100644--- a/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt+++ b/screentime/src/main/java/com/vayunmathur/screentime/platform/ScreenTimeViewModel.kt@@ -253,6 +253,16 @@ class ScreenTimeViewModel(app: Application) : AndroidViewModel(app) {                 }             } else {                 rules.upsert(AppTimer(packageName, minutes))+                // A changed limit is a new budget for today: the spent mark was+                // earned against the old limit, so clearing it before reconciling+                // lets registration re-evaluate from current usage - an app raised+                // above its use re-arms for what is left, while one still at or+                // over the new limit is enforced again immediately. Keeping the+                // stale mark would leave a raised timer paused until midnight+                // with no observer armed, unlike delete-then-re-add, which clears.+                withContext(Dispatchers.IO) {+                    SpentState(getApplication()).clear(packageName)+                }             }             reconcile()             refresh()
screentime/src/test/java/com/vayunmathur/screentime/platform/SpentTimerEditTest.kt
diff --git a/screentime/src/test/java/com/vayunmathur/screentime/platform/SpentTimerEditTest.kt b/screentime/src/test/java/com/vayunmathur/screentime/platform/SpentTimerEditTest.ktnew file mode 100644index 0000000000..da36b7ac19--- /dev/null+++ b/screentime/src/test/java/com/vayunmathur/screentime/platform/SpentTimerEditTest.kt@@ -0,0 +1,122 @@+package com.vayunmathur.screentime.platform++import android.app.Application+import android.app.usage.UsageStatsManager+import android.content.Context+import androidx.room3.Room+import androidx.test.core.app.ApplicationProvider+import com.vayunmathur.library.util.databases+import com.vayunmathur.screentime.FakeAndroidKeyStore+import com.vayunmathur.screentime.data.AppTimer+import com.vayunmathur.screentime.data.ScreenTimeDatabase+import com.vayunmathur.screentime.data.ScreenTimeRules+import java.time.LocalDate+import java.time.ZoneId+import kotlinx.coroutines.runBlocking+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows+import org.robolectric.annotation.Config+import org.robolectric.shadows.ShadowUsageStatsManager+import kotlin.test.AfterTest+import kotlin.test.BeforeTest+import kotlin.test.Test+import kotlin.test.assertFalse+import kotlin.test.assertTrue++/**+ * Regression: raising a spent timer's limit must give the app its remaining+ * budget back today. The spent mark was earned against the old limit (30 min+ * used of a 30-minute timer); editing to 60 minutes leaves 30 minutes, so the+ * mark must be re-evaluated - not kept until midnight with no observer armed.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class SpentTimerEditTest {++    private val app: Application get() = ApplicationProvider.getApplicationContext()+    private val rules: ScreenTimeRules get() = ScreenTimeRules.get(app)++    @BeforeTest fun setUp() {+        FakeAndroidKeyStore.install()+        resetRulesSingleton()+        app.getSharedPreferences("screentime_spent", Context.MODE_PRIVATE)+            .edit().clear().apply()+        synchronized(databases) {+            runCatching { databases[ScreenTimeDatabase::class]?.close() }+            databases[ScreenTimeDatabase::class] =+                Room.inMemoryDatabaseBuilder(app, ScreenTimeDatabase::class.java)+                    .allowMainThreadQueries().build()+        }+    }++    @AfterTest fun tearDown() {+        resetRulesSingleton()+        synchronized(databases) {+            runCatching { databases[ScreenTimeDatabase::class]?.close() }+            databases.remove(ScreenTimeDatabase::class)+        }+        app.getSharedPreferences("screentime_spent", Context.MODE_PRIVATE)+            .edit().clear().apply()+    }++    private fun resetRulesSingleton() {+        runCatching {+            val field = ScreenTimeRules::class.java.getDeclaredField("instance")+            field.isAccessible = true+            field.set(null, null)+        }+    }++    private fun seedToday(pkg: String, foregroundMs: Long) {+        val start = LocalDate.now().atStartOfDay(ZoneId.systemDefault())+            .toInstant().toEpochMilli()+        val stats = ShadowUsageStatsManager.UsageStatsBuilder.newBuilder()+            .setPackageName(pkg)+            .setFirstTimeStamp(start + 60_000L)+            .setLastTimeStamp(start + 3_600_000L)+            .setTotalTimeInForeground(foregroundMs)+            .build()+        val shadow = Shadows.shadowOf(app.getSystemService(UsageStatsManager::class.java))+        shadow.addUsageStats(UsageStatsManager.INTERVAL_DAILY, stats)+        shadow.addUsageStats(UsageStatsManager.INTERVAL_BEST, stats)+    }++    private fun await(desc: String, cond: () -> Boolean) {+        val deadline = System.currentTimeMillis() + 8_000L+        while (System.currentTimeMillis() < deadline) {+            org.robolectric.shadows.ShadowLooper.idleMainLooper()+            if (runCatching { cond() }.getOrDefault(false)) return+            Thread.sleep(25L)+        }+        throw AssertionError("timed out: $desc")+    }++    @Test fun raisingSpentTimerAboveUsedUnspendsItAndRearmsObserver() {+        val pkg = "com.raised.app"+        // 30 minutes used today, spent against the 30-minute timer.+        seedToday(pkg, 30 * 60_000L)+        runBlocking { rules.upsert(AppTimer(pkg, 30)) }+        val spent = SpentState(app)+        spent.markSpent(pkg)+        assertTrue(spent.hasSpent(pkg))++        // The user raises the limit to 60 minutes: 30 minutes remain today.+        ScreenTimeViewModel(app).setTimer(pkg, 60)++        await("timer raised") {+            runBlocking { rules.timer(pkg) }?.dailyLimitMinutes == 60+        }+        await("spent mark re-evaluated against the new limit") {+            !spent.hasSpent(pkg)+        }+        assertFalse(spent.hasSpent(pkg))+        // Registration must have re-armed for the remaining 30 minutes rather+        // than the timer staying excluded as spent with no observer.+        val shadow = Shadows.shadowOf(app.getSystemService(UsageStatsManager::class.java))+        await("observer re-armed for the raised timer") {+            shadow.registeredAppUsageObservers.isNotEmpty()+        }+        assertTrue(shadow.registeredAppUsageObservers.isNotEmpty())+    }+}