Your phone, on your command. Gotcha is world's first fully on-device AI copilot for Android that turns natural language into real device actions — safely.
Recompute scheduled tasks on zone change, overlap fix for one-offs (#150)
Rishabh Bajpaifc2f3a30f6da
diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.ktindex a71efb5..720b017 100644--- a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt+++ b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt@@ -10,6 +10,7 @@ import com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.SettingsRepositoryimport com.gotcha.i18n.stringLookupimport com.gotcha.scheduled.ScheduledTaskScheduler+import com.gotcha.scheduled.ScheduledTaskStoreimport com.gotcha.updater.runUpdateCheckimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -91,6 +92,21 @@ class NotificationRescheduleReceiver : BroadcastReceiver() {runAsync(TAG) {// finally: a failure arming one set of alarms must not leave the other unarmed.try {+ // A zone or clock change moves wall-clock time under the stored+ // next runs (issue #150): re-resolve non-hourly tasks first, so+ // the alarm below arms at the new zone's moment. A reboot or+ // update changes nothing about the mapping, so those only re-arm.+ // Deliberately also on TIME_SET: wall tasks follow the wall,+ // which may advance past (no MISSED record) or re-arm (a repeat)+ // occurrences the clock move invalidated.+ if (intent.action == Intent.ACTION_TIMEZONE_CHANGED || intent.action == Intent.ACTION_TIME_CHANGED) {+ runCatching {+ ScheduledTaskStore(app).rebaseForZoneChange(+ System.currentTimeMillis(),+ ZoneId.systemDefault()+ )+ }.onFailure { Log.w(TAG, "Scheduled task rebase failed", it) }+ }if (intent.action != ACTION_EXACT_ALARM_PERMISSION_CHANGED) LocalNotificationScheduler.scheduleAll(app)} finally {ScheduledTaskScheduler.reschedule(app)diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTask.ktindex e87423a..44b7708 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt@@ -141,6 +141,15 @@ data class ScheduledTask(fun nextOccurrence(task: ScheduledTask, after: Long, zone: ZoneId): Long? {val start = task.startval startAt = start.atZone(zone).toInstant().toEpochMilli()+ if (task.repeat.kind == RepeatKind.NONE) {+ // A one-off in the repeated hour when summer time ends: the earlier+ // pass may be gone while the later one still lies ahead, so fall+ // through to it instead of reporting nothing left to run. Arming only:+ // once the task fires, the planner spends it (null) rather than+ // re-arming per pass.+ if (startAt > after) return startAt+ return laterOffsetAtOverlap(start, zone)?.takeIf { it > after }+ }if (startAt > after) {// The start itself, unless a weekly task does not run on that weekday.if (task.repeat.kind != RepeatKind.WEEKLY || start.dayOfWeek in weekdaysOf(task.repeat, start)) {@@ -199,5 +208,26 @@ fun nextOccurrence(task: ScheduledTask, after: Long, zone: ZoneId): Long? {private fun weekdaysOf(repeat: Repeat, start: LocalDateTime): Set<DayOfWeek> =repeat.weekdays.filter { it in 1..7 }.map { DayOfWeek.of(it) }.toSet().ifEmpty { setOf(start.dayOfWeek) }+/**+ * True when wall-clock [local] still lies ahead of [now] in [zone]: either+ * pass counts on the night summer time ends (issue #150). The form's+ * "that time has passed" check and [nextOccurrence]'s one-off path share it,+ * so a picked time the form accepts is one the schedule can still reach.+ * Repeating candidates keep the earlier pass only: a daily task in that hour+ * runs once, at the first pass.+ */+fun isWallTimeFuture(local: LocalDateTime, zone: ZoneId, now: Long): Boolean {+ if (local.atZone(zone).toInstant().toEpochMilli() > now) return true+ return laterOffsetAtOverlap(local, zone)?.let { it > now } == true+}++/** The second pass of an ambiguous wall time, or null when unambiguous. */+private fun laterOffsetAtOverlap(local: LocalDateTime, zone: ZoneId): Long? {+ val early = local.atZone(zone)+ val late = early.withLaterOffsetAtOverlap()+ if (late == early) return null+ return late.toInstant().toEpochMilli()+}+private const val HOUR_MS = 60L * 60L * 1000Lprivate const val DAYS_TO_SCAN = 8diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.ktindex e9bd8ce..ab33929 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt@@ -41,6 +41,21 @@ object ScheduledTaskPlanner {busySince = null)+ /**+ * [task] carried across a time-zone or clock change (issue #150): its+ * wall-clock schedule is re-resolved in [zone], so a daily 08:00 stays at+ * 08:00 local instead of keeping the old zone's moment. One-offs keep+ * their wall time too. Hourly tasks count real hours from their start+ * instant and keep it; retries and busy waits are real delays and are left+ * alone, as is history. A spent one-off ([nextRunAt] null) stays spent.+ */+ fun rebasedForZone(task: ScheduledTask, now: Long, zone: ZoneId): ScheduledTask {+ if (task.repeat.kind == RepeatKind.HOURLY) return task+ if (task.repeat.kind == RepeatKind.NONE && task.nextRunAt == null) return task+ val next = nextOccurrence(task, now, zone)+ return if (next == task.nextRunAt) task else task.copy(nextRunAt = next)+ }+/*** [task] switched on or off from Settings. Pausing keeps everything as it is.* Resuming keeps a retry or a busy wait that is still ahead, so a quick@@ -50,7 +65,11 @@ object ScheduledTaskPlanner {fun toggled(task: ScheduledTask, enabled: Boolean, now: Long, zone: ZoneId): ScheduledTask {if (!enabled) return task.copy(enabled = false)if (task.enabled) return task- val nextRunAt = task.nextRunAt?.takeIf { it > now } ?: nextOccurrence(task, now, zone)+ // A spent one-off stays spent: resuming must not re-arm it off the+ // overlap fall-through in nextOccurrence (issue #150).+ val spent = task.repeat.kind == RepeatKind.NONE && task.nextRunAt == null+ val nextRunAt = task.nextRunAt?.takeIf { it > now }+ ?: if (spent) null else nextOccurrence(task, now, zone)val retryAt = task.retryAt?.takeIf { it > now && (nextRunAt == null || it < nextRunAt) }return task.copy(enabled = true,@@ -192,8 +211,15 @@ object ScheduledTaskPlanner {private fun scheduleIsDue(task: ScheduledTask, now: Long): Boolean =task.nextRunAt?.let { it <= now + DUE_SLACK_MS } ?: false- private fun nextAfter(task: ScheduledTask, now: Long, zone: ZoneId): Long? =- nextOccurrence(task, maxOf(now, task.nextRunAt ?: now), zone)+ private fun nextAfter(task: ScheduledTask, now: Long, zone: ZoneId): Long? {+ // A one-off is spent once it fires: the overlap fall-through in+ // nextOccurrence is for arming only, or the same task would fire once+ // per pass (issue #150).+ if (task.repeat.kind == RepeatKind.NONE) {+ return null+ }+ return nextOccurrence(task, maxOf(now, task.nextRunAt ?: now), zone)+ }private const val MINUTE_MS = 60L * 1000L}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.ktindex a0d127b..6f0c2d8 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt@@ -103,6 +103,20 @@ class ScheduledTaskStore internal constructor(update(id) { null }}+ /**+ * Re-resolves every non-hourly task's next run in [zone] after the wall+ * clock moved under it (issue #150). Hourly tasks, retries and busy waits+ * are real durations and keep their moments. Returns true when anything+ * changed. One lock covers the read and the write, like [update].+ */+ fun rebaseForZoneChange(now: Long, zone: ZoneId): Boolean = synchronized(LOCK) {+ val tasks = read()+ val rebased = tasks.map { ScheduledTaskPlanner.rebasedForZone(it, now, zone) }+ if (rebased == tasks) return false+ write(rebased)+ true+ }+/** The pinned chat [sessionId] was deleted: a same-chat task starts a new one next time. */fun forgetChat(sessionId: String) = synchronized(LOCK) {val tasks = read()diff --git a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.ktindex afcd510..7c2fb1a 100644--- a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt@@ -72,6 +72,7 @@ import com.gotcha.scheduled.ScheduledTaskSchedulerimport com.gotcha.scheduled.ScheduledTaskStoreimport com.gotcha.scheduled.TaskRunimport com.gotcha.scheduled.TaskRunStatus+import com.gotcha.scheduled.isWallTimeFutureimport com.gotcha.service.ChatRunServiceimport com.gotcha.tools.AgentModeimport com.gotcha.ui.theme.SkinAlertDialog@@ -597,7 +598,7 @@ private fun TaskEditor((kind == RepeatKind.HOURLY || kind == RepeatKind.DAILY) &&(every == null || every !in 1..ScheduledTask.MAX_INTERVAL) -> badIntervalkind == RepeatKind.NONE &&- !startAt.atZone(ZoneId.systemDefault()).toInstant().isAfter(Instant.now()) -> pastTime+ !isWallTimeFuture(startAt, ZoneId.systemDefault(), Instant.now().toEpochMilli()) -> pastTimeAttachmentFiles.documentChars(files) > ComposerAttachment.MAX_TOTAL_DOCUMENT_CHARS -> tooMuchTextelse -> ""}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.ktindex 53972e6..1c6dd55 100644--- a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt@@ -266,4 +266,114 @@ class ScheduledTaskPlannerTest {assertEquals(ScheduledTask.MAX_HISTORY, task.history.size)assertEquals((ScheduledTask.MAX_HISTORY + 4).toLong(), task.history.last().at)}++ @Test+ fun `a zone change keeps the daily wall time`() {+ // Daily 08:00 armed in Berlin; after today's run the next is 26 Oct+ // 08:00 Berlin. The phone then moves to Tokyo (same instant): the+ // stored moment would fire at 16:00 Tokyo, but rebasing moves it to+ // 08:00 Tokyo wall time.+ val berlin = ZoneId.of("Europe/Berlin")+ val tokyo = ZoneId.of("Asia/Tokyo")+ val armed = ScheduledTaskPlanner.armed(+ ScheduledTask(+ id = "t",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-25T08:00",+ repeat = Repeat(RepeatKind.DAILY)+ ),+ LocalDateTime.parse("2026-10-25T09:00").atZone(berlin).toInstant().toEpochMilli(),+ berlin+ )+ assertEquals(+ LocalDateTime.parse("2026-10-26T08:00").atZone(berlin).toInstant().toEpochMilli(),+ armed.nextRunAt+ )+ val sameInstantInTokyo = LocalDateTime.parse("2026-10-25T09:00")+ .atZone(berlin).toInstant().toEpochMilli()+ val rebased = ScheduledTaskPlanner.rebasedForZone(armed, sameInstantInTokyo, tokyo)+ assertEquals(+ LocalDateTime.parse("2026-10-26T08:00").atZone(tokyo).toInstant().toEpochMilli(),+ rebased.nextRunAt+ )+ // The wall time reads back as 08:00 in Tokyo.+ assertEquals(+ "2026-10-26T08:00",+ LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(rebased.nextRunAt!!), tokyo).toString()+ )+ }++ @Test+ fun `a zone change leaves hourly tasks retries and history alone`() {+ val berlin = ZoneId.of("Europe/Berlin")+ val tokyo = ZoneId.of("Asia/Tokyo")+ val hourly = ScheduledTaskPlanner.armed(+ ScheduledTask(+ id = "h",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-25T00:00",+ repeat = Repeat(RepeatKind.HOURLY, interval = 2)+ ),+ LocalDateTime.parse("2026-10-25T00:00").atZone(berlin).toInstant().toEpochMilli(),+ berlin+ )+ val nowInTokyo = hourly.nextRunAt!! - 60_000L+ assertEquals(hourly, ScheduledTaskPlanner.rebasedForZone(hourly, nowInTokyo, tokyo))++ val retrying = daily().copy(retryAt = at("2026-10-19T07:30"), retriesUsed = 1)+ val rebased = ScheduledTaskPlanner.rebasedForZone(retrying, at("2026-10-19T07:00"), zone)+ assertEquals(at("2026-10-19T07:30"), rebased.retryAt)+ assertEquals(1, rebased.retriesUsed)+ }++ @Test+ fun `a zone change never resurrects a spent one-off`() {+ val spent = ScheduledTask(+ id = "t",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-19T08:00",+ nextRunAt = null+ )+ assertEquals(+ spent,+ ScheduledTaskPlanner.rebasedForZone(spent, at("2026-10-19T09:00"), ZoneId.of("Asia/Tokyo"))+ )+ }++ @Test+ fun `a spent one-off stays spent through pause resume and busy waits`() {+ // In the overlap hour a resume must not re-arm off the later pass.+ val berlin = ZoneId.of("Europe/Berlin")+ val spent = ScheduledTask(+ id = "t",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-25T02:40",+ enabled = false,+ nextRunAt = null+ )+ val betweenPasses = java.time.ZonedDateTime.of(+ LocalDateTime.parse("2026-10-25T02:37"),+ berlin+ ).withLaterOffsetAtOverlap().toInstant().toEpochMilli()+ assertNull(ScheduledTaskPlanner.toggled(spent, true, betweenPasses, berlin).nextRunAt)+ // A busy wait on a due one-off claims no next time either.+ val firstPass = LocalDateTime.parse("2026-10-25T02:40")+ .atZone(berlin).toInstant().toEpochMilli()+ val busy = ScheduledTaskPlanner.busy(+ ScheduledTask(+ id = "t",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-25T02:40",+ nextRunAt = firstPass+ ),+ firstPass,+ berlin+ )+ assertNull(busy.nextRunAt)+ }}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.ktindex 1cb1a34..5d71e91 100644--- a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt@@ -129,4 +129,60 @@ class ScheduledTaskScheduleTest {assertEquals("2026-10-15T09:00", next(fifteenth, "2026-10-01T00:00"))assertEquals("2026-11-15T09:00", next(fifteenth, "2026-10-15T09:00"))}++ @Test+ fun `a one-off in the repeated hour fires once, at whichever pass is armed`() {+ // Summer time ends in Berlin on 25 Oct 2026: 02:00-03:00 happens twice.+ // At 02:37 CET (the second pass) the first 02:40 (CEST) is gone but the+ // second 02:40 (CET) still lies ahead.+ val once = task("2026-10-25T02:40")+ val betweenPasses = java.time.ZonedDateTime.of(+ LocalDateTime.parse("2026-10-25T02:37"),+ zone+ ).withLaterOffsetAtOverlap().toInstant().toEpochMilli()+ val got = nextOccurrence(once, betweenPasses, zone)?.let {+ LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(it), zone).toString()+ }+ assertEquals("2026-10-25T02:40", got)+ assertTrue(isWallTimeFuture(LocalDateTime.parse("2026-10-25T02:40"), zone, betweenPasses))+ }++ @Test+ fun `a one-off armed at the first pass does not fire again at the second`() {+ val once = task("2026-10-25T02:40")+ val firstPass = LocalDateTime.parse("2026-10-25T02:40")+ .atZone(zone).toInstant().toEpochMilli()+ // Firing at the first pass spends the task even though the wall time+ // comes round again an hour later.+ val started = ScheduledTaskPlanner.started(+ once.copy(nextRunAt = firstPass),+ "chat",+ firstPass,+ zone+ )+ assertNull(started.nextRunAt)+ }++ @Test+ fun `a daily task in the repeated hour runs once at the first pass`() {+ val daily = task("2026-10-25T02:30", Repeat(RepeatKind.DAILY))+ // Before the first pass: today at the first pass, not the second.+ val before = java.time.ZonedDateTime.of(+ LocalDateTime.parse("2026-10-25T02:10"),+ zone+ ).withEarlierOffsetAtOverlap().toInstant().toEpochMilli()+ val got = nextOccurrence(daily, before, zone)?.let { instant ->+ LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(instant), zone).toString()+ }+ assertEquals("2026-10-25T02:30", got)+ // After the first pass fired: tomorrow, not the second pass today.+ val firstPass = java.time.ZonedDateTime.of(+ LocalDateTime.parse("2026-10-25T02:30"),+ zone+ ).withEarlierOffsetAtOverlap().toInstant().toEpochMilli()+ val after = nextOccurrence(daily, firstPass, zone)?.let { instant ->+ LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(instant), zone).toString()+ }+ assertEquals("2026-10-26T02:30", after)+ }}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.ktindex d0110e0..dcd386a 100644--- a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt@@ -142,4 +142,41 @@ class ScheduledTaskStoreTest {store.delete(seeded.id)assertTrue(!store.hasBriefingPreset())}++ @Test+ fun `a zone change rebases wall-clock tasks and reports whether anything moved`() {+ val berlin = java.time.ZoneId.of("Europe/Berlin")+ val tokyo = java.time.ZoneId.of("Asia/Tokyo")+ val armedAt = java.time.LocalDateTime.parse("2026-10-25T09:00").atZone(berlin).toInstant().toEpochMilli()+ store.put(+ task("daily").copy(+ startLocal = "2026-10-25T08:00",+ repeat = Repeat(RepeatKind.DAILY),+ nextRunAt = ScheduledTaskPlanner.armed(+ task("daily").copy(+ startLocal = "2026-10-25T08:00",+ repeat = Repeat(RepeatKind.DAILY)+ ),+ armedAt,+ berlin+ ).nextRunAt+ )+ )+ store.put(+ task("hourly").copy(+ startLocal = "2026-10-25T00:00",+ repeat = Repeat(RepeatKind.HOURLY, interval = 2),+ nextRunAt = armedAt + 2 * 60 * 60 * 1000L+ )+ )+ val sameInstant = armedAt+ assertTrue(store.rebaseForZoneChange(sameInstant, tokyo))+ assertEquals(+ java.time.LocalDateTime.parse("2026-10-26T08:00").atZone(tokyo).toInstant().toEpochMilli(),+ store.get("daily")!!.nextRunAt+ )+ assertEquals(armedAt + 2 * 60 * 60 * 1000L, store.get("hourly")!!.nextRunAt)+ // A second rebase with nothing moved reports false.+ assertTrue(!store.rebaseForZoneChange(sameInstant, tokyo))+ }}