Skip to content

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.

Review fixes: waiting notification safety and sync

Rishabh Bajpai93bbd57351fe
diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskForm.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskForm.kt
index 2ec8ef4..e598bf0 100644
--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskForm.kt
+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskForm.kt
@@ -47,7 +47,20 @@ data class ScheduledTaskForm(
* 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.
+ *
+ * [onCurrent] sees the task as stored before the save, inside the same
+ * update: callers syncing a busy wait's notification read it there, so a
+ * wait starting mid-save cannot slip through.
*/
- fun saveOver(store: ScheduledTaskStore, id: String, now: Long, zone: ZoneId): ScheduledTask? =
- store.update(id) { current -> ScheduledTaskPlanner.edited(current, applyTo(current), now, zone) }
+ fun saveOver(
+ store: ScheduledTaskStore,
+ id: String,
+ now: Long,
+ zone: ZoneId,
+ onCurrent: ((ScheduledTask) -> Unit)? = null
+ ): ScheduledTask? =
+ store.update(id) { current ->
+ onCurrent?.invoke(current)
+ ScheduledTaskPlanner.edited(current, applyTo(current), now, zone)
+ }
}
diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt
index 3f59cca..bf77891 100644
--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt
+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt
@@ -60,6 +60,10 @@ class ScheduledTaskNotifier(private val context: Context) {
* 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.
+ *
+ * The tap only opens the app: its intent carries a distinct action so the
+ * RUN_TASK_ID extra of a needs-tap PendingIntent sharing this slot can
+ * never leak onto it and start a run on tap.
*/
@Suppress("MissingPermission") // canPost() checks it.
fun postWaiting(task: ScheduledTask) {
@@ -69,6 +73,7 @@ class ScheduledTaskNotifier(private val context: Context) {
context,
notificationId(task.id),
Intent(context, MainActivity::class.java)
+ .setAction(ACTION_OPEN_WAITING)
.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK or Intent.FLAG_ACTIVITY_CLEAR_TOP),
PendingIntent.FLAG_UPDATE_CURRENT or PendingIntent.FLAG_IMMUTABLE
)
@@ -79,6 +84,7 @@ class ScheduledTaskNotifier(private val context: Context) {
.setContentText(body)
.setStyle(NotificationCompat.BigTextStyle().bigText(body))
.setCategory(NotificationCompat.CATEGORY_STATUS)
+ .setSilent(true)
.setAutoCancel(false)
.setOngoing(false)
.setOnlyAlertOnce(true)
@@ -113,7 +119,34 @@ class ScheduledTaskNotifier(private val context: Context) {
/** On the tap intent: the task MainActivity should run. */
const val EXTRA_RUN_TASK_ID = "com.gotcha.scheduled.RUN_TASK_ID"
+ /** The tap of a waiting notification only opens the app; see [postWaiting]. */
+ const val ACTION_OPEN_WAITING = "com.gotcha.scheduled.OPEN_WAITING"
+
/** One slot per task, clear of the chat slots and Gotcha's other fixed ids. */
internal fun notificationId(taskId: String): Int = 0x5C00_0000 or (taskId.hashCode() and 0x00FF_FFFF)
}
}
+
+/**
+ * Keeps a busy wait's notification true after a save: a wait the save cleared
+ * must not keep it, a surviving wait is re-posted so its title stays fresh.
+ * [hadWait] is the wait state before the save, read inside the store update
+ * so a wait starting mid-save cannot slip through. The task is re-read
+ * before acting: a run that moved it after the save owns the notification
+ * from there, and the stale snapshot could repost a cleared wait or cancel a
+ * new one. Untouched otherwise, so a tap-to-run prompt sharing the slot
+ * survives an unrelated edit; pausing always dismisses.
+ */
+fun syncWaitingNotification(
+ notifier: ScheduledTaskNotifier,
+ store: ScheduledTaskStore,
+ hadWait: Boolean,
+ saved: ScheduledTask
+) {
+ val current = store.get(saved.id) ?: saved
+ val hasWait = current.enabled && current.busySince != null && current.retryAt != null
+ when {
+ !current.enabled || (hadWait && !hasWait) -> notifier.cancel(current.id)
+ hadWait && hasWait -> notifier.postWaiting(current)
+ }
+}
diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt
index 1938c00..c808f80 100644
--- a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt
+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt
@@ -110,7 +110,7 @@ object ScheduledTaskRuns {
// Started from a window alarm, the keep-alive service is refused and the
// run would be frozen with the app; a tap on the notification runs it instead.
store.update(task.id) { ScheduledTaskPlanner.notStarted(it, TaskRunStatus.NEEDS_TAP, null, now, zone) }
- ScheduledTaskNotifier(app).postNeedsTap(task)
+ notifier.postNeedsTap(task)
return ScheduledStart.Failed(app.getString(R.string.scheduled_task_needs_exact_alarms))
}
val result = withContext(Dispatchers.Main) { ChatRunner.of(app).startScheduled(task, attachments) }
@@ -126,11 +126,15 @@ object ScheduledTaskRuns {
// 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) }
+ // through the alarm path like any other wait. The enabled
+ // check runs inside the update: a pause landing mid-start
+ // must not leave a wait no alarm will ever fire.
+ val updated = store.update(task.id) {
+ if (!it.enabled) it else 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) {
+ if (updated?.enabled == true && updated.retryAt != null) {
notifier.postWaiting(updated)
return if (userInitiated) ScheduledStart.Queued else result
}
@@ -143,7 +147,7 @@ object ScheduledTaskRuns {
}
notifier.cancel(task.id)
}
- is ScheduledStart.Queued -> {
+ ScheduledStart.Queued -> {
// startScheduled never returns this; kept for exhaustiveness.
}
}
diff --git a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt
index 34f91c9..d7a9bad 100644
--- a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt
+++ b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt
@@ -16,6 +16,7 @@ import com.gotcha.scheduled.ScheduledTaskPlanner
import com.gotcha.scheduled.ScheduledTaskScheduler
import com.gotcha.scheduled.ScheduledTaskStore
import com.gotcha.scheduled.isWallTimeFuture
+import com.gotcha.scheduled.syncWaitingNotification
import kotlinx.serialization.Serializable
import kotlinx.serialization.json.Json
import kotlinx.serialization.json.JsonArray
@@ -277,6 +278,7 @@ class ScheduledTaskTool(
}
)
}
+ var hadWait = false
val saved = if (existing == null) {
val created = ScheduledTask(
id = UUID.randomUUID().toString(),
@@ -289,13 +291,17 @@ class ScheduledTaskTool(
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()) }
+ // approval was asked keeps its history and next time. The wait
+ // state is read inside the same update for the notification sync.
+ store.update(existing.id) { current ->
+ hadWait = current.busySince != null && current.retryAt != null
+ ScheduledTaskPlanner.edited(current, edit(current), now, zone())
+ }
?: return unknownTask(existing.id)
}
if (attachments != null) store.saveAttachments(saved.id, attachments)
ScheduledTaskScheduler.reschedule(context)
- syncWaitingNotification(ScheduledTaskNotifier(context), existing, saved)
+ syncWaitingNotification(ScheduledTaskNotifier(context), store, hadWait, saved)
val next = saved.dueAt?.let(::formatInstant) ?: "none"
return ToolResult.ok(
(if (existing == null) "Scheduled" else "Updated") +
@@ -535,22 +541,3 @@ 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.kt
index 4e4c58d..8484800 100644
--- a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt
+++ b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt
@@ -74,6 +74,7 @@ import com.gotcha.scheduled.ScheduledTaskStore
import com.gotcha.scheduled.TaskRun
import com.gotcha.scheduled.TaskRunStatus
import com.gotcha.scheduled.isWallTimeFuture
+import com.gotcha.scheduled.syncWaitingNotification
import com.gotcha.service.ChatRunService
import com.gotcha.tools.AgentMode
import com.gotcha.ui.theme.SkinAlertDialog
@@ -328,9 +329,17 @@ private fun TaskRow(
)
}
val next = task.dueAt
+ // While waiting, dueAt is the retry time, shown again on the line
+ // below: the primary line keeps the regular schedule instead.
+ val waitingAt = task.retryAt
+ val waiting = task.enabled && task.busySince != null && waitingAt != null
+ val nextScheduled = task.nextRunAt
Text(
when {
!task.enabled -> stringResource(R.string.scheduled_paused)
+ waiting && nextScheduled != null ->
+ stringResource(R.string.scheduled_next_run, formatDateTime(nextScheduled))
+ waiting -> stringResource(R.string.scheduled_no_more_runs)
next == null -> stringResource(R.string.scheduled_no_more_runs)
else -> stringResource(R.string.scheduled_next_run, formatDateTime(next))
},
@@ -339,8 +348,7 @@ private fun TaskRow(
)
// 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) {
+ if (waiting) {
Text(
stringResource(R.string.scheduled_waiting_row, formatDateTime(waitingAt)),
style = MaterialTheme.typography.bodySmall,
@@ -643,6 +651,9 @@ private fun TaskEditor(
attachmentNames = files.map { it.name }
)
scope.launch {
+ // Read inside the save's own update (see saveOver): a
+ // wait starting while the form was open still syncs.
+ var hadWait = false
val saved = withContext(Dispatchers.IO) {
val now = System.currentTimeMillis()
val zone = ZoneId.systemDefault()
@@ -660,22 +671,14 @@ private fun TaskEditor(
} 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)
+ form.saveOver(store, initial.id, now, zone) { current ->
+ hadWait = current.busySince != null && current.retryAt != null
+ }
}
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)
- }
- }
+ syncWaitingNotification(ScheduledTaskNotifier(context), store, hadWait, it)
}
saved
}
diff --git a/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt b/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt
index dd3dfd9..6c3a831 100644
--- a/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt
+++ b/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt
@@ -7,6 +7,7 @@ import androidx.core.app.NotificationCompat
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.ViewModelStore
import androidx.test.core.app.ApplicationProvider
+import com.gotcha.R
import com.gotcha.data.ChatHistoryRepository
import com.gotcha.data.ChatSession
import com.gotcha.data.LlmProvider
@@ -15,6 +16,7 @@ import com.gotcha.data.SettingsRepository
import com.gotcha.llm.ChatMessage
import com.gotcha.scheduled.ScheduledStart
import com.gotcha.scheduled.ScheduledTask
+import com.gotcha.scheduled.ScheduledTaskNotifier
import com.gotcha.scheduled.ScheduledTaskRuns
import com.gotcha.scheduled.ScheduledTaskStore
import com.gotcha.scheduled.TaskRunStatus
@@ -76,14 +78,20 @@ class ScheduledRunTest {
private fun runner() = ChatRunner.of(application)
- private fun task(id: String = "news", sameChat: Boolean = false, chat: String? = null) = ScheduledTask(
+ private fun task(
+ id: String = "news",
+ sameChat: Boolean = false,
+ chat: String? = null,
+ enabled: Boolean = true
+ ) = ScheduledTask(
id = id,
name = "Morning news",
prompt = "Summarise the news",
startLocal = "2099-01-01T08:00",
agentMode = AgentMode.MONITOR.name,
sameChat = sameChat,
- chatSessionId = chat
+ chatSessionId = chat,
+ enabled = enabled
).also { store.put(it) }
/** Runs [id] as "Run now" does, letting the main looper turn until it has started. */
@@ -238,6 +246,12 @@ class ScheduledRunTest {
val queued = store.get("second")!!
assertNotNull("a queued start keeps its retry", queued.retryAt)
assertNotNull("a queued start keeps its wait start", queued.busySince)
+ val waitingTitle = application.getString(R.string.scheduled_waiting_title, "Morning news")
+ fun waitingPosted() = shadowOf(manager).allNotifications.any {
+ it.channelId == ScheduledTaskNotifier.CHANNEL_ID &&
+ it.extras.getString(NotificationCompat.EXTRA_TITLE) == waitingTitle
+ }
+ assertTrue("queueing posts the waiting notification", waitingPosted())
// A wait that already gave up reports Busy, not Queued.
task(id = "third")
@@ -245,6 +259,13 @@ class ScheduledRunTest {
assertEquals(ScheduledStart.Busy, runNow("third"))
assertEquals(TaskRunStatus.SKIPPED_BUSY, store.get("third")!!.lastRun!!.status)
+ // A paused task is promised no queue: nothing is persisted.
+ task(id = "fourth", enabled = false)
+ assertEquals(ScheduledStart.Busy, runNow("fourth"))
+ val paused = store.get("fourth")!!
+ assertNull(paused.retryAt)
+ assertNull(paused.busySince)
+
runner().stop()
waitForRunToFinish()
@@ -263,6 +284,7 @@ class ScheduledRunTest {
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)
+ assertTrue("starting the run clears the waiting notification", !waitingPosted())
runner().stop()
waitForRunToFinish()
}