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.
Queue scheduled starts while busy instead of dropping them
Rishabh Bajpaib2847c627d1f
diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 2cd0af1..2dc8d12 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -691,6 +691,8 @@ class MainActivity : ComponentActivity() {is ScheduledStart.Started -> openSessionRequested = result.sessionIdScheduledStart.Busy ->Toast.makeText(this@MainActivity, R.string.scheduled_run_now_busy, Toast.LENGTH_LONG).show()+ ScheduledStart.Queued ->+ Toast.makeText(this@MainActivity, R.string.scheduled_run_now_queued, Toast.LENGTH_LONG).show()is ScheduledStart.Failed ->Toast.makeText(this@MainActivity, result.detail, Toast.LENGTH_LONG).show()}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.ktindex c46f55a..3f59cca 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt@@ -55,6 +55,46 @@ class ScheduledTaskNotifier(private val context: Context) {NotificationManagerCompat.from(context).cancel(notificationId(taskId))}+ /**+ * A task that fired while another run holds Gotcha is queued, not lost.+ * One quiet slot per task, updated in place on every recheck: same id and+ * onlyAlertOnce, so waiting never buzzes. Cancelled when the run starts,+ * gives up, or the task is paused, edited or deleted.+ */+ @Suppress("MissingPermission") // canPost() checks it.+ fun postWaiting(task: ScheduledTask) {+ if (!ChatCompletionNotifier(context).canPost()) return+ ensureChannel()+ val open = PendingIntent.getActivity(+ context,+ notificationId(task.id),+ Intent(context, MainActivity::class.java)+ .addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP),+ PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE+ )+ val body = context.getString(R.string.scheduled_waiting_body)+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(context.getString(R.string.scheduled_waiting_title, task.name))+ .setContentText(body)+ .setStyle(NotificationCompat.BigTextStyle().bigText(body))+ .setCategory(NotificationCompat.CATEGORY_STATUS)+ .setAutoCancel(false)+ .setOngoing(false)+ .setOnlyAlertOnce(true)+ .setContentIntent(open)+ // The task name can be personal: the lock screen gets a generic line.+ .setVisibility(NotificationCompat.VISIBILITY_PRIVATE)+ .setPublicVersion(+ NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(context.getString(R.string.scheduled_needs_tap_public_title))+ .build()+ )+ .build()+ NotificationManagerCompat.from(context).notify(notificationId(task.id), notification)+ }+private fun ensureChannel() {val manager = context.getSystemService(NotificationManager::class.java) ?: returnif (manager.getNotificationChannel(CHANNEL_ID) != null) returndiff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.ktindex 8d42138..1938c00 100644--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt@@ -22,6 +22,12 @@ sealed class ScheduledStart {/** Another run holds the agent; nothing was started. */object Busy : ScheduledStart()+ /**+ * Another run holds the agent, so this start is queued: the task waits+ * with a busy retry and runs when the runner frees up.+ */+ object Queued : ScheduledStart()+data class Failed(val detail: String) : ScheduledStart()}@@ -91,10 +97,13 @@ object ScheduledTaskRuns {zone: ZoneId,userInitiated: Boolean): ScheduledStart {+ val notifier = ScheduledTaskNotifier(app)val attachments = store.loadAttachments(task)if (attachments == null) {val detail = app.getString(R.string.scheduled_task_files_missing)store.update(task.id) { ScheduledTaskPlanner.notStarted(it, TaskRunStatus.NOT_STARTED, detail, now, zone) }+ // notStarted clears any wait, so its notification must go too.+ notifier.cancel(task.id)return ScheduledStart.Failed(detail)}if (!userInitiated && !ScheduledTaskScheduler.canRunUnattended(app)) {@@ -106,14 +115,37 @@ object ScheduledTaskRuns {}val result = withContext(Dispatchers.Main) { ChatRunner.of(app).startScheduled(task, attachments) }when (result) {- is ScheduledStart.Started ->+ is ScheduledStart.Started -> {store.update(task.id) { ScheduledTaskPlanner.started(it, result.sessionId, now, zone) }- ScheduledStart.Busy ->- if (!userInitiated) store.update(task.id) { ScheduledTaskPlanner.busy(it, now, zone) }- is ScheduledStart.Failed ->+ notifier.cancel(task.id)+ }+ ScheduledStart.Busy -> {+ // A paused task has no alarm coming, so a wait for it would+ // never fire: don't promise a queue, just stay busy.+ if (userInitiated && !task.enabled) return result+ // Automatic fires and manual starts alike wait their turn: the+ // occurrence is claimed and retried, never dropped. A manual+ // start reports Queued so the UI can say so; its retry fires+ // through the alarm path like any other wait.+ val updated = store.update(task.id) { ScheduledTaskPlanner.busy(it, now, zone) }+ // A wait that just gave up (SKIPPED_BUSY, no retry) is not+ // queued: report Busy so nothing is promised.+ if (updated?.retryAt != null) {+ notifier.postWaiting(updated)+ return if (userInitiated) ScheduledStart.Queued else result+ }+ notifier.cancel(task.id)+ return result+ }+ is ScheduledStart.Failed -> {store.update(task.id) {ScheduledTaskPlanner.notStarted(it, TaskRunStatus.NOT_STARTED, result.detail, now, zone)}+ notifier.cancel(task.id)+ }+ is ScheduledStart.Queued -> {+ // startScheduled never returns this; kept for exhaustiveness.+ }}return result}diff --git a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.ktindex 36bde4d..34f91c9 100644--- a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt+++ b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt@@ -11,6 +11,7 @@ import com.gotcha.i18n.stringLookupimport com.gotcha.scheduled.Repeatimport com.gotcha.scheduled.RepeatKindimport com.gotcha.scheduled.ScheduledTask+import com.gotcha.scheduled.ScheduledTaskNotifierimport com.gotcha.scheduled.ScheduledTaskPlannerimport com.gotcha.scheduled.ScheduledTaskSchedulerimport com.gotcha.scheduled.ScheduledTaskStore@@ -200,6 +201,7 @@ class ScheduledTaskTool(fun doDelete(id: String): ToolResult {val task = store.get(id) ?: return unknownTask(id)store.delete(id)+ ScheduledTaskNotifier(context).cancel(id)ScheduledTaskScheduler.reschedule(context)return ToolResult.ok("Deleted the scheduled task \"${task.name}\".")}@@ -293,6 +295,7 @@ class ScheduledTaskTool(}if (attachments != null) store.saveAttachments(saved.id, attachments)ScheduledTaskScheduler.reschedule(context)+ syncWaitingNotification(ScheduledTaskNotifier(context), existing, saved)val next = saved.dueAt?.let(::formatInstant) ?: "none"return ToolResult.ok((if (existing == null) "Scheduled" else "Updated") +@@ -532,3 +535,22 @@ private fun shortenMemoryPath(path: String): String {}}.getOrDefault(File(path).name)}++/**+ * Keeps a busy wait's notification true after an edit: a wait the edit+ * cleared must not keep it, a surviving wait is re-posted so its title stays+ * fresh. Untouched otherwise, so a tap-to-run prompt sharing the slot+ * survives an edit; pausing always dismisses.+ */+private fun syncWaitingNotification(+ notifier: ScheduledTaskNotifier,+ existing: ScheduledTask?,+ saved: ScheduledTask+) {+ val hadWait = existing?.busySince != null && existing.retryAt != null+ val hasWait = saved.enabled && saved.busySince != null && saved.retryAt != null+ when {+ !saved.enabled || (hadWait && !hasWait) -> notifier.cancel(saved.id)+ hadWait && hasWait -> notifier.postWaiting(saved)+ }+}diff --git a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.ktindex 1b83483..4e4c58d 100644--- a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt+++ b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt@@ -66,6 +66,7 @@ import com.gotcha.scheduled.RepeatKindimport com.gotcha.scheduled.ScheduledStartimport com.gotcha.scheduled.ScheduledTaskimport com.gotcha.scheduled.ScheduledTaskForm+import com.gotcha.scheduled.ScheduledTaskNotifierimport com.gotcha.scheduled.ScheduledTaskPlannerimport com.gotcha.scheduled.ScheduledTaskRunsimport com.gotcha.scheduled.ScheduledTaskScheduler@@ -141,9 +142,17 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {fun toggled(task: ScheduledTask, enabled: Boolean) {scope.launch {withContext(Dispatchers.IO) {- store.update(task.id) {+ val updated = store.update(task.id) {ScheduledTaskPlanner.toggled(it, enabled, System.currentTimeMillis(), ZoneId.systemDefault())}+ // Keep the waiting notification true: a resumed wait re-posts+ // (same quiet slot), a pause or cleared wait cancels.+ val notifier = ScheduledTaskNotifier(context)+ if (updated != null && updated.enabled && updated.busySince != null && updated.retryAt != null) {+ notifier.postWaiting(updated)+ } else {+ notifier.cancel(task.id)+ }ScheduledTaskScheduler.reschedule(context)}tick++@@ -152,6 +161,7 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {val startedText = stringResource(R.string.scheduled_run_now_started)val busyText = stringResource(R.string.scheduled_run_now_busy)+ val queuedText = stringResource(R.string.scheduled_run_now_queued)SettingsScaffold(title = stringResource(SettingsPage.SCHEDULED_TASKS.title), onBack = onBack, overlay = overlay) {Text(stringResource(R.string.scheduled_intro), style = MaterialTheme.typography.bodyMedium)if (!canRunUnattended) ExactAlarmHint(context)@@ -188,6 +198,7 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {when (result) {is ScheduledStart.Started -> startedTextScheduledStart.Busy -> busyText+ ScheduledStart.Queued -> queuedTextis ScheduledStart.Failed -> result.detail})@@ -243,6 +254,7 @@ fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {scope.launch {withContext(Dispatchers.IO) {store.delete(task.id)+ ScheduledTaskNotifier(context).cancel(task.id)ScheduledTaskScheduler.reschedule(context)}if (editing == task.id) editing = null@@ -325,6 +337,16 @@ private fun TaskRow(style = MaterialTheme.typography.bodySmall,color = MaterialTheme.colorScheme.onSurfaceVariant)+ // Queued behind another run: say so with its recheck time, or the+ // wait reads as a stuck Next line.+ val waitingAt = task.retryAt+ if (task.enabled && task.busySince != null && waitingAt != null) {+ Text(+ stringResource(R.string.scheduled_waiting_row, formatDateTime(waitingAt)),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.primary+ )+ }Text(stringResource(if (task.sameChat) R.string.scheduled_target_same_chat else R.string.scheduled_target_new_chat@@ -643,6 +665,17 @@ private fun TaskEditor(saved?.let {store.saveAttachments(it.id, files)ScheduledTaskScheduler.reschedule(context)+ // A schedule edit can clear a busy wait: refresh+ // its notification, or dismiss it when the wait+ // is gone. Untouched otherwise, so a tap-to-run+ // prompt sharing the slot survives an edit.+ if (initial?.busySince != null && initial.retryAt != null) {+ if (it.enabled && it.busySince != null && it.retryAt != null) {+ ScheduledTaskNotifier(context).postWaiting(it)+ } else {+ ScheduledTaskNotifier(context).cancel(it.id)+ }+ }}saved}diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 22ad8d9..441ed98 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -1792,6 +1792,10 @@<string name="scheduled_run_now">Run now</string><string name="scheduled_run_now_started">Started. It\'s running in its chat.</string><string name="scheduled_run_now_busy">Gotcha is busy with another task. Try again when it ends.</string>+ <string name="scheduled_run_now_queued">Queued. It will run when the current task ends.</string>+ <string name="scheduled_waiting_row">Waiting for the current run, retry at %1$s</string>+ <string name="scheduled_waiting_title">“%1$s” is waiting</string>+ <string name="scheduled_waiting_body">It will run when the current task ends.</string><string name="scheduled_history">History</string><string name="scheduled_hide_history">Hide history</string><string name="scheduled_open_chat">Open chat</string>diff --git a/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt b/app/src/test/java/com/gotcha/agent/ScheduledRunTest.ktindex c23495b..dd3dfd9 100644--- a/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt+++ b/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt@@ -28,6 +28,7 @@ import kotlinx.coroutines.runBlockingimport kotlinx.serialization.json.JsonPrimitiveimport org.junit.Assert.assertEqualsimport org.junit.Assert.assertNotNull+import org.junit.Assert.assertNullimport org.junit.Assert.assertTrueimport org.junit.Beforeimport org.junit.Test@@ -211,7 +212,7 @@ class ScheduledRunTest {}@Test- fun `a task never runs alongside another run`() {+ fun `a second start while busy queues its turn instead of dropping it`() {ServerSocket(0).use { silent ->// Holds the run's request unanswered; later ones (the title, as the// stopped run saves) are dropped at once.@@ -233,8 +234,35 @@ class ScheduledRunTest {assertTrue(first is ScheduledStart.Started)task(id = "second")- assertEquals(ScheduledStart.Busy, runNow("second"))+ assertEquals(ScheduledStart.Queued, runNow("second"))+ val queued = store.get("second")!!+ assertNotNull("a queued start keeps its retry", queued.retryAt)+ assertNotNull("a queued start keeps its wait start", queued.busySince)+ // A wait that already gave up reports Busy, not Queued.+ task(id = "third")+ store.update("third") { it.copy(busySince = System.currentTimeMillis() - 61 * 60_000L) }+ assertEquals(ScheduledStart.Busy, runNow("third"))+ assertEquals(TaskRunStatus.SKIPPED_BUSY, store.get("third")!!.lastRun!!.status)++ runner().stop()+ waitForRunToFinish()++ // The queued retry fires once the runner frees up.+ val retryAt = store.get("second")!!.retryAt!!+ val fired = CoroutineScope(Dispatchers.Unconfined).async {+ ScheduledTaskRuns.fireDue(application, retryAt)+ }+ val fireDeadline = System.currentTimeMillis() + 5_000+ while (!fired.isCompleted && System.currentTimeMillis() < fireDeadline) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(10)+ }+ runBlocking { fired.await() }+ waitForRunToFinish()+ val dequeued = store.get("second")!!+ assertNull("the retry is spent once the run starts", dequeued.retryAt)+ assertNull("the wait ends once the run starts", dequeued.busySince)runner().stop()waitForRunToFinish()}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.ktindex 2ce93b6..e0fafd4 100644--- a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt@@ -230,6 +230,19 @@ class ScheduledTaskPlannerTest {assertNull(started.busySince)}+ @Test+ fun `a manual start while busy queues behind the run and fires at its retry`() {+ // Nothing scheduled due: Run now at 07:00 only leaves a wait.+ val now = at("2026-10-19T07:00")+ val queued = ScheduledTaskPlanner.busy(daily(now), now, zone)+ assertEquals(at("2026-10-19T08:00"), queued.nextRunAt)+ assertEquals(now, queued.busySince)+ val retryAt = queued.retryAt!!+ assertEquals(now + ScheduledTaskPlanner.BUSY_RECHECK_MS, retryAt)+ // The retry is late by design, not missed: it runs.+ assertEquals(ScheduledTaskPlanner.Decision.Run, ScheduledTaskPlanner.decide(queued, retryAt, zone))+ }+@Testfun `a same-chat task keeps the chat its first run made`() {val task = daily().copy(sameChat = true)