fix(#459): review round 3 — two-week cap, one-off offsets for single occurrences, one summary per listed day, commit from the picker's actions

This commit is contained in:
makiolaj committed 2026-11-13 18:27:52 +01:00
1 parent 741e1e9a65
commit c353ac8072
15 files changed
+115 -64

No files matched your search

@@ -1236,8 +1236,9 @@ class AndroidCalendarDataSource @Inject constructor(
)
}
// Whether the provider copied the parent's reminder rows is its
// business — reconciling against the actual rows handles both ways.
reconcileReminders(exceptionId, encodedReminders(form, allDayReminderTimeMinutes))
// business — reconciling against the actual rows handles both ways. The
// exception is a one-off, so a fixed-time reminder takes real minutes.
reconcileReminders(exceptionId, encodedReminders(form.toDetachedOccurrence(), allDayReminderTimeMinutes))
reconcileAttendees(exceptionId, form.attendees)
return exceptionId
}
@@ -4,6 +4,8 @@ import androidx.datastore.core.DataStore
import androidx.datastore.preferences.core.Preferences
import de.jeanlucmakiola.floret.prefs.PrefStore
import de.jeanlucmakiola.floret.prefs.nullableLongPref
import de.jeanlucmakiola.floret.prefs.nullableStringPref
import java.time.LocalDate
import javax.inject.Inject
import javax.inject.Singleton
@@ -28,15 +30,17 @@ class ReminderStatePrefs @Inject constructor(
suspend fun setLastScanMillis(millis: Long) = prefs.set(LAST_SCAN, millis)
/**
* The moment of the last daily summary posted (#459): recorded at once, so a
* pass failing after posting can't post it again before the watermark moves.
* The day the last daily summary listed (#459): recorded at once, so neither
* a pass failing after posting nor a later time picked the same evening
* lists it twice.
*/
suspend fun lastDigestMillis(): Long = prefs.get(LAST_DIGEST) ?: 0L
suspend fun lastDigestDay(): LocalDate? =
prefs.get(LAST_DIGEST_DAY)?.let { runCatching { LocalDate.parse(it) }.getOrNull() }
suspend fun setLastDigestMillis(millis: Long) = prefs.set(LAST_DIGEST, millis)
suspend fun setLastDigestDay(day: LocalDate) = prefs.set(LAST_DIGEST_DAY, day.toString())
private companion object {
val LAST_SCAN = nullableLongPref("reminder_last_scan_millis")
val LAST_DIGEST = nullableLongPref("reminder_last_digest_millis")
val LAST_DIGEST_DAY = nullableStringPref("reminder_last_digest_day")
}
}
@@ -351,7 +351,8 @@ class SettingsPrefs @Inject constructor(
/** The replaced default stays a known pattern, so events that got it keep reading as it. */
suspend fun setDefaultFixedTimeReminder(reminder: FixedTimeReminder?) {
prefs.edit {
retireFixedTimeReminder(it, it[SettingsKeys.defaultFixedTimeReminder])
val old = it[SettingsKeys.defaultFixedTimeReminder]
if (old != reminder) retireFixedTimeReminder(it, old)
it[SettingsKeys.defaultFixedTimeReminder] = reminder
}
}
@@ -360,7 +361,8 @@ class SettingsPrefs @Inject constructor(
suspend fun setCalendarFixedTimeReminderOverride(calendarId: Long, override: FixedTimeOverride) {
prefs.edit {
val current = it[SettingsKeys.perCalendarFixedTimeReminderOverride]
retireFixedTimeReminder(it, current[calendarId])
val old = current[calendarId]
if (old != (override as? FixedTimeOverride.At)?.reminder) retireFixedTimeReminder(it, old)
it[SettingsKeys.perCalendarFixedTimeReminderOverride] = when (override) {
FixedTimeOverride.Inherit -> current - calendarId
FixedTimeOverride.Off -> current + (calendarId to null)
@@ -384,8 +386,12 @@ class SettingsPrefs @Inject constructor(
}
}
/** Keep a default being replaced known, unless it still is a default elsewhere. */
private fun retireFixedTimeReminder(preferences: MutablePreferences, reminder: FixedTimeReminder?) {
if (reminder == null) return
val defaults = listOfNotNull(preferences[SettingsKeys.defaultFixedTimeReminder]) +
preferences[SettingsKeys.perCalendarFixedTimeReminderOverride].values.filterNotNull()
if (defaults.count { it == reminder } > 1) return
preferences[SettingsKeys.recentFixedTimeReminders] =
(listOf(reminder) + preferences[SettingsKeys.recentFixedTimeReminders]).distinct()
}
@@ -100,6 +100,11 @@ class DailyDigestNotifier @Inject constructor(
}
}
/** Withdraw the summary showing, if any. */
fun cancel() {
NotificationManagerCompat.from(context).cancel(TAG_DIGEST, NOTIFICATION_ID)
}
/** The summary's channel id, created if missing — for the settings deep-link. */
fun channelId(): String {
ensureChannel()
@@ -88,7 +88,14 @@ class ReminderScanner @Inject constructor(
val horizon = now + MAX_ALARM_INTERVAL_MILLIS
val digestSettings = settingsPrefs.dailyDigest.first()
val nextDigest = if (digestSettings.enabled) postDigest(digestSettings, lastFired, now) else null
val nextReminder = if (settingsPrefs.remindersEnabled.first()) reminders(lastFired, now, horizon) else null
val nextReminder = try {
if (settingsPrefs.remindersEnabled.first()) reminders(lastFired, now, horizon) else null
} catch (e: Exception) {
// The watermark stays, so the next pass owes these reminders again;
// keep that pass, and the summary's next moment, armed.
alarms.scheduleScan(minOf(nextDigest ?: horizon, now + RETRY_AFTER_FAILURE_MILLIS))
throw e
}
// Advance even when nothing could be posted, so muting notifications
// doesn't build a backlog — and while both are off, so switching one
@@ -140,20 +147,20 @@ class ReminderScanner @Inject constructor(
*/
private suspend fun postDigest(settings: DailyDigestSettings, lastFired: Long, now: Long): Long {
val zone = ZoneId.systemDefault()
// Neither a moment already posted nor one that passed before the summary
// was last changed is owed.
val posted = try {
state.lastDigestMillis()
val listed = try {
state.lastDigestDay()
} catch (e: Exception) {
Log.w(TAG, "Could not read the last daily summary", e)
now
null
}
val schedule = scheduleDigest(
timeMinutes = settings.timeMinutes,
day = settings.day,
zone = zone,
lastFiredMillis = maxOf(lastFired, settings.armedAtMillis, posted),
// A moment that passed before the summary was last changed is not owed.
lastFiredMillis = maxOf(lastFired, settings.armedAtMillis),
nowMillis = now,
lastListedDay = listed,
)
val day = schedule.dueDay
if (day != null && notifier.canPost()) {
@@ -165,7 +172,7 @@ class ReminderScanner @Inject constructor(
val to = day.plusDays(2).atStartOfDay(zone).toInstant().toEpochMilli()
val left = settings.excludedCalendarIds + calendarPrefs.pendingDisabledCalendarIds.first()
digestNotifier.post(day, digestEntries(source.occurrences(from, to), day, zone, left))
state.setLastDigestMillis(schedule.dueAtMillis)
state.setLastDigestDay(day)
} catch (e: Exception) {
Log.w(TAG, "Daily summary failed", e)
}
@@ -227,5 +234,8 @@ class ReminderScanner @Inject constructor(
const val MAX_ALARM_INTERVAL_MILLIS = 24L * 60 * 60 * 1000
const val PROVIDER_CHANGE_DEBOUNCE_MILLIS = 2_000L
/** How soon a pass whose reminders failed is tried again. */
const val RETRY_AFTER_FAILURE_MILLIS = 15L * 60 * 1000
}
}
@@ -25,20 +25,19 @@ data class DailyDigestSettings(
)
/**
* What one scan concluded for the summary: list [dueDay] now — the summary of
* the moment [dueAtMillis] — or nothing when it is null, and wake up again at
* [nextAlarmMillis].
* What one scan concluded for the summary: list [dueDay] now (null when nothing
* is owed), and wake up again at [nextAlarmMillis].
*/
data class DigestSchedule(
val dueDay: LocalDate?,
val dueAtMillis: Long,
val nextAlarmMillis: Long,
)
/**
* When the summary is owed: a moment in `(lastFiredMillis, nowMillis]` is due.
* Only the latest such moment counts — a phone off for three evenings gets one
* summary, not three — and only while the day it lists has not passed.
* summary, not three — and only while the day it lists has not passed and is
* not [lastListedDay]: each day is listed once.
*/
fun scheduleDigest(
timeMinutes: Int,
@@ -46,6 +45,7 @@ fun scheduleDigest(
zone: ZoneId,
lastFiredMillis: Long,
nowMillis: Long,
lastListedDay: LocalDate? = null,
): DigestSchedule {
val time = LocalTime.of(timeMinutes / 60, timeMinutes % 60)
val fireAt = { date: LocalDate -> date.atTime(time).atZone(zone).toInstant().toEpochMilli() }
@@ -53,8 +53,8 @@ fun scheduleDigest(
val latestDate = if (fireAt(today) <= nowMillis) today else today.minusDays(1)
val listed = latestDate.plusDays(day.daysAhead)
val dueAt = fireAt(latestDate)
val dueDay = listed.takeIf { dueAt > lastFiredMillis && !it.isBefore(today) }
return DigestSchedule(dueDay = dueDay, dueAtMillis = dueAt, nextAlarmMillis = fireAt(latestDate.plusDays(1)))
val dueDay = listed.takeIf { dueAt > lastFiredMillis && !it.isBefore(today) && it != lastListedDay }
return DigestSchedule(dueDay = dueDay, nextAlarmMillis = fireAt(latestDate.plusDays(1)))
}
/**
@@ -52,7 +52,8 @@ data class FixedTimeReminder(val daysBefore: Int, val minuteOfDay: Int) {
fun toToken(): String = "$daysBefore$TOKEN_SEP$minuteOfDay"
companion object {
const val MAX_DAYS_BEFORE = 28
/** Two weeks, well inside the four weeks Google Calendar takes for a reminder. */
const val MAX_DAYS_BEFORE = 14
private const val TOKEN_SEP = "@"
/** [toToken] read back; null for anything malformed or out of range. */
@@ -47,21 +47,26 @@ fun fixedTimeReminderLabel(reminder: FixedTimeReminder): String = stringResource
/**
* The "N days before at HH:MM" editor (#459): a day count and a time, read as
* one sentence, plus a confirm. Seeded from [initial]; [onConfirm] gets the
* finished reminder. [connected] gives it the shape that meets a row above it.
* one sentence. Seeded from [initial]; [onValueChange] follows every edit (null
* while the day count is out of range). With a [confirmLabel] it carries its own
* confirm, reporting through [onConfirm]; without one the host picker commits
* from its actions slot. [connected] gives it the shape that meets a row above it.
*/
@Composable
fun FixedTimeReminderEditor(
initial: FixedTimeReminder,
confirmLabel: String,
onConfirm: (FixedTimeReminder) -> Unit,
modifier: Modifier = Modifier,
confirmLabel: String? = null,
onConfirm: (FixedTimeReminder) -> Unit = {},
onValueChange: (FixedTimeReminder?) -> Unit = {},
connected: Boolean = true,
) {
var daysText by rememberSaveable { mutableStateOf(initial.daysBefore.toString()) }
var minuteOfDay by rememberSaveable { mutableStateOf(initial.minuteOfDay) }
var pickingTime by rememberSaveable { mutableStateOf(false) }
val days = daysText.toIntOrNull()?.takeIf { it in 1..FixedTimeReminder.MAX_DAYS_BEFORE }
val value = days?.let { FixedTimeReminder(it, minuteOfDay) }
LaunchedEffect(value) { onValueChange(value) }
Surface(
color = MaterialTheme.colorScheme.surfaceContainerHigh,
@@ -82,7 +87,7 @@ fun FixedTimeReminderEditor(
DialogAmountField(value = daysText, onValueChange = { daysText = it }, placeholder = "1")
Spacer(Modifier.width(12.dp))
Text(
text = pluralStringResource(R.plurals.reminder_fixed_days_before_at, days ?: 1),
text = stringResource(R.string.reminder_fixed_days_before_at),
style = MaterialTheme.typography.bodyLarge,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f, fill = false),
@@ -94,17 +99,19 @@ fun FixedTimeReminderEditor(
}
Row(verticalAlignment = Alignment.CenterVertically) {
Text(
text = days?.let { fixedTimeReminderLabel(FixedTimeReminder(it, minuteOfDay)) }
text = value?.let { fixedTimeReminderLabel(it) }
?: stringResource(R.string.reminder_fixed_days_range, FixedTimeReminder.MAX_DAYS_BEFORE),
style = MaterialTheme.typography.bodyMedium,
color = MaterialTheme.colorScheme.onSurfaceVariant,
modifier = Modifier.weight(1f),
)
Spacer(Modifier.width(16.dp))
FilledTonalButton(
enabled = days != null,
onClick = { days?.let { onConfirm(FixedTimeReminder(it, minuteOfDay)) } },
) { Text(confirmLabel) }
if (confirmLabel != null) {
Spacer(Modifier.width(16.dp))
FilledTonalButton(
enabled = value != null,
onClick = { value?.let(onConfirm) },
) { Text(confirmLabel) }
}
}
}
}
@@ -123,8 +130,8 @@ fun FixedTimeReminderEditor(
/**
* Picker for a fixed-time default (#459), full-screen: off, or a reminder at a
* set time edited in place — and, on a per-calendar picker ([inheritedLabel]
* non-null), deferring to the global default. Applies live; the user leaves via
* back.
* non-null), deferring to the global default, [inherited], which also seeds the
* editor. Applies live; the user leaves via back.
*/
@Composable
fun FixedTimeReminderPicker(
@@ -133,6 +140,7 @@ fun FixedTimeReminderPicker(
onSelect: (FixedTimeOverride) -> Unit,
onDismiss: () -> Unit,
inheritedLabel: String? = null,
inherited: FixedTimeReminder? = null,
) {
var current by rememberSaveable(stateSaver = FixedTimeOverrideSaver) { mutableStateOf(selected) }
var editing by rememberSaveable { mutableStateOf(false) }
@@ -176,7 +184,7 @@ fun FixedTimeReminderPicker(
checked = chosen != null,
) {
FixedTimeReminderEditor(
initial = chosen ?: DEFAULT_FIXED_TIME_REMINDER,
initial = chosen ?: inherited ?: DEFAULT_FIXED_TIME_REMINDER,
confirmLabel = stringResource(R.string.reminder_custom_set),
onConfirm = {
apply(FixedTimeOverride.At(it))
@@ -1616,6 +1616,7 @@ private fun ReminderPickerDialog(
) {
var customMode by rememberSaveable { mutableStateOf(false) }
var fixedMode by rememberSaveable { mutableStateOf(false) }
var pendingFixed by remember { mutableStateOf<FixedTimeReminder?>(null) }
var amountText by rememberSaveable { mutableStateOf("") }
var unit by rememberSaveable { mutableStateOf(ReminderUnit.Minutes) }
val customMinutes = amountText.toIntOrNull()
@@ -1626,12 +1627,17 @@ private fun ReminderPickerDialog(
title = stringResource(R.string.event_edit_add_reminder),
onDismiss = onDismiss,
actions = {
// The quick-pick list adds on tap; only the custom step needs Add.
// The quick-pick list adds on tap; only the custom steps need Add.
if (customMode) {
TextButton(
enabled = customMinutes != null && customMinutes !in alreadyChosen,
onClick = { customMinutes?.let(onSelect) },
) { Text(stringResource(R.string.event_edit_add)) }
} else if (fixedMode) {
TextButton(
enabled = pendingFixed != null,
onClick = { pendingFixed?.let(onSelectFixed) },
) { Text(stringResource(R.string.event_edit_add)) }
}
},
) {
@@ -1640,8 +1646,7 @@ private fun ReminderPickerDialog(
Spacer(Modifier.height(8.dp))
FixedTimeReminderEditor(
initial = DEFAULT_FIXED_TIME_REMINDER,
confirmLabel = stringResource(R.string.event_edit_add),
onConfirm = onSelectFixed,
onValueChange = { pendingFixed = it },
connected = false,
)
} else if (!customMode) {
@@ -877,6 +877,17 @@ class EventEditViewModel @Inject constructor(
return@launch
}
}
// Remembered before the write, so the rows read back as these
// reminders from the first re-read on (#459).
if (!form.isAllDay && form.fixedReminders.isNotEmpty()) {
try {
settingsPrefs.rememberFixedTimeReminders(form.fixedReminders)
} catch (e: CancellationException) {
throw e
} catch (e: Exception) {
Log.w(TAG, "Could not remember the set-time reminders", e)
}
}
val result = try {
if (target == null) {
repository.createEvent(form)
@@ -928,10 +939,6 @@ class EventEditViewModel @Inject constructor(
Log.w(TAG, "Save failed (scope=$scope, eventId=${target?.eventId})", e)
SaveUiState.Failed
}
// Remembered once saved, so the rows read back as these reminders (#459).
if (result == SaveUiState.Saved && !form.isAllDay && form.fixedReminders.isNotEmpty()) {
runCatching { settingsPrefs.rememberFixedTimeReminders(form.fixedReminders) }
}
settle(result)
}
}
@@ -276,6 +276,7 @@ internal fun NotificationsScreen(
onSelect = { viewModel.setCalendarFixedTimeReminderOverride(calendarId, it) },
onDismiss = { fixedOverrideFor = null },
inheritedLabel = fixedReminderChoiceLabel(state.defaultFixedTimeReminder),
inherited = state.defaultFixedTimeReminder,
)
}
if (showDigestDay) {
@@ -417,7 +417,11 @@ class SettingsViewModel @Inject constructor(
save { setCalendarFixedTimeReminderOverride(calendarId, override) }
/** Every summary change re-plans, so the next one is armed for its new moment (#459). */
fun setDailyDigestEnabled(enabled: Boolean) = saveAndScan { setDailyDigestEnabled(enabled) }
fun setDailyDigestEnabled(enabled: Boolean) {
saveAndScan { setDailyDigestEnabled(enabled) }
// A summary left showing would go stale with nothing to replace it.
if (!enabled) digestNotifier.cancel()
}
fun setDailyDigestTimeMinutes(minutesOfDay: Int) = saveAndScan { setDailyDigestTimeMinutes(minutesOfDay) }
+2 -5
View File
@@ -742,11 +742,8 @@
<!-- Reminders at a set time (#459). %1$s is a lead in days ("1 day before"), %2$s a clock time. -->
<string name="reminder_fixed_time">%1$s at %2$s</string>
<string name="reminder_fixed_at_set_time">At a set time</string>
<!-- Read as one sentence with the number field before it and a time after it: "[1] day before, at [20:00]". -->
<plurals name="reminder_fixed_days_before_at">
<item quantity="one">day before, at</item>
<item quantity="other">days before, at</item>
</plurals>
<!-- Read as one sentence with a number field before it and a time after it: "[2] days before, at [20:00]". The full wording shows below it. -->
<string name="reminder_fixed_days_before_at">days before, at</string>
<string name="reminder_fixed_days_range">Pick 1 to %1$d days</string>
<string name="settings_fixed_reminder">Reminder at a set time</string>
<string name="event_edit_reminder_fixed_summary">E.g. the evening before</string>
@@ -29,13 +29,13 @@ class DailyDigestTest {
}
@Test
fun `the due moment is reported so it can be recorded`() {
val schedule = scheduleDigest(eight, DigestDay.Tomorrow, zone, millis("2026-06-10T19:00"), millis("2026-06-10T20:01"))
assertThat(schedule.dueAtMillis).isEqualTo(millis("2026-06-10T20:00"))
// Recorded, it is no longer owed.
assertThat(
scheduleDigest(eight, DigestDay.Tomorrow, zone, schedule.dueAtMillis, millis("2026-06-10T20:02")).dueDay,
).isNull()
fun `a day already listed is not listed again`() {
// Posted at 20:00, then the time moved to 21:00 the same evening.
val schedule = scheduleDigest(
21 * 60, DigestDay.Tomorrow, zone, millis("2026-06-10T20:30"), millis("2026-06-10T21:00"),
lastListedDay = LocalDate.of(2026, 6, 11),
)
assertThat(schedule.dueDay).isNull()
}
@Test
+7 -5
View File
@@ -436,11 +436,13 @@ counts after a long gap, and it is dropped once the day it lists has passed.
It is independent of the event-reminder switch, posts on its own channel
(`DailyDigestNotifier`), lists switched-on calendars minus its own exclusions,
and replaces the previous summary — or withdraws it when the day is empty.
Two guards keep it to one per moment: the moment posted is recorded at once
(`ReminderStatePrefs.lastDigestMillis`), so a pass failing later can't post it
again, and changing the switch, time or day stamps `dailyDigestArmedAt`, so a
moment that passed before the change is not owed by it. A failing summary is
logged and skipped; it never costs the event reminders of the same pass.
Each day is listed once: the day is recorded as soon as it is posted
(`ReminderStatePrefs.lastDigestDay`), so neither a pass failing later nor a later
time picked the same evening lists it twice, and changing the switch, time or
day stamps `dailyDigestArmedAt`, so a moment that passed before the change is
not owed by it. A failing summary is logged and skipped; it never costs the
event reminders of the same pass, and a failing reminder pass still arms a retry
and the summary's next moment.
The per-calendar reminder mute does not apply: a calendar too noisy to ping per
event can still belong in the overview, and the summary has its own
per-calendar switch next to it.