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.
fix(scheduled): address review on retries, edit approval and alarm handoff
Durganshu19858b722c6a
diff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex 872730d..afef6dd 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -1158,7 +1158,7 @@ class AgentEngine(} else {val approved = events.awaitConfirmation(listOf(call.function.name),- withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.describe(request, agent) }+ withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.describe(request, sessionId, agent) })val decided = if (approved) {withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.apply(request, sessionId, agent) }diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.ktindex c9244bb..e9bd8ce 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt@@ -41,6 +41,39 @@ object ScheduledTaskPlanner {busySince = null)+ /**+ * [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+ * off/on loses nothing; one whose time passed during the pause was cancelled+ * by it. The scheduled time moves on past the pause the same way.+ */+ 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)+ val retryAt = task.retryAt?.takeIf { it > now && (nextRunAt == null || it < nextRunAt) }+ return task.copy(+ enabled = true,+ nextRunAt = nextRunAt,+ retryAt = retryAt,+ retriesUsed = if (retryAt != null) task.retriesUsed else 0,+ busySince = if (retryAt != null) task.busySince else null+ )+ }++ /**+ * [edited] as saved over [existing] (null for a new task): re-armed when its+ * schedule changed, [toggled] when only on/off did, and otherwise left with+ * its times as they are.+ */+ fun edited(existing: ScheduledTask?, edited: ScheduledTask, now: Long, zone: ZoneId): ScheduledTask = when {+ existing == null || edited.startLocal != existing.startLocal || edited.repeat != existing.repeat ->+ armed(edited, now, zone)+ edited.enabled != existing.enabled ->+ toggled(edited.copy(enabled = existing.enabled), edited.enabled, now, zone)+ else -> edited+ }+fun decide(task: ScheduledTask, now: Long, zone: ZoneId): Decision {val due = task.dueAt ?: return Decision.Waitif (due > now + DUE_SLACK_MS) return Decision.Wait@@ -59,14 +92,28 @@ object ScheduledTaskPlanner {* [BUSY_GIVE_UP_MS]. The occurrence is claimed as the wait starts (the task* moves to its next time, and the wait is a [ScheduledTask.retryAt]), or its* time, now past, would stay the soonest alarm and fire again at once.+ *+ * When the next scheduled time comes while an earlier occurrence is still+ * waiting, the earlier one is given up as [TaskRunStatus.SKIPPED_BUSY] and+ * the new one starts a wait of its own: one run can't stand for two+ * occurrences, and the new one gets its full [BUSY_GIVE_UP_MS].*/fun busy(task: ScheduledTask, now: Long, zone: ZoneId): ScheduledTask {+ val newOccurrence = scheduleIsDue(task, now)+ val skipped = TaskRun(at = now, status = TaskRunStatus.SKIPPED_BUSY)+ if (newOccurrence && task.busySince != null) {+ return task.withRun(skipped).copy(+ nextRunAt = nextAfter(task, now, zone),+ retryAt = now + BUSY_RECHECK_MS,+ retriesUsed = 0,+ busySince = now+ )+ }val since = task.busySince ?: nowif (now - since >= BUSY_GIVE_UP_MS) {- return task.copy(retryAt = null, retriesUsed = 0, busySince = null)- .withRun(TaskRun(at = now, status = TaskRunStatus.SKIPPED_BUSY))+ return task.copy(retryAt = null, retriesUsed = 0, busySince = null).withRun(skipped)}- val claimed = if (scheduleIsDue(task, now)) {+ val claimed = if (newOccurrence) {task.copy(nextRunAt = nextAfter(task, now, zone), retriesUsed = 0)} else {task@@ -77,6 +124,8 @@ object ScheduledTaskPlanner {/*** The run has started: the occurrence is used up, so the task moves to its* next time now. A failure that comes back later may still set [ScheduledTask.retryAt].+ * A retry delivered so late (the phone asleep, say) that the next scheduled+ * time has come too is one run for both, and counts as the new occurrence.*/fun started(task: ScheduledTask, sessionId: String, now: Long, zone: ZoneId): ScheduledTask {val newOccurrence = scheduleIsDue(task, now)@@ -92,7 +141,9 @@ object ScheduledTaskPlanner {/*** The run in [sessionId] ended with [status]. A failure is tried again after* the task's retry delay while it has retries left; every other outcome, and- * the last failure, closes the occurrence.+ * the last failure, closes the occurrence. So does a failure whose retry+ * would come no sooner than the next scheduled time: that run takes the+ * retry's place, rather than the retry using up the next occurrence.*/fun finished(task: ScheduledTask,@@ -102,11 +153,10 @@ object ScheduledTaskPlanner {now: Long): ScheduledTask {val recorded = task.withRun(TaskRun(at = now, status = status, sessionId = sessionId, detail = detail))- return if (status == TaskRunStatus.FAILED && task.retriesUsed < task.maxRetries) {- recorded.copy(- retryAt = now + task.retryDelayMinutes.coerceAtLeast(1) * MINUTE_MS,- retriesUsed = task.retriesUsed + 1- )+ val retryAt = now + task.retryDelayMinutes.coerceAtLeast(1) * MINUTE_MS+ val beforeNext = task.nextRunAt?.let { retryAt < it } ?: true+ return if (status == TaskRunStatus.FAILED && task.retriesUsed < task.maxRetries && beforeNext) {+ recorded.copy(retryAt = retryAt, retriesUsed = task.retriesUsed + 1)} else {recorded.copy(retryAt = null, retriesUsed = 0)}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.ktindex 0d4174c..8d42138 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt@@ -119,19 +119,33 @@ object ScheduledTaskRuns {}}-/** The scheduled-task alarm going off. Not exported: only Gotcha's own PendingIntent fires it. */+/**+ * The scheduled-task alarm going off. Not exported: only Gotcha's own PendingIntent fires it.+ *+ * The pass (decrypting the store, loading files, starting the runner, for every+ * due task) can outlast a broadcast's time on a cold start, and Android may+ * then kill the process before the starts are recorded or the alarm re-armed.+ * So a handoff alarm is armed first, before any of that work, and cleared once+ * the pass is done; a pass cut short is made again when it fires. Making it+ * again is safe: a task whose start was recorded is no longer due, and one+ * whose start was not had its run killed with the process.+ */class ScheduledTaskReceiver : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {val app = context.applicationContext as Applicationif (intent.action != ACTION_FIRE) return+ ScheduledTaskScheduler.armHandoff(app)val pending = goAsync()CoroutineScope(Dispatchers.IO).launch {try {ScheduledTaskRuns.fireDue(app)} catch (e: Exception) {Log.w(TAG, "Scheduled task work failed", e)+ // fireDue re-arms only when it finishes; without this the next task would never fire.+ runCatching { ScheduledTaskScheduler.reschedule(app) }} finally {+ ScheduledTaskScheduler.cancelHandoff(app)pending.finish()}}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskScheduler.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskScheduler.ktindex ddc3a41..58739df 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskScheduler.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskScheduler.kt@@ -25,6 +25,12 @@ object ScheduledTaskScheduler {/** How late Android may deliver the alarm when exact alarms are not allowed. */private const val WINDOW_MS = 10L * 60L * 1000L+ /** How soon [armHandoff]'s alarm fires when a pass was cut short. */+ const val HANDOFF_MS = 60L * 1000L++ private const val ALARM_REQUEST = 0+ private const val HANDOFF_REQUEST = 1+/** Arms the alarm for the soonest task, or cancels it when nothing is due. Reads prefs: off the main thread. */fun reschedule(context: Context) {val alarm = context.getSystemService(AlarmManager::class.java) ?: return@@ -47,16 +53,43 @@ object ScheduledTaskScheduler {}}+ /**+ * Arms a second alarm a little ahead, for a firing whose work may outlive+ * the receiver: if Android kills the process before the pass records its+ * runs and re-arms, this one fires and the pass is made again. Cheap, as it+ * reads nothing, so it is set before any of the slow work starts.+ */+ fun armHandoff(context: Context, now: Long = System.currentTimeMillis()) {+ val alarm = context.getSystemService(AlarmManager::class.java) ?: return+ val at = now + HANDOFF_MS+ val pending = fireIntent(context, HANDOFF_REQUEST)+ try {+ if (canRunUnattended(context)) {+ alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)+ } else {+ alarm.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)+ }+ } catch (e: SecurityException) {+ Log.w(TAG, "Exact alarm refused; using an inexact handoff", e)+ alarm.setAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)+ }+ }++ /** The pass finished: the handoff armed by [armHandoff] is not needed. */+ fun cancelHandoff(context: Context) {+ context.getSystemService(AlarmManager::class.java)?.cancel(fireIntent(context, HANDOFF_REQUEST))+ }+/** True when a task can start its run with nobody there: exact alarms are allowed. */fun canRunUnattended(context: Context): Boolean {if (Build.VERSION.SDK_INT < Build.VERSION_CODES.S) return truereturn context.getSystemService(AlarmManager::class.java)?.canScheduleExactAlarms() == true}- private fun fireIntent(context: Context): PendingIntent =+ private fun fireIntent(context: Context, request: Int = ALARM_REQUEST): PendingIntent =PendingIntent.getBroadcast(context,- 0,+ request,Intent(context, ScheduledTaskReceiver::class.java).setAction(ScheduledTaskReceiver.ACTION_FIRE),PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE)diff --git a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.ktindex 42686a2..0f4314e 100644--- a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt+++ b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt@@ -2,7 +2,10 @@ package com.gotcha.toolsimport android.content.Contextimport com.gotcha.agent.AttachmentFiles+import com.gotcha.agent.ChatTitleimport com.gotcha.agent.ComposerAttachment+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.i18n.stringLookupimport com.gotcha.scheduled.Repeatimport com.gotcha.scheduled.RepeatKindimport com.gotcha.scheduled.ScheduledTask@@ -65,7 +68,11 @@ class ScheduledTaskTool(private val context: Context,private val store: ScheduledTaskStore = ScheduledTaskStore(context),private val zone: () -> ZoneId = { ZoneId.systemDefault() },- private val clock: () -> Long = { System.currentTimeMillis() }+ private val clock: () -> Long = { System.currentTimeMillis() },+ /** The title of chat [String], or null when it is no longer saved. */+ private val chatTitle: suspend (String) -> String? = { id ->+ ChatHistoryRepository(context).loadSession(id)?.title?.let { ChatTitle.display(it, context.stringLookup()) }+ }) {private val fileResolver by lazy { FileResolver(context) }@@ -173,14 +180,17 @@ class ScheduledTaskTool(/*** What the user is asked to approve for [request]: the whole task as it- * would be saved, in plain words. [chatMode] caps the task's mode.+ * would be saved, in plain words. [sessionId] is the chat it was asked+ * from, as for [apply]; [chatMode] caps the task's mode.*/- fun describe(request: ScheduleRequest, chatMode: AgentMode): String {+ suspend fun describe(request: ScheduleRequest, sessionId: String?, chatMode: AgentMode): String {val existing = request.taskId?.let { store.get(it) }val start = (request.startLocal ?: existing?.startLocal)?.let(LocalDateTime::parse)val repeat = request.repeat ?: existing?.repeat ?: Repeat()val mode = resolveMode(request, existing, chatMode)val sameChat = request.sameChat ?: existing?.sameChat ?: false+ // The chat a same-chat task will run in, as apply() works it out, when it is not this one.+ val otherChat = existing?.chatSessionId?.takeIf { sameChat && request.sameChat != true && it != sessionId }val files = request.files?.map { File(it).name } ?: existing?.attachmentNames.orEmpty()return buildString {append(if (existing == null) "Schedule a new task" else "Change the scheduled task \"${existing.name}\"")@@ -188,7 +198,14 @@ class ScheduledTaskTool(append("Name: ${request.name ?: existing?.name}\n")if (start != null) append("When: ${describeSchedule(start, repeat)}\n")append("Mode: ${mode.name.lowercase().replaceFirstChar { it.uppercase() }}\n")- append(if (sameChat) "Runs in: this chat, each time\n" else "Runs in: a new chat each time\n")+ append(+ when {+ !sameChat -> "Runs in: a new chat each time\n"+ otherChat == null -> "Runs in: this chat, each time\n"+ else -> chatTitle(otherChat)?.let { "Runs in: the chat \"$it\" (not this one), each time\n" }+ ?: "Runs in: the chat it was set up for, which is no longer saved (not this one)\n"+ }+ )if (files.isNotEmpty()) append("Files: ${files.joinToString()}\n")request.enabled?.let { append(if (it) "Turns the task on\n" else "Pauses the task\n") }append("Prompt: ${request.prompt ?: existing?.prompt}")@@ -204,9 +221,7 @@ class ScheduledTaskTool(val now = clock()val existing = request.taskId?.let { store.get(it) ?: return unknownTask(it) }val attachments = request.files?.let {- loadFiles(- it- ).getOrElse { e -> return ToolResult.error(e.message.orEmpty()) }+ loadFiles(it).getOrElse { e -> return ToolResult.error(e.message.orEmpty()) }}val sameChat = request.sameChat ?: existing?.sameChat ?: falseval base = existing ?: ScheduledTask(@@ -233,9 +248,7 @@ class ScheduledTaskTool(enabled = request.enabled ?: base.enabled,attachmentNames = attachments?.map { it.name } ?: base.attachmentNames)- val scheduleChanged = existing == null || edited.startLocal != existing.startLocal ||- edited.repeat != existing.repeat || edited.enabled != existing.enabled- val saved = if (scheduleChanged) ScheduledTaskPlanner.armed(edited, now, zone()) else edited+ val saved = ScheduledTaskPlanner.edited(existing, edited, now, zone())if (attachments != null) store.saveAttachments(saved.id, attachments)store.put(saved)ScheduledTaskScheduler.reschedule(context)diff --git a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.ktindex 66c9cb3..238264d 100644--- a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt@@ -122,11 +122,13 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {onDispose { lifecycle.removeObserver(observer) }}- /** Saves [task] as edited, re-armed, and the alarm with it. */- fun changed(task: ScheduledTask) {+ /** Switches [task] on or off, keeping a pending retry or busy wait (see [ScheduledTaskPlanner.toggled]). */+ fun toggled(task: ScheduledTask, enabled: Boolean) {scope.launch {withContext(Dispatchers.IO) {- store.put(ScheduledTaskPlanner.armed(task, System.currentTimeMillis(), ZoneId.systemDefault()))+ store.update(task.id) {+ ScheduledTaskPlanner.toggled(it, enabled, System.currentTimeMillis(), ZoneId.systemDefault())+ }ScheduledTaskScheduler.reschedule(context)}tick++@@ -160,7 +162,7 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {} else {TaskRow(task = task,- onEnabledChange = { changed(task.copy(enabled = it)) },+ onEnabledChange = { toggled(task, it) },onEdit = { editing = task.id },onRunNow = {scope.launch {diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.ktindex 5008963..53972e6 100644--- a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt@@ -105,6 +105,95 @@ class ScheduledTaskPlannerTest {assertEquals(2, failedAgain.history.size)}+ private fun hourly(now: Long = at("2026-10-19T07:00")) = ScheduledTaskPlanner.armed(+ ScheduledTask(+ id = "h",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-19T08:00",+ repeat = Repeat(RepeatKind.HOURLY)+ ),+ now,+ zone+ )++ @Test+ fun `a retry that would land after the next scheduled time is left to that run`() {+ val started = ScheduledTaskPlanner.started(hourly(), "chat", at("2026-10-19T08:00"), zone)+ assertEquals(at("2026-10-19T09:00"), started.nextRunAt)++ // Failed at 08:55: a retry at 09:05 would come after the 09:00 run.+ val late = ScheduledTaskPlanner.finished(started, TaskRunStatus.FAILED, "chat", null, at("2026-10-19T08:55"))+ assertNull(late.retryAt)+ assertEquals(0, late.retriesUsed)+ assertEquals(at("2026-10-19T09:00"), late.dueAt)+ assertEquals(TaskRunStatus.FAILED, late.lastRun!!.status)++ // Failed at 08:30: the retry at 08:40 comes first, and keeps 09:00 as it is.+ val early = ScheduledTaskPlanner.finished(started, TaskRunStatus.FAILED, "chat", null, at("2026-10-19T08:30"))+ assertEquals(at("2026-10-19T08:40"), early.retryAt)+ val retried = ScheduledTaskPlanner.started(early, "chat", at("2026-10-19T08:40"), zone)+ assertEquals(at("2026-10-19T09:00"), retried.nextRunAt)+ assertEquals(1, retried.retriesUsed)+ }++ @Test+ fun `a retry delivered after the next scheduled time is one run for both`() {+ val started = ScheduledTaskPlanner.started(hourly(), "chat", at("2026-10-19T08:00"), zone)+ val failed = ScheduledTaskPlanner.finished(started, TaskRunStatus.FAILED, "chat", null, at("2026-10-19T08:30"))+ // The phone slept through 08:40 and woke at 09:01.+ val now = at("2026-10-19T09:01")+ assertEquals(ScheduledTaskPlanner.Decision.Run, ScheduledTaskPlanner.decide(failed, now, zone))+ val run = ScheduledTaskPlanner.started(failed, "chat", now, zone)+ assertEquals(at("2026-10-19T10:00"), run.nextRunAt)+ assertNull(run.retryAt)+ assertEquals(0, run.retriesUsed)+ }++ @Test+ fun `a new occurrence that comes while an older one waits on a busy runner replaces it`() {+ val waiting = ScheduledTaskPlanner.busy(hourly(), at("2026-10-19T08:00"), zone)+ assertEquals(at("2026-10-19T09:00"), waiting.nextRunAt)+ val recheck = at("2026-10-19T08:58")+ val stillWaiting = ScheduledTaskPlanner.busy(waiting.copy(retryAt = recheck), recheck, zone)+ assertEquals(at("2026-10-19T08:00"), stillWaiting.busySince)++ // 09:00 comes while 08:00 still waits: 08:00 is given up, and 09:00 waits on its own.+ val now = at("2026-10-19T09:00")+ val replaced = ScheduledTaskPlanner.busy(stillWaiting, now, zone)+ assertEquals(TaskRunStatus.SKIPPED_BUSY, replaced.lastRun!!.status)+ assertEquals(now, replaced.busySince)+ assertEquals(at("2026-10-19T10:00"), replaced.nextRunAt)+ assertEquals(now + ScheduledTaskPlanner.BUSY_RECHECK_MS, replaced.dueAt)+ }++ @Test+ fun `a quick pause and resume keeps a pending retry`() {+ val now = at("2026-10-19T08:00")+ val started = ScheduledTaskPlanner.started(daily(), "chat", now, zone)+ val failed = ScheduledTaskPlanner.finished(started, TaskRunStatus.FAILED, "chat", null, now + minute)++ val paused = ScheduledTaskPlanner.toggled(failed, false, now + 2 * minute, zone)+ assertNull(paused.dueAt)+ val resumed = ScheduledTaskPlanner.toggled(paused, true, now + 3 * minute, zone)+ assertEquals(failed.retryAt, resumed.retryAt)+ assertEquals(1, resumed.retriesUsed)+ assertEquals(failed.dueAt, resumed.dueAt)+ }++ @Test+ fun `a resume after the retry's time drops it and moves the schedule past the pause`() {+ val now = at("2026-10-19T08:00")+ val started = ScheduledTaskPlanner.started(daily(), "chat", now, zone)+ val failed = ScheduledTaskPlanner.finished(started, TaskRunStatus.FAILED, "chat", null, now + minute)+ val paused = ScheduledTaskPlanner.toggled(failed, false, now + 2 * minute, zone)++ val resumed = ScheduledTaskPlanner.toggled(paused, true, at("2026-10-21T12:00"), zone)+ assertNull(resumed.retryAt)+ assertEquals(0, resumed.retriesUsed)+ assertEquals(at("2026-10-22T08:00"), resumed.nextRunAt)+ }+@Testfun `a task with no retries gives a failure up at once`() {val now = at("2026-10-19T08:00")diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskSchedulerTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskSchedulerTest.ktnew file mode 100644index 0000000..cd1da25--- /dev/null+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskSchedulerTest.kt@@ -0,0 +1,47 @@+package com.gotcha.scheduled++import android.app.AlarmManager+import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.testsupport.FakeAndroidKeyStore+import org.junit.Assert.assertEquals+import org.junit.Assert.assertTrue+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.Shadows.shadowOf+import org.robolectric.annotation.Config++/**+ * [ScheduledTaskScheduler]'s handoff alarm (issue #132): armed before a pass's+ * slow work, it stands apart from the task alarm, so a pass killed half way is+ * made again whatever the task alarm was set to.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScheduledTaskSchedulerTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val alarms = shadowOf(context.getSystemService(AlarmManager::class.java))++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ ScheduledTaskStore(context).let { store -> store.all().forEach { store.delete(it.id) } }+ }++ @Test+ fun `the handoff fires a minute on, and is not cleared by re-arming the task alarm`() {+ val now = 1_000_000L+ ScheduledTaskScheduler.armHandoff(context, now)+ assertEquals(now + ScheduledTaskScheduler.HANDOFF_MS, alarms.scheduledAlarms.single().triggerAtTime)++ // No task is due, so the task alarm is cancelled; the handoff stays.+ ScheduledTaskScheduler.reschedule(context)+ assertEquals(1, alarms.scheduledAlarms.size)++ ScheduledTaskScheduler.cancelHandoff(context)+ assertTrue(alarms.scheduledAlarms.isEmpty())+ }+}diff --git a/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt b/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.ktindex 34906c5..df5c284 100644--- a/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt+++ b/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt@@ -7,6 +7,7 @@ import com.gotcha.scheduled.RepeatKindimport com.gotcha.scheduled.ScheduledTaskimport com.gotcha.scheduled.ScheduledTaskStoreimport com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.coroutines.test.runTestimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonObjectimport org.junit.Assert.assertEquals@@ -42,7 +43,13 @@ class ScheduledTaskToolTest {FakeAndroidKeyStore.setUp()store = ScheduledTaskStore(context)store.all().forEach { store.delete(it.id) }- tool = ScheduledTaskTool(context, store, zone = { zone }, clock = { now })+ tool = ScheduledTaskTool(+ context,+ store,+ zone = { zone },+ clock = { now },+ chatTitle = { id -> if (id == "news-chat") "Morning news" else null }+ )}private fun args(json: String): JsonObject = Json.parseToJsonElement(json) as JsonObject@@ -206,7 +213,7 @@ class ScheduledTaskToolTest {}@Test- fun `the approval prompt shows the whole task`() {+ fun `the approval prompt shows the whole task`() = runTest {val request = request(tool.prepareCreate(args(@@ -215,7 +222,7 @@ class ScheduledTaskToolTest {))- val prompt = tool.describe(request, AgentMode.OPERATOR)+ val prompt = tool.describe(request, sessionId = "chat", chatMode = AgentMode.OPERATOR)assertTrue(prompt, prompt.contains("Name: News"))assertTrue(prompt, prompt.contains("every 2 days at 08:00"))@@ -225,6 +232,42 @@ class ScheduledTaskToolTest {assertTrue(prompt, prompt.contains("without asking you first"))}+ @Test+ fun `an edit asked from another chat names the chat a same-chat task stays in`() = runTest {+ store.put(+ ScheduledTask(+ id = "t",+ name = "News",+ prompt = "Summarise",+ startLocal = "2026-10-19T08:00",+ sameChat = true,+ chatSessionId = "news-chat"+ )+ )++ val rename = request(tool.prepareEdit(args("""{"task_id":"t","name":"Headlines"}""")))+ val prompt = tool.describe(rename, sessionId = "other-chat", chatMode = AgentMode.OPERATOR)+ assertTrue(prompt, prompt.contains("Runs in: the chat \"Morning news\" (not this one)"))+ tool.apply(rename, sessionId = "other-chat", chatMode = AgentMode.OPERATOR)+ assertEquals("news-chat", store.get("t")!!.chatSessionId)++ // Asked from the pinned chat itself, it is "this chat".+ val fromPinned = tool.describe(rename, sessionId = "news-chat", chatMode = AgentMode.OPERATOR)+ assertTrue(fromPinned, fromPinned.contains("Runs in: this chat, each time"))++ // same_chat=true moves it here, and says so.+ val repin = request(tool.prepareEdit(args("""{"task_id":"t","same_chat":true}""")))+ val repinPrompt = tool.describe(repin, sessionId = "other-chat", chatMode = AgentMode.OPERATOR)+ assertTrue(repinPrompt, repinPrompt.contains("Runs in: this chat, each time"))+ tool.apply(repin, sessionId = "other-chat", chatMode = AgentMode.OPERATOR)+ assertEquals("other-chat", store.get("t")!!.chatSessionId)++ // A pinned chat that was deleted is not passed off as this one.+ store.put(store.get("t")!!.copy(chatSessionId = "gone"))+ val orphan = tool.describe(rename, sessionId = "other-chat", chatMode = AgentMode.OPERATOR)+ assertTrue(orphan, orphan.contains("no longer saved"))+ }+@Testfun `list shows each task with its id, and delete asks first`() {store.put(ScheduledTask(id = "t", name = "News", prompt = "Summarise", startLocal = "2026-10-19T08:00"))