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): save task edits over the stored task, not the opened copy
Durganshu0d1515bd5f4b
diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskForm.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskForm.ktnew file mode 100644index 0000000..2ec8ef4--- /dev/null+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskForm.kt@@ -0,0 +1,53 @@+package com.gotcha.scheduled++import java.time.ZoneId++/**+ * What the Settings editor sets on a task. Everything else on a task (its next+ * run, retry and busy waits, history) belongs to the runs, which can change it+ * while the editor is open, so a save lays these fields over the task as it is+ * stored then, not as it was when the editor opened.+ *+ * [openedWithChatId] is the task's chat when the editor opened. While the user+ * leaves the chat picker on it, the stored chat wins, so a chat a same-chat run+ * started meanwhile is kept.+ */+data class ScheduledTaskForm(+ val name: String,+ val prompt: String,+ val startLocal: String,+ val repeat: Repeat,+ val agentMode: String,+ val personaId: String?,+ val sameChat: Boolean,+ val chatSessionId: String?,+ val openedWithChatId: String?,+ val maxRetries: Int,+ val attachmentNames: List<String>+) {+ fun applyTo(task: ScheduledTask): ScheduledTask = task.copy(+ name = name,+ prompt = prompt,+ startLocal = startLocal,+ repeat = repeat,+ agentMode = agentMode,+ personaId = personaId,+ sameChat = sameChat,+ chatSessionId = when {+ !sameChat -> null+ chatSessionId == openedWithChatId -> task.chatSessionId+ else -> chatSessionId+ },+ maxRetries = maxRetries,+ attachmentNames = attachmentNames+ )++ /**+ * Saves the form over the stored task [id] and returns the result, or null+ * when the task was deleted meanwhile (it is not brought back). The schedule+ * is re-worked only when the form changed it, so a pending retry or busy+ * wait survives an edit to, say, the name.+ */+ fun saveOver(store: ScheduledTaskStore, id: String, now: Long, zone: ZoneId): ScheduledTask? =+ store.update(id) { current -> ScheduledTaskPlanner.edited(current, applyTo(current), now, zone) }+}diff --git a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.ktindex 0f4314e..ba20678 100644--- a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt+++ b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt@@ -223,34 +223,43 @@ class ScheduledTaskTool(val attachments = request.files?.let {loadFiles(it).getOrElse { e -> return ToolResult.error(e.message.orEmpty()) }}- val sameChat = request.sameChat ?: existing?.sameChat ?: false- val base = existing ?: ScheduledTask(- id = UUID.randomUUID().toString(),- name = request.name.orEmpty(),- prompt = request.prompt.orEmpty(),- startLocal = request.startLocal ?: return missing("start"),- createdByAgent = true,- createdAt = now- )- val edited = base.copy(- name = request.name ?: base.name,- prompt = request.prompt ?: base.prompt,- startLocal = request.startLocal ?: base.startLocal,- repeat = request.repeat ?: base.repeat,- agentMode = resolveMode(request, existing, chatMode).name,- sameChat = sameChat,- // Asked from this chat: "the same chat" is this one.- chatSessionId = if (sameChat && (request.sameChat == true || base.chatSessionId == null)) {- sessionId- } else {- base.chatSessionId- },- enabled = request.enabled ?: base.enabled,- attachmentNames = attachments?.map { it.name } ?: base.attachmentNames- )- val saved = ScheduledTaskPlanner.edited(existing, edited, now, zone())+ val mode = resolveMode(request, existing, chatMode).name+ fun edit(base: ScheduledTask): ScheduledTask {+ val sameChat = request.sameChat ?: base.sameChat+ return base.copy(+ name = request.name ?: base.name,+ prompt = request.prompt ?: base.prompt,+ startLocal = request.startLocal ?: base.startLocal,+ repeat = request.repeat ?: base.repeat,+ agentMode = mode,+ sameChat = sameChat,+ // Asked from this chat: "the same chat" is this one.+ chatSessionId = if (sameChat && (request.sameChat == true || base.chatSessionId == null)) {+ sessionId+ } else {+ base.chatSessionId+ },+ enabled = request.enabled ?: base.enabled,+ attachmentNames = attachments?.map { it.name } ?: base.attachmentNames+ )+ }+ val saved = if (existing == null) {+ val created = ScheduledTask(+ id = UUID.randomUUID().toString(),+ name = request.name.orEmpty(),+ prompt = request.prompt.orEmpty(),+ startLocal = request.startLocal ?: return missing("start"),+ createdByAgent = true,+ createdAt = now+ )+ ScheduledTaskPlanner.edited(null, edit(created), now, zone()).also(store::put)+ } else {+ // Over the task as stored now, so a run that ended since the+ // approval was asked keeps its history and next time.+ store.update(existing.id) { current -> ScheduledTaskPlanner.edited(current, edit(current), now, zone()) }+ ?: return unknownTask(existing.id)+ }if (attachments != null) store.saveAttachments(saved.id, attachments)- store.put(saved)ScheduledTaskScheduler.reschedule(context)val next = saved.dueAt?.let(::formatInstant) ?: "none"return ToolResult.ok(diff --git a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.ktindex 238264d..f3fb4c4 100644--- a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt@@ -63,6 +63,7 @@ import com.gotcha.scheduled.Repeatimport com.gotcha.scheduled.RepeatKindimport com.gotcha.scheduled.ScheduledStartimport com.gotcha.scheduled.ScheduledTask+import com.gotcha.scheduled.ScheduledTaskFormimport com.gotcha.scheduled.ScheduledTaskPlannerimport com.gotcha.scheduled.ScheduledTaskRunsimport com.gotcha.scheduled.ScheduledTaskScheduler@@ -387,6 +388,7 @@ private fun TaskEditor(}val unreadable = stringResource(R.string.scheduled_file_unreadable)+ val taskGone = stringResource(R.string.scheduled_task_gone)val tooMany = stringResource(R.string.scheduled_too_many_files, ComposerAttachment.MAX_PER_MESSAGE)val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->if (uris.isEmpty()) return@rememberLauncherForActivityResult@@ -568,15 +570,7 @@ private fun TaskEditor(else -> ""}if (error.isNotEmpty()) return@Button- val task = (- initial ?: ScheduledTask(- id = UUID.randomUUID().toString(),- name = "",- prompt = "",- startLocal = "",- createdAt = System.currentTimeMillis()- )- ).copy(+ val form = ScheduledTaskForm(name = name.trim(),prompt = prompt.trim(),startLocal = startAt.toString(),@@ -588,19 +582,38 @@ private fun TaskEditor(agentMode = mode.name,personaId = personaId,sameChat = sameChat,- chatSessionId = if (sameChat) chatSessionId else null,+ chatSessionId = chatSessionId,+ openedWithChatId = initial?.chatSessionId,maxRetries = retries,attachmentNames = files.map { it.name })scope.launch {- withContext(Dispatchers.IO) {- store.saveAttachments(task.id, files)- store.put(- ScheduledTaskPlanner.armed(task, System.currentTimeMillis(), ZoneId.systemDefault())- )- ScheduledTaskScheduler.reschedule(context)+ val saved = withContext(Dispatchers.IO) {+ val now = System.currentTimeMillis()+ val zone = ZoneId.systemDefault()+ val saved = if (initial == null) {+ val created = form.applyTo(+ ScheduledTask(+ id = UUID.randomUUID().toString(),+ name = "",+ prompt = "",+ startLocal = "",+ createdAt = now+ )+ )+ ScheduledTaskPlanner.armed(created, now, zone).also(store::put)+ } else {+ // Over the task as stored now: a run may have+ // changed it while the form was open.+ form.saveOver(store, initial.id, now, zone)+ }+ saved?.let {+ store.saveAttachments(it.id, files)+ ScheduledTaskScheduler.reschedule(context)+ }+ saved}- onSaved()+ if (saved == null) error = taskGone else onSaved()}},modifier = Modifier.testTag("scheduled_save")diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskFormTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskFormTest.ktnew file mode 100644index 0000000..88194b5--- /dev/null+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskFormTest.kt@@ -0,0 +1,133 @@+package com.gotcha.scheduled++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Before+import org.junit.Test+import org.junit.runner.RunWith+import org.robolectric.RobolectricTestRunner+import org.robolectric.annotation.Config+import java.io.File+import java.time.LocalDateTime+import java.time.ZoneId++/**+ * [ScheduledTaskForm]: a save from the Settings editor lands on the task as it+ * is stored at that moment, so a run that changed it while the form was open+ * keeps what it wrote (#136 review).+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScheduledTaskFormTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val dir = File(context.filesDir, "scheduled-form-test")+ private val zone = ZoneId.of("UTC")+ private lateinit var store: ScheduledTaskStore++ private fun at(local: String): Long = LocalDateTime.parse(local).atZone(zone).toInstant().toEpochMilli()++ @Before+ fun setUp() {+ dir.deleteRecursively()+ store = ScheduledTaskStore(context.getSharedPreferences("scheduled-form-test", Context.MODE_PRIVATE), dir)+ }++ private val opened = ScheduledTaskPlanner.armed(+ ScheduledTask(+ id = "t",+ name = "Morning",+ prompt = "p",+ startLocal = "2026-10-19T08:00",+ repeat = Repeat(RepeatKind.DAILY),+ sameChat = true+ ),+ at("2026-10-19T07:00"),+ zone+ )++ /** The form as the editor would build it from [opened], with [name] typed in. */+ private fun form(+ name: String = opened.name,+ startLocal: String = opened.startLocal,+ chatSessionId: String? = opened.chatSessionId+ ) = ScheduledTaskForm(+ name = name,+ prompt = opened.prompt,+ startLocal = startLocal,+ repeat = opened.repeat,+ agentMode = opened.agentMode,+ personaId = opened.personaId,+ sameChat = opened.sameChat,+ chatSessionId = chatSessionId,+ openedWithChatId = opened.chatSessionId,+ maxRetries = opened.maxRetries,+ attachmentNames = opened.attachmentNames+ )++ /** The 08:00 run finished while the form was open: it moved the task on and started its chat. */+ private fun runFinishedMeanwhile() = store.update("t") {+ it.copy(+ nextRunAt = at("2026-10-20T08:00"),+ chatSessionId = "run-chat",+ history = listOf(TaskRun(at = at("2026-10-19T08:00"), status = TaskRunStatus.DONE, sessionId = "run-chat"))+ )+ }++ @Test+ fun `a save keeps the history, next time and chat of a run that ended while the form was open`() {+ store.put(opened)+ runFinishedMeanwhile()++ val saved = form(name = "Renamed").saveOver(store, "t", at("2026-10-19T08:05"), zone)!!++ assertEquals("Renamed", saved.name)+ assertEquals(at("2026-10-20T08:00"), saved.nextRunAt)+ assertEquals(1, saved.history.size)+ assertEquals("run-chat", saved.chatSessionId)+ assertEquals(saved, store.get("t"))+ }++ @Test+ fun `an edit that leaves the schedule alone keeps a pending retry or busy wait`() {+ store.put(opened.copy(retryAt = at("2026-10-19T08:10"), retriesUsed = 1, busySince = at("2026-10-19T08:00")))++ val saved = form(name = "Renamed").saveOver(store, "t", at("2026-10-19T08:05"), zone)!!++ assertEquals(at("2026-10-19T08:10"), saved.retryAt)+ assertEquals(1, saved.retriesUsed)+ assertEquals(at("2026-10-19T08:00"), saved.busySince)+ }++ @Test+ fun `changing the start time arms the task again`() {+ store.put(opened.copy(retryAt = at("2026-10-19T08:10"), retriesUsed = 1))++ val saved = form(startLocal = "2026-10-19T09:00").saveOver(store, "t", at("2026-10-19T08:05"), zone)!!++ assertEquals(at("2026-10-19T09:00"), saved.nextRunAt)+ assertNull(saved.retryAt)+ assertEquals(0, saved.retriesUsed)+ }++ @Test+ fun `a chat picked in the form wins over the stored one`() {+ store.put(opened)+ runFinishedMeanwhile()++ val saved = form(chatSessionId = "picked").saveOver(store, "t", at("2026-10-19T08:05"), zone)!!++ assertEquals("picked", saved.chatSessionId)+ }++ @Test+ fun `a task deleted while the form was open is not brought back`() {+ store.put(opened)+ store.delete("t")++ assertNull(form(name = "Renamed").saveOver(store, "t", at("2026-10-19T08:05"), zone))+ assertEquals(emptyList<ScheduledTask>(), store.all())+ }+}