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.
feat(scheduled): scheduled tasks that start agent chats (#132)
Durganshu31b610f64f25
diff --git a/app/src/main/AndroidManifest.xml b/app/src/main/AndroidManifest.xmlindex 56b08b8..f2da7fd 100644--- a/app/src/main/AndroidManifest.xml+++ b/app/src/main/AndroidManifest.xml@@ -285,9 +285,10 @@android:name=".notifications.ReminderCheckReceiver"android:exported="false" />- <!-- Re-arms those alarms, which a reboot, an app update or a clock change would- otherwise lose or misplace. All four broadcasts are protected and exempt from the- implicit-broadcast limits. -->+ <!-- Re-arms those alarms and the scheduled tasks' one, which a reboot, an app update or+ a clock change would otherwise lose or misplace. All five broadcasts are protected+ and exempt from the implicit-broadcast limits; the last one is sent when the+ exact-alarm grant changes. --><receiverandroid:name=".notifications.NotificationRescheduleReceiver"android:exported="true">@@ -296,9 +297,17 @@<action android:name="android.intent.action.MY_PACKAGE_REPLACED" /><action android:name="android.intent.action.TIMEZONE_CHANGED" /><action android:name="android.intent.action.TIME_SET" />+ <action android:name="android.app.action.SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED" /></intent-filter></receiver>+ <!-- Scheduled tasks (issue #132): the alarm that starts a task's run, and the tap on a+ task's "tap to run" notification. Not exported: only Gotcha's own PendingIntents+ fire it. -->+ <receiver+ android:name=".scheduled.ScheduledTaskReceiver"+ android:exported="false" />+<receiverandroid:name=".tools.WakeWordBootReceiver"android:exported="true">diff --git a/app/src/main/assets/app/about-gotcha.md b/app/src/main/assets/app/about-gotcha.mdindex 59f213f..7ef77a5 100644--- a/app/src/main/assets/app/about-gotcha.md+++ b/app/src/main/assets/app/about-gotcha.md@@ -32,6 +32,13 @@ mid-conversation.the call log, find and add contacts, send and read SMS.- **Calendar** — list, create, edit and delete events, and check availability.- **Clock** — set and edit alarms and timers, list them, snooze, dismiss.+- **Scheduled tasks** — in Operator, set up a prompt for Gotcha to run by itself+ later, once or on repeat (every few hours or days, chosen weekdays, monthly),+ in a new chat each time or always the same one, with `schedule_agent_task`;+ change, pause or delete one with `edit_scheduled_task` and+ `delete_scheduled_task`; list them in either mode with `list_scheduled_tasks`.+ The user approves every task you set up. A run that a schedule started cannot+ set up or change tasks. The user can also add tasks themselves in Settings.- **Files** — list, read, write, edit surgically, grep, glob, and report storage.- **Documents and media** — parse and edit PDFs, edit audio and video, convertaudio formats (via Termux ffmpeg), take photos, record audio, transcribe audio@@ -72,6 +79,7 @@ Everything below is reached from **Settings** in the navigation drawer.| Permissions | Every runtime and special-access permission, grouped: Communications, Contacts, Calendar, Media & Storage, Location, Device Control, Notifications, System Access, Health || Termux (Linux shell) | Guided setup for the Linux shell used by `run_termux_command` and audio conversion || Skills / Plugins | Built-in skills, importing community skills by URL, allowed community skill hosts |+| Scheduled tasks | Prompts Gotcha runs by itself at set times: add, edit, pause, delete or run one now; the history of each one's runs, failures included, with a link to the chat each run went into. Without "Alarms & reminders" allowed for Gotcha, a task cannot start on its own and asks for a tap on a notification instead; the page links to that permission || Proactive Assistance | Master switch for proactive offers, OTP/code detection, auto-copy OTP, and what may be scanned (screen content, notifications, clipboard) || Assistive Ball and Wake Word | The floating ball over other apps, hands-free voice calls, turning Night Light off for screenshots, the "Hey Gotcha" wake word, when it listens, and detection sensitivity || Appearance | Theme |diff --git a/app/src/main/java/com/gotcha/GotchaApp.kt b/app/src/main/java/com/gotcha/GotchaApp.ktindex ce4118d..44896a5 100644--- a/app/src/main/java/com/gotcha/GotchaApp.kt+++ b/app/src/main/java/com/gotcha/GotchaApp.kt@@ -1,6 +1,8 @@package com.gotcha+import android.app.Activityimport android.app.Application+import android.os.Bundleimport android.util.Logimport com.gotcha.agent.ChatRunnerimport java.io.File@@ -29,8 +31,33 @@ class GotchaApp : Application() {*/val chatRunner: ChatRunner by lazy { ChatRunner(this) }+ @Volatile+ private var startedActivities = 0++ /**+ * True while any of Gotcha's screens is started. False in a process an alarm+ * started with no screen at all, which a scheduled task's run needs to know+ * (issue #132): nothing else has told the runner it is out of sight.+ */+ val hasStartedActivity: Boolean get() = startedActivities > 0+override fun onCreate() {super.onCreate()+ registerActivityLifecycleCallbacks(object : ActivityLifecycleCallbacks {+ override fun onActivityStarted(activity: Activity) {+ startedActivities+++ }++ override fun onActivityStopped(activity: Activity) {+ startedActivities = (startedActivities - 1).coerceAtLeast(0)+ }++ override fun onActivityCreated(activity: Activity, savedInstanceState: Bundle?) = Unit+ override fun onActivityResumed(activity: Activity) = Unit+ override fun onActivityPaused(activity: Activity) = Unit+ override fun onActivitySaveInstanceState(activity: Activity, outState: Bundle) = Unit+ override fun onActivityDestroyed(activity: Activity) = Unit+ })// pdfbox ships its glyph tables as Android assets; the resource loader// needs a Context before the first PDF text extraction (DocumentParser).com.gotcha.tools.DocumentParser.init(this)diff --git a/app/src/main/java/com/gotcha/MainActivity.kt b/app/src/main/java/com/gotcha/MainActivity.ktindex 47a1a71..01a844f 100644--- a/app/src/main/java/com/gotcha/MainActivity.kt+++ b/app/src/main/java/com/gotcha/MainActivity.kt@@ -61,6 +61,10 @@ import com.gotcha.notifications.NotificationDispatcherimport com.gotcha.notifications.NotificationPayloadimport com.gotcha.notifications.NotificationTargetimport com.gotcha.notifications.ServerMessages+import com.gotcha.scheduled.ScheduledStart+import com.gotcha.scheduled.ScheduledTaskNotifier+import com.gotcha.scheduled.ScheduledTaskRuns+import com.gotcha.scheduled.ScheduledTaskSchedulerimport com.gotcha.service.AssistiveBallServiceimport com.gotcha.service.GotchaDeviceAdminReceiverimport com.gotcha.tools.AgentMode@@ -336,6 +340,9 @@ class MainActivity : ComponentActivity() {// notification alarms are armed here too. Re-arming is idempotent.lifecycleScope.launch(Dispatchers.IO) {runCatching { LocalNotificationScheduler.scheduleAll(applicationContext) }+ // An alarm already past fires at once, so a task due while Gotcha could+ // not run it gets its turn now (issue #132).+ runCatching { ScheduledTaskScheduler.reschedule(applicationContext) }// Re-arming pushes the 4-hour check back, so someone who opens Gotcha// more often than that would never reach the update check through the// alarm alone. It limits itself to about twice a day (issue #126).@@ -598,6 +605,11 @@ class MainActivity : ComponentActivity() {// Consumed, as above: a recreation must not open another chat.intent.removeExtra(LocalNotifier.EXTRA_DRAFT_PROMPT)}+ intent?.getStringExtra(ScheduledTaskNotifier.EXTRA_RUN_TASK_ID)?.let { taskId ->+ // Consumed, as above: a recreation must not run the task again.+ intent.removeExtra(ScheduledTaskNotifier.EXTRA_RUN_TASK_ID)+ runScheduledTask(taskId)+ }if (intent?.getBooleanExtra(LocalNotifier.EXTRA_OPEN_UPDATE, false) == true) {openUpdateRequested = trueintent.removeExtra(LocalNotifier.EXTRA_OPEN_UPDATE)@@ -626,6 +638,24 @@ class MainActivity : ComponentActivity() {}}+ /**+ * A tap on a scheduled task's "tap to run" notification (issue #132): the+ * task runs now, and its chat opens to show it working.+ */+ private fun runScheduledTask(taskId: String) {+ ScheduledTaskNotifier(this).cancel(taskId)+ lifecycleScope.launch {+ val result = withContext(Dispatchers.IO) { ScheduledTaskRuns.runNow(application, taskId) }+ when (result) {+ is ScheduledStart.Started -> openSessionRequested = result.sessionId+ ScheduledStart.Busy ->+ Toast.makeText(this@MainActivity, R.string.scheduled_run_now_busy, Toast.LENGTH_LONG).show()+ is ScheduledStart.Failed ->+ Toast.makeText(this@MainActivity, result.detail, Toast.LENGTH_LONG).show()+ }+ }+ }+override fun onStart() {super.onStart()chatViewModel.setForeground(true)@@ -1059,6 +1089,10 @@ class MainActivity : ComponentActivity() {},onStartTour = { startTour() },onSendFeedback = { showFeedbackSheet = true },+ onOpenChat = { id ->+ chatViewModel.openSession(id)+ currentRoute = Route.HOME+ },page = settingsPage,onPageChange = {settingsPage = itdiff --git a/app/src/main/java/com/gotcha/agent/AgentEngine.kt b/app/src/main/java/com/gotcha/agent/AgentEngine.ktindex cc7bfce..872730d 100644--- a/app/src/main/java/com/gotcha/agent/AgentEngine.kt+++ b/app/src/main/java/com/gotcha/agent/AgentEngine.kt@@ -24,6 +24,7 @@ import com.gotcha.tools.AppNavigatorSessionimport com.gotcha.tools.DeviceCapabilitiesimport com.gotcha.tools.FileResolverimport com.gotcha.tools.GotchaSettingsUpdate+import com.gotcha.tools.ScheduledTaskToolimport com.gotcha.tools.ScreenPerceptionimport com.gotcha.tools.SubAgentSessionimport com.gotcha.tools.ToolExecutor@@ -34,7 +35,9 @@ import com.gotcha.ui.personaByIdimport com.gotcha.util.GotchaLogimport com.gotcha.util.HumanReadableErrorimport kotlinx.coroutines.CancellationException+import kotlinx.coroutines.Dispatchersimport kotlinx.coroutines.delay+import kotlinx.coroutines.withContextimport kotlinx.coroutines.withTimeoutOrNullimport kotlinx.serialization.json.Jsonimport kotlinx.serialization.json.JsonArray@@ -109,6 +112,14 @@ class AgentEngine(*/var sessionPersonaId: String? = null+ /**+ * True while the run was started by a scheduled task rather than by the user+ * (issue #132). The schedule tools are withheld from it, so a prompt injected+ * into an unattended run can't schedule more of them.+ */+ @Volatile+ var scheduledRun: Boolean = false+/*** Stable key for the provider's server-side prompt KV cache* (`prompt_cache_key` / `X-Session-Id`), independent of [sessionId] which@@ -710,6 +721,19 @@ class AgentEngine(handleDeleteConfirm("CONFIRM_DELETE_TIMER:", "timer", call, result)} else if (result.success && result.message.startsWith("CONFIRM_DELETE_CALENDAR_EVENT:")) {handleDeleteConfirm("CONFIRM_DELETE_CALENDAR_EVENT:", "calendar_event", call, result)+ } else if (result.success &&+ result.message.startsWith(ScheduledTaskTool.DELETE_CONFIRM_PREFIX)+ ) {+ handleDeleteConfirm(+ ScheduledTaskTool.DELETE_CONFIRM_PREFIX,+ "scheduled_task",+ call,+ result+ )+ } else if (result.success &&+ result.message.startsWith(ScheduledTaskTool.CONFIRM_PREFIX)+ ) {+ handleScheduleTaskConfirm(call, result, agent)} else if (result.success && result.message.startsWith("CONFIRM_SEND_EMAIL:")) {handleSendEmailConfirm(call, result)} else if (result.success &&@@ -1117,6 +1141,47 @@ class AgentEngine()}+ /**+ * Handles a tool result prefixed with CONFIRM_SCHEDULE_TASK:base64(request)+ * (issue #132). A scheduled task runs the agent later with nobody watching,+ * so every create and every edit asks, showing the task exactly as it would+ * be saved. Its mode is capped at [agent], this run's own. Nothing is saved+ * unless the user allows it; an unanswered prompt counts as declined.+ */+ private suspend fun handleScheduleTaskConfirm(call: ToolCall, result: ToolResult, agent: AgentMode) {+ val request = ScheduledTaskTool.decodePayload(+ result.message.removePrefix(ScheduledTaskTool.CONFIRM_PREFIX)+ )+ var declined = false+ val outcome = if (request == null) {+ ToolResult.error("Failed to read the scheduled task request. Nothing was saved.")+ } else {+ val approved = events.awaitConfirmation(+ listOf(call.function.name),+ withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.describe(request, agent) }+ )+ val decided = if (approved) {+ withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.apply(request, sessionId, agent) }+ } else {+ declined = true+ ToolResult.error(+ "The user declined; nothing was scheduled or changed. Do not retry unless the user asks again."+ )+ }+ toolExecutor.actionLog.record(+ call.function.name,+ (if (approved) "(approved) " else "(denied) ") + (request.taskId ?: request.name.orEmpty()),+ decided+ )+ decided+ }+ history += ChatMessage(role = "tool", content = JsonPrimitive(outcome.message), toolCallId = call.id)+ events.onUi(+ if (outcome.success || declined) MessageKind.TOOL else MessageKind.ERROR,+ "${call.function.name}: ${outcome.message}"+ )+ }+private suspend fun handleDeleteConfirm(confirmPrefix: String, kind: String, call: ToolCall, result: ToolResult) {val body = result.message.removePrefix(confirmPrefix)val parts = body.split(":", limit = 2)@@ -1130,6 +1195,8 @@ class AgentEngine("alarm" -> toolExecutor.executeDeleteAlarm(id.toLong())"timer" -> toolExecutor.executeDeleteTimer(id.toLong())"calendar_event" -> toolExecutor.executeDeleteCalendarEvent(id.toLong())+ "scheduled_task" -> withContext(Dispatchers.IO) { toolExecutor.scheduledTaskTool.doDelete(id) }+ .also { toolExecutor.actionLog.record("delete_scheduled_task", "(confirmed) $id", it) }else -> return}} else {@@ -1243,7 +1310,9 @@ class AgentEngine(*/private fun hiddenTools(): Set<String> =ConnectorRegistry.hiddenToolNames(settings.disabledConnectors) +- DeviceCapabilities.hiddenToolNames(appContext)+ DeviceCapabilities.hiddenToolNames(appContext) ++ // A run a schedule started can't plant, re-enable or widen tasks (issue #132).+ (if (scheduledRun) ScheduledTaskTool.TOOL_NAMES else emptySet())/*** A separate system message carrying only the current date/time.diff --git a/app/src/main/java/com/gotcha/agent/AttachmentFiles.kt b/app/src/main/java/com/gotcha/agent/AttachmentFiles.ktnew file mode 100644index 0000000..91fa777--- /dev/null+++ b/app/src/main/java/com/gotcha/agent/AttachmentFiles.kt@@ -0,0 +1,62 @@+package com.gotcha.agent++import android.graphics.Bitmap+import android.graphics.BitmapFactory+import com.gotcha.tools.DocumentParser+import com.gotcha.tools.ScreenPerception++/**+ * Turns a file's bytes into a [ComposerAttachment] the way the composer does:+ * an image is downscaled to JPEG base64, anything else has its text extracted+ * by [DocumentParser]. Shared by the composer and scheduled tasks (issue #132),+ * whose files are read once, when the task is saved.+ */+internal object AttachmentFiles {++ /**+ * Null when [bytes] claim to be an image that can't be decoded. An unreadable+ * or unsupported document throws [com.gotcha.tools.DocumentError], whose+ * message is fit to show the user.+ */+ fun fromBytes(bytes: ByteArray, name: String, mimeType: String?, maxDimension: Int = 1024): ComposerAttachment? {+ val id = java.util.UUID.randomUUID().toString()+ if (mimeType?.startsWith("image/") == true) {+ return imageBase64(bytes, maxDimension)?.let { ComposerAttachment.Image(id, name, it) }+ }+ val extracted = DocumentParser.extract(bytes, name, mimeType)+ return ComposerAttachment.Document(+ id,+ Attachment(+ name = name,+ mimeType = extracted.mimeType,+ size = bytes.size.toLong(),+ text = extracted.text,+ pageCount = extracted.pageCount,+ truncated = extracted.truncated+ )+ )+ }++ fun imageBase64(bytes: ByteArray, maxDimension: Int = 1024): String? = try {+ BitmapFactory.decodeByteArray(bytes, 0, bytes.size)?.let { bitmap ->+ ScreenPerception.compressBitmap(+ bitmap = bitmap,+ maxDimension = maxDimension,+ quality = 85,+ format = Bitmap.CompressFormat.JPEG,+ recycleInput = true+ )+ }+ } catch (_: Exception) {+ null+ }++ /** A MIME type for a file the agent names by path, from its extension. */+ fun mimeTypeFor(name: String): String? =+ android.webkit.MimeTypeMap.getSingleton()+ .getMimeTypeFromExtension(name.substringAfterLast('.', "").lowercase())++ /** Extracted document text across [attachments], to hold to [ComposerAttachment.MAX_TOTAL_DOCUMENT_CHARS]. */+ fun documentChars(attachments: List<ComposerAttachment>): Int =+ attachments.sumOf { (it as? ComposerAttachment.Document)?.attachment?.text?.length ?: 0 }+}diff --git a/app/src/main/java/com/gotcha/agent/ChatRunner.kt b/app/src/main/java/com/gotcha/agent/ChatRunner.ktindex 25d68b9..7167247 100644--- a/app/src/main/java/com/gotcha/agent/ChatRunner.kt+++ b/app/src/main/java/com/gotcha/agent/ChatRunner.kt@@ -27,6 +27,10 @@ import com.gotcha.notifications.LocalNotificationStoreimport com.gotcha.notifications.NotificationCategoryimport com.gotcha.notifications.NotificationTargetimport com.gotcha.notifications.RunOutcome+import com.gotcha.scheduled.ScheduledStart+import com.gotcha.scheduled.ScheduledTask+import com.gotcha.scheduled.ScheduledTaskRuns+import com.gotcha.scheduled.TaskRunStatusimport com.gotcha.service.ChatRunServiceimport com.gotcha.service.RunningChatimport com.gotcha.tools.AgentMode@@ -214,6 +218,12 @@ class ChatRunner(private val app: Application) : AgentEvents {/** Next UiMessage id in [RunState.transcript]. */private var nextTranscriptId = 0L+ /**+ * The scheduled task whose run is in flight (issue #132), or null for a run+ * the user started. Its outcome goes into the task's history.+ */+ private var scheduledTask: ScheduledTask? = null+/** Agent mode of the session currently bound to [engine]. */internal var engineAgent: AgentMode = AgentMode.MONITOR@@ -449,6 +459,41 @@ class ChatRunner(private val app: Application) : AgentEvents {}}+ /**+ * Starts the run of scheduled [task] (issue #132), with its prompt and+ * [attachments] as the user's message: in a new chat, or at the end of the+ * task's chat in same-chat mode, falling back to a new chat when that one+ * is gone. Never runs alongside another run. The screen is left where it is:+ * it only follows the run when the user is already looking at that chat.+ */+ internal suspend fun startScheduled(task: ScheduledTask, attachments: List<ComposerAttachment>): ScheduledStart {+ startup.join()+ if (isRunning || agentJob?.isActive == true) return ScheduledStart.Busy+ val saved = task.chatSessionId?.takeIf { task.sameChat }?.let { historyRepository.loadSession(it) }+ // Loading the chat suspended: a send may have started meanwhile.+ if (isRunning || agentJob?.isActive == true) return ScheduledStart.Busy+ // The alarm may have started the process: with no screen ever shown,+ // nothing has said yet that Gotcha is out of sight.+ if ((app as? GotchaApp)?.hasStartedActivity == false) appInForeground = false+ if (saved != null) {+ bindSaved(saved, task.mode, saved.displayMessages)+ } else {+ bindFresh(java.util.UUID.randomUUID().toString(), task.mode)+ engine.sessionPersonaId = task.personaId+ }+ val runningId = engine.sessionId ?: return ScheduledStart.Failed("No chat to run in.")+ scheduledTask = task+ engine.scheduledRun = true+ currentRunIsVoice = false+ val msg = buildUserMessage(task.prompt, attachments)+ engine.history += msg+ appendTranscript(MessageKind.USER, userDisplayText(task.prompt, msg, attachments), attachments = attachments)+ // Main.immediate: executeRun marks the run busy and starts the keep-alive+ // service before this returns, while the alarm's grace period still holds.+ agentJob = scope.launch { executeRun(engineAgent, runningId) }+ return ScheduledStart.Started(runningId)+ }+/*** Replaces the user message [targetId] in [view] with [text] and* [attachments] (null keeps the original ones), drops everything after it@@ -617,6 +662,20 @@ class ChatRunner(private val app: Application) : AgentEvents {})}+ scheduledTask?.let { task ->+ scheduledTask = null+ engine.scheduledRun = false+ val status = when {+ stopped || engine.isDiscarded(runningId) -> TaskRunStatus.STOPPED+ runEndedOnError -> TaskRunStatus.FAILED+ else -> TaskRunStatus.DONE+ }+ val error = _state.value.transcript.lastOrNull { it.kind == MessageKind.ERROR }?.text+ ?.takeIf { status == TaskRunStatus.FAILED }+ withContext(Dispatchers.IO) {+ runCatching { ScheduledTaskRuns.recordOutcome(app, task.id, runningId, status, error) }+ }+ }// In the background the ongoing notification turns into the// finished one, in the same slot (issue #115).if (finished != null) {@@ -1053,8 +1112,10 @@ class ChatRunner(private val app: Application) : AgentEvents {// Issue #100: a chat kept out of notifications, or chats not to be named// at all, get a notification that says only that a task finished.val named = mayNameChat(sessionId)+ // A scheduled run is named after its task (issue #132), which says more than a new chat's title.+ val chatTitle = scheduledTask?.name ?: engine.currentTitle()val title = if (named) {- ChatCompletionNotifier.notificationTitle(engine.currentTitle(), outcome, app.stringLookup())+ ChatCompletionNotifier.notificationTitle(chatTitle, outcome, app.stringLookup())} else {app.getString(ChatCompletionNotifier.anonymousTitle(outcome))}@@ -1066,7 +1127,7 @@ class ChatRunner(private val app: Application) : AgentEvents {)return completionNotifier.build(sessionId = sessionId,- chatTitle = engine.currentTitle(),+ chatTitle = chatTitle,outcome = outcome,reply = reply,preview = settings.chatCompletionPreview,diff --git a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt b/app/src/main/java/com/gotcha/agent/ChatViewModel.ktindex c947d47..b9415aa 100644--- a/app/src/main/java/com/gotcha/agent/ChatViewModel.kt+++ b/app/src/main/java/com/gotcha/agent/ChatViewModel.kt@@ -1127,6 +1127,10 @@ class ChatViewModel(application: Application) : AndroidViewModel(application), C}historyRepository.deleteSession(id)localNotificationStore.forgetChat(id)+ // A same-chat task pinned to it starts a new chat next time (issue #132).+ withContext(Dispatchers.IO) {+ runCatching { com.gotcha.scheduled.ScheduledTaskStore(getApplication()).forgetChat(id) }+ }if (_uiState.value.activeSessionId == id) {clearChat()} else if (wasBound) {diff --git a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.ktindex 14aa053..a71efb5 100644--- a/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt+++ b/app/src/main/java/com/gotcha/notifications/LocalNotificationScheduler.kt@@ -9,6 +9,7 @@ import android.util.Logimport com.gotcha.data.ChatHistoryRepositoryimport com.gotcha.data.SettingsRepositoryimport com.gotcha.i18n.stringLookup+import com.gotcha.scheduled.ScheduledTaskSchedulerimport com.gotcha.updater.runUpdateCheckimport kotlinx.coroutines.CoroutineScopeimport kotlinx.coroutines.Dispatchers@@ -79,7 +80,7 @@ private fun BroadcastReceiver.runAsync(tag: String, block: suspend () -> Unit) {/*** Re-arms the alarms after a reboot, an app update or a clock change — none of- * which an alarm survives at the right time. Exported only because those+ * which an alarm survives at the right time — scheduled tasks' included. Exported only because those* broadcasts come from the system; it never posts anything itself.*/class NotificationRescheduleReceiver : BroadcastReceiver() {@@ -87,16 +88,31 @@ class NotificationRescheduleReceiver : BroadcastReceiver() {override fun onReceive(context: Context, intent: Intent) {if (intent.action !in RESCHEDULE_ACTIONS) returnval app = context.applicationContext- runAsync(TAG) { LocalNotificationScheduler.scheduleAll(app) }+ runAsync(TAG) {+ // finally: a failure arming one set of alarms must not leave the other unarmed.+ try {+ if (intent.action != ACTION_EXACT_ALARM_PERMISSION_CHANGED) LocalNotificationScheduler.scheduleAll(app)+ } finally {+ ScheduledTaskScheduler.reschedule(app)+ }+ }}private companion object {const val TAG = "NotificationReschedule"++ /**+ * The exact-alarm grant changing: scheduled tasks (issue #132) switch+ * between an exact alarm and a window. AlarmManager's constant is API 31+.+ */+ const val ACTION_EXACT_ALARM_PERMISSION_CHANGED =+ "android.app.action.SCHEDULE_EXACT_ALARM_PERMISSION_STATE_CHANGED"val RESCHEDULE_ACTIONS = setOf(Intent.ACTION_BOOT_COMPLETED,Intent.ACTION_MY_PACKAGE_REPLACED,Intent.ACTION_TIMEZONE_CHANGED,- Intent.ACTION_TIME_CHANGED+ Intent.ACTION_TIME_CHANGED,+ ACTION_EXACT_ALARM_PERMISSION_CHANGED)}}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTask.ktnew file mode 100644index 0000000..cb6b3b4--- /dev/null+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTask.kt@@ -0,0 +1,197 @@+package com.gotcha.scheduled++import com.gotcha.tools.AgentMode+import kotlinx.serialization.Serializable+import java.time.DayOfWeek+import java.time.Instant+import java.time.LocalDateTime+import java.time.YearMonth+import java.time.ZoneId+import java.time.temporal.ChronoUnit++/** How often a [ScheduledTask] comes round again (issue #132). */+@Serializable+enum class RepeatKind { NONE, HOURLY, DAILY, WEEKLY, MONTHLY }++/**+ * A task's repeat rule. [interval] is the N in "every N hours" or "every N+ * days", and is ignored by the other kinds. [weekdays] are ISO day numbers+ * (1 = Monday … 7 = Sunday) for [RepeatKind.WEEKLY]; empty means the start+ * date's own weekday. A monthly task repeats on its start date's day of the+ * month, or the month's last day when the month is shorter.+ */+@Serializable+data class Repeat(+ val kind: RepeatKind = RepeatKind.NONE,+ val interval: Int = 1,+ val weekdays: List<Int> = emptyList()+)++/** How one firing of a task ended, as its history lists it. */+@Serializable+enum class TaskRunStatus {+ /** The run finished with a reply. */+ DONE,++ /** The run ended on an error: the model was unreachable, not configured, … */+ FAILED,++ /** Someone stopped the run. */+ STOPPED,++ /** The phone was off or asleep well past the time, so the run was not started. */+ MISSED,++ /** Another run held Gotcha for too long, so this one never got its turn. */+ SKIPPED_BUSY,++ /** Android would not let the task run unattended; a notification asks for a tap. */+ NEEDS_TAP,++ /** The task could not be started: its files went missing, say. [TaskRun.detail] says why. */+ NOT_STARTED+}++@Serializable+data class TaskRun(+ val at: Long,+ val status: TaskRunStatus,+ /** The chat the run went into, when it started one. */+ val sessionId: String? = null,+ /** The error shown at the end of a failed run, or why it did not start. */+ val detail: String? = null+)++/**+ * A prompt Gotcha sends itself at a set time (issue #132). When it fires, an+ * ordinary agent run starts with [prompt] (and [attachmentNames]' files) as the+ * user's message, in a new chat, or in [chatSessionId] when [sameChat] is on.+ *+ * [startLocal] is a local date-time ("2026-10-19T08:00"), not an instant, so a+ * daily 8:00 task stays at 8:00 wherever the phone is and across a change to+ * summer time. [nextRunAt] is the next time it is due by its schedule, null once+ * a one-time task has had its turn; [retryAt] is a sooner re-try of the current+ * one, after a failure or while another run holds Gotcha.+ */+@Serializable+data class ScheduledTask(+ val id: String,+ val name: String,+ val prompt: String,+ val startLocal: String,+ val repeat: Repeat = Repeat(),+ val enabled: Boolean = true,+ /** [AgentMode] name. */+ val agentMode: String = AgentMode.MONITOR.name,+ val personaId: String? = null,+ val sameChat: Boolean = false,+ val chatSessionId: String? = null,+ /** How many times a failed run is tried again before the occurrence is given up. */+ val maxRetries: Int = DEFAULT_MAX_RETRIES,+ val retryDelayMinutes: Int = DEFAULT_RETRY_DELAY_MINUTES,+ /** True for a task the agent set up with schedule_agent_task, which the user approved. */+ val createdByAgent: Boolean = false,+ /** Names of the files stored with the task; the files themselves are in [ScheduledTaskStore]. */+ val attachmentNames: List<String> = emptyList(),+ val createdAt: Long = 0L,+ val nextRunAt: Long? = null,+ val retryAt: Long? = null,+ /** Retries already used on the current occurrence. */+ val retriesUsed: Int = 0,+ /** When the current occurrence first found another run in progress. */+ val busySince: Long? = null,+ /** Newest last, capped at [MAX_HISTORY]. */+ val history: List<TaskRun> = emptyList()+) {+ val mode: AgentMode+ get() = runCatching { AgentMode.valueOf(agentMode) }.getOrDefault(AgentMode.MONITOR)++ val start: LocalDateTime+ get() = LocalDateTime.parse(startLocal)++ /** When this task should next fire, if it is on and has anything left to run. */+ val dueAt: Long?+ get() = if (!enabled) null else listOfNotNull(nextRunAt, retryAt).minOrNull()++ /** The most recent run, if any. */+ val lastRun: TaskRun? get() = history.lastOrNull()++ fun withRun(run: TaskRun): ScheduledTask = copy(history = (history + run).takeLast(MAX_HISTORY))++ companion object {+ const val MAX_HISTORY = 20+ const val DEFAULT_MAX_RETRIES = 1+ const val DEFAULT_RETRY_DELAY_MINUTES = 10+ const val MAX_RETRIES = 5+ const val MAX_INTERVAL = 365+ }+}++/**+ * The first time [task] is due strictly after [after], by its schedule alone+ * (retries aside), or null when there is none: a one-time task whose time has+ * passed. Pure, so the calendar rules are tested on the JVM.+ */+fun nextOccurrence(task: ScheduledTask, after: Long, zone: ZoneId): Long? {+ val start = task.start+ val startAt = start.atZone(zone).toInstant().toEpochMilli()+ 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)) {+ return startAt+ }+ }+ val interval = task.repeat.interval.coerceIn(1, ScheduledTask.MAX_INTERVAL).toLong()+ val afterLocal = LocalDateTime.ofInstant(Instant.ofEpochMilli(after), zone)+ return when (task.repeat.kind) {+ RepeatKind.NONE -> null+ RepeatKind.HOURLY -> {+ // Hours are counted in real time, so a summer-time change does not+ // stretch or skip one.+ val step = interval * HOUR_MS+ val k = if (after < startAt) 0 else (after - startAt) / step + 1+ startAt + k * step+ }+ RepeatKind.DAILY -> {+ val daysSince = ChronoUnit.DAYS.between(start.toLocalDate(), afterLocal.toLocalDate()).coerceAtLeast(0)+ var k = daysSince / interval+ var candidate: Long+ do {+ candidate = start.plusDays(k * interval).atZone(zone).toInstant().toEpochMilli()+ k+++ } while (candidate <= after)+ candidate+ }+ RepeatKind.WEEKLY -> {+ val days = weekdaysOf(task.repeat, start)+ var date = maxOf(start.toLocalDate(), afterLocal.toLocalDate())+ // Eight days always reach the next listed weekday after today's has passed.+ repeat(DAYS_TO_SCAN) {+ if (date.dayOfWeek in days) {+ val at = date.atTime(start.toLocalTime()).atZone(zone).toInstant().toEpochMilli()+ if (at > after && at >= startAt) return at+ }+ date = date.plusDays(1)+ }+ null+ }+ RepeatKind.MONTHLY -> {+ val day = start.dayOfMonth+ var month = YearMonth.from(maxOf(start.toLocalDate(), afterLocal.toLocalDate()))+ // The current month may already be past; the next one never is.+ repeat(2) {+ val date = month.atDay(minOf(day, month.lengthOfMonth()))+ val at = date.atTime(start.toLocalTime()).atZone(zone).toInstant().toEpochMilli()+ if (at > after && at >= startAt) return at+ month = month.plusMonths(1)+ }+ null+ }+ }+}++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) }++private const val HOUR_MS = 60L * 60L * 1000L+private const val DAYS_TO_SCAN = 8diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.ktnew file mode 100644index 0000000..c46f55a--- /dev/null+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskNotifier.kt@@ -0,0 +1,79 @@+package com.gotcha.scheduled++import android.app.NotificationChannel+import android.app.NotificationManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import androidx.core.app.NotificationCompat+import androidx.core.app.NotificationManagerCompat+import com.gotcha.MainActivity+import com.gotcha.R+import com.gotcha.notifications.ChatCompletionNotifier++/**+ * The "tap to run" notification of a task Android would not let run on its own+ * (issue #132). The tap opens Gotcha, which runs the task there and shows its+ * chat: with Gotcha in front, its keep-alive service may start again.+ */+class ScheduledTaskNotifier(private val context: Context) {++ @Suppress("MissingPermission") // canPost() checks it.+ fun postNeedsTap(task: ScheduledTask) {+ if (!ChatCompletionNotifier(context).canPost()) return+ ensureChannel()+ val tap = PendingIntent.getActivity(+ context,+ notificationId(task.id),+ Intent(context, MainActivity::class.java)+ .putExtra(EXTRA_RUN_TASK_ID, task.id)+ .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_needs_tap_body)+ val notification = NotificationCompat.Builder(context, CHANNEL_ID)+ .setSmallIcon(R.drawable.ic_notification)+ .setContentTitle(context.getString(R.string.scheduled_needs_tap_title, task.name))+ .setContentText(body)+ .setStyle(NotificationCompat.BigTextStyle().bigText(body))+ .setCategory(NotificationCompat.CATEGORY_REMINDER)+ .setAutoCancel(true)+ .setContentIntent(tap)+ // 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)+ }++ fun cancel(taskId: String) {+ NotificationManagerCompat.from(context).cancel(notificationId(taskId))+ }++ private fun ensureChannel() {+ val manager = context.getSystemService(NotificationManager::class.java) ?: return+ if (manager.getNotificationChannel(CHANNEL_ID) != null) return+ manager.createNotificationChannel(+ NotificationChannel(+ CHANNEL_ID,+ context.getString(R.string.channel_scheduled_tasks),+ NotificationManager.IMPORTANCE_DEFAULT+ ).apply { description = context.getString(R.string.channel_scheduled_tasks_description) }+ )+ }++ companion object {+ const val CHANNEL_ID = "gotcha_scheduled_tasks"++ /** On the tap intent: the task MainActivity should run. */+ const val EXTRA_RUN_TASK_ID = "com.gotcha.scheduled.RUN_TASK_ID"++ /** 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)+ }+}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.ktnew file mode 100644index 0000000..c9244bb--- /dev/null+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskPlanner.kt@@ -0,0 +1,149 @@+package com.gotcha.scheduled++import java.time.ZoneId++/**+ * The bookkeeping of scheduled tasks (issue #132), kept free of Android so it+ * is tested on the JVM: what a task does when its alarm fires, and how each+ * outcome moves it on to its next time.+ */+object ScheduledTaskPlanner {++ /** A task this late (the phone was off, or deep asleep) is recorded as missed rather than run. */+ const val CATCH_UP_MS = 60L * 60L * 1000L++ /** How often a task waiting for another run to end looks again. */+ const val BUSY_RECHECK_MS = 2L * 60L * 1000L++ /** How long a task waits for another run to end before it gives this occurrence up. */+ const val BUSY_GIVE_UP_MS = 60L * 60L * 1000L++ /** Early enough to count as due: alarms may be delivered a little before their time. */+ const val DUE_SLACK_MS = 30L * 1000L++ sealed class Decision {+ /** Not due yet. */+ object Wait : Decision()++ /** Due: start the run. */+ object Run : Decision()++ /** Too late to run; [task] has the miss recorded and its next time set. */+ data class Missed(val task: ScheduledTask) : Decision()+ }++ /** A new or edited [task], with its next time worked out from [now]. */+ fun armed(task: ScheduledTask, now: Long, zone: ZoneId): ScheduledTask =+ task.copy(+ nextRunAt = nextOccurrence(task, now, zone),+ retryAt = null,+ retriesUsed = 0,+ busySince = null+ )++ fun decide(task: ScheduledTask, now: Long, zone: ZoneId): Decision {+ val due = task.dueAt ?: return Decision.Wait+ if (due > now + DUE_SLACK_MS) return Decision.Wait+ // A retry or a wait for a busy runner is late by design, not missed.+ val waitingAlready = task.retryAt != null && due == task.retryAt+ if (!waitingAlready && now - due > CATCH_UP_MS) {+ return Decision.Missed(+ advance(task, now, zone).withRun(TaskRun(at = now, status = TaskRunStatus.MISSED))+ )+ }+ return Decision.Run+ }++ /**+ * Another run holds Gotcha: wait a little and look again, up to+ * [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.+ */+ fun busy(task: ScheduledTask, now: Long, zone: ZoneId): ScheduledTask {+ val since = task.busySince ?: now+ if (now - since >= BUSY_GIVE_UP_MS) {+ return task.copy(retryAt = null, retriesUsed = 0, busySince = null)+ .withRun(TaskRun(at = now, status = TaskRunStatus.SKIPPED_BUSY))+ }+ val claimed = if (scheduleIsDue(task, now)) {+ task.copy(nextRunAt = nextAfter(task, now, zone), retriesUsed = 0)+ } else {+ task+ }+ return claimed.copy(busySince = since, retryAt = now + BUSY_RECHECK_MS)+ }++ /**+ * 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].+ */+ fun started(task: ScheduledTask, sessionId: String, now: Long, zone: ZoneId): ScheduledTask {+ val newOccurrence = scheduleIsDue(task, now)+ return task.copy(+ nextRunAt = if (newOccurrence) nextAfter(task, now, zone) else task.nextRunAt,+ retryAt = null,+ retriesUsed = if (newOccurrence) 0 else task.retriesUsed,+ busySince = null,+ chatSessionId = if (task.sameChat) sessionId else task.chatSessionId+ )+ }++ /**+ * 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.+ */+ fun finished(+ task: ScheduledTask,+ status: TaskRunStatus,+ sessionId: String?,+ detail: String?,+ 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+ )+ } else {+ recorded.copy(retryAt = null, retriesUsed = 0)+ }+ }++ /** [task] could not be started at all; recorded without a retry. */+ fun notStarted(+ task: ScheduledTask,+ status: TaskRunStatus,+ detail: String?,+ now: Long,+ zone: ZoneId+ ): ScheduledTask =+ advance(task, now, zone).withRun(TaskRun(at = now, status = status, detail = detail))++ /** The earliest time any of [tasks] is due, or null when none is. */+ fun nextAlarm(tasks: List<ScheduledTask>): Long? = tasks.mapNotNull { it.dueAt }.minOrNull()++ /**+ * Gives the current occurrence up. When it was the scheduled time that fired,+ * the task moves on to its next one after [now]; when it was a retry, the+ * next scheduled time was already set as the run started, and stays.+ */+ private fun advance(task: ScheduledTask, now: Long, zone: ZoneId): ScheduledTask =+ task.copy(+ nextRunAt = if (scheduleIsDue(task, now)) nextAfter(task, now, zone) else task.nextRunAt,+ retryAt = null,+ retriesUsed = 0,+ busySince = null+ )++ /** True when [task]'s scheduled time, not just a retry, has come. */+ 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 const val MINUTE_MS = 60L * 1000L+}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.ktnew file mode 100644index 0000000..0d4174c--- /dev/null+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskRuns.kt@@ -0,0 +1,144 @@+package com.gotcha.scheduled++import android.app.Application+import android.content.BroadcastReceiver+import android.content.Context+import android.content.Intent+import android.util.Log+import com.gotcha.R+import com.gotcha.agent.ChatRunner+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.sync.Mutex+import kotlinx.coroutines.sync.withLock+import kotlinx.coroutines.withContext+import java.time.ZoneId++/** What [ChatRunner.startScheduled] made of a task. */+sealed class ScheduledStart {+ data class Started(val sessionId: String) : ScheduledStart()++ /** Another run holds the agent; nothing was started. */+ object Busy : ScheduledStart()++ data class Failed(val detail: String) : ScheduledStart()+}++/**+ * Starts the runs of scheduled tasks and writes down how they went (issue #132).+ * One lock covers both, so a run that ends at once can't have its result+ * written before the record that it started.+ */+object ScheduledTaskRuns {++ private val lock = Mutex()++ /** Starts every task that is due now, records the rest of what happened, and re-arms the alarm. */+ suspend fun fireDue(app: Application, now: Long = System.currentTimeMillis()) {+ lock.withLock {+ val store = ScheduledTaskStore(app)+ val zone = ZoneId.systemDefault()+ for (task in store.all().sortedBy { it.dueAt ?: Long.MAX_VALUE }) {+ when (val decision = ScheduledTaskPlanner.decide(task, now, zone)) {+ ScheduledTaskPlanner.Decision.Wait -> Unit+ is ScheduledTaskPlanner.Decision.Missed -> store.put(decision.task)+ // The first due task takes the runner; the ones after it find it+ // busy and wait their turn.+ ScheduledTaskPlanner.Decision.Run -> start(app, store, task, now, zone, userInitiated = false)+ }+ }+ }+ ScheduledTaskScheduler.reschedule(app)+ }++ /**+ * Runs task [id] now, for "Run now" in Settings or a tap on its "tap to run" notification.+ * The task's schedule is left as it is, unless this was its scheduled time.+ */+ suspend fun runNow(app: Application, id: String, now: Long = System.currentTimeMillis()): ScheduledStart {+ val result = lock.withLock {+ val store = ScheduledTaskStore(app)+ val task = store.get(id) ?: return@withLock ScheduledStart.Failed(app.getString(R.string.scheduled_task_gone))+ start(app, store, task, now, ZoneId.systemDefault(), userInitiated = true)+ }+ ScheduledTaskScheduler.reschedule(app)+ return result+ }++ /** The run of task [taskId] in [sessionId] ended with [status]; [detail] is its error, if any. */+ suspend fun recordOutcome(+ context: Context,+ taskId: String,+ sessionId: String,+ status: TaskRunStatus,+ detail: String?,+ now: Long = System.currentTimeMillis()+ ) {+ lock.withLock {+ ScheduledTaskStore(context).update(taskId) {+ ScheduledTaskPlanner.finished(it, status, sessionId, detail, now)+ }+ }+ ScheduledTaskScheduler.reschedule(context)+ }++ private suspend fun start(+ app: Application,+ store: ScheduledTaskStore,+ task: ScheduledTask,+ now: Long,+ zone: ZoneId,+ userInitiated: Boolean+ ): ScheduledStart {+ 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) }+ return ScheduledStart.Failed(detail)+ }+ if (!userInitiated && !ScheduledTaskScheduler.canRunUnattended(app)) {+ // 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)+ return ScheduledStart.Failed(app.getString(R.string.scheduled_task_needs_exact_alarms))+ }+ val result = withContext(Dispatchers.Main) { ChatRunner.of(app).startScheduled(task, attachments) }+ when (result) {+ 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 ->+ store.update(task.id) {+ ScheduledTaskPlanner.notStarted(it, TaskRunStatus.NOT_STARTED, result.detail, now, zone)+ }+ }+ return result+ }+}++/** The scheduled-task alarm going off. Not exported: only Gotcha's own PendingIntent fires it. */+class ScheduledTaskReceiver : BroadcastReceiver() {++ override fun onReceive(context: Context, intent: Intent) {+ val app = context.applicationContext as Application+ if (intent.action != ACTION_FIRE) return+ val pending = goAsync()+ CoroutineScope(Dispatchers.IO).launch {+ try {+ ScheduledTaskRuns.fireDue(app)+ } catch (e: Exception) {+ Log.w(TAG, "Scheduled task work failed", e)+ } finally {+ pending.finish()+ }+ }+ }++ companion object {+ private const val TAG = "ScheduledTasks"+ const val ACTION_FIRE = "com.gotcha.scheduled.FIRE"+ }+}diff --git a/app/src/main/java/com/gotcha/scheduled/ScheduledTaskScheduler.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskScheduler.ktnew file mode 100644index 0000000..ddc3a41--- /dev/null+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskScheduler.kt@@ -0,0 +1,63 @@+package com.gotcha.scheduled++import android.app.AlarmManager+import android.app.PendingIntent+import android.content.Context+import android.content.Intent+import android.os.Build+import android.util.Log++/**+ * Keeps one alarm armed for the scheduled task due soonest (issue #132), and+ * re-arms it after every change, every firing, and after a reboot, an app+ * update or a clock change (through `NotificationRescheduleReceiver`).+ *+ * The alarm is exact when Android allows it. That also matters for the run+ * itself: an exact alarm is what lets Gotcha start its keep-alive service from+ * the background on Android 12 and later. Without the permission, the alarm+ * goes off within a window instead, and the task asks for a tap+ * ([TaskRunStatus.NEEDS_TAP]) rather than starting a run Android would freeze.+ */+object ScheduledTaskScheduler {++ private const val TAG = "ScheduledTasks"++ /** How late Android may deliver the alarm when exact alarms are not allowed. */+ private const val WINDOW_MS = 10L * 60L * 1000L++ /** 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+ val pending = fireIntent(context)+ val at = ScheduledTaskPlanner.nextAlarm(ScheduledTaskStore(context).all())+ if (at == null) {+ alarm.cancel(pending)+ return+ }+ try {+ if (canRunUnattended(context)) {+ alarm.setExactAndAllowWhileIdle(AlarmManager.RTC_WAKEUP, at, pending)+ } else {+ alarm.setWindow(AlarmManager.RTC_WAKEUP, at, WINDOW_MS, pending)+ }+ } catch (e: SecurityException) {+ // The exact-alarm grant was withdrawn between the check and the call.+ Log.w(TAG, "Exact alarm refused; using a window", e)+ alarm.setWindow(AlarmManager.RTC_WAKEUP, at, WINDOW_MS, pending)+ }+ }++ /** 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 true+ return context.getSystemService(AlarmManager::class.java)?.canScheduleExactAlarms() == true+ }++ private fun fireIntent(context: Context): PendingIntent =+ PendingIntent.getBroadcast(+ context,+ 0,+ 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/scheduled/ScheduledTaskStore.kt b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.ktnew file mode 100644index 0000000..61cc52b--- /dev/null+++ b/app/src/main/java/com/gotcha/scheduled/ScheduledTaskStore.kt@@ -0,0 +1,115 @@+package com.gotcha.scheduled++import android.content.Context+import android.content.SharedPreferences+import com.gotcha.agent.ComposerAttachment+import com.gotcha.data.SafeEncryptedSharedPreferences+import kotlinx.serialization.builtins.ListSerializer+import kotlinx.serialization.json.Json+import java.io.File++/**+ * The scheduled tasks (issue #132). The tasks are kept in encrypted prefs, like+ * settings, because their prompts are personal. Their files are kept next to+ * the chats, one JSON file per task under [attachmentsDir]: images there are+ * already downscaled to JPEG and documents already turned into text, so a task+ * still has its files when the picker's permission to read them is long gone.+ *+ * Every change goes through [update], which holds one lock across the read and+ * the write, so the alarm receiver and the Settings page can't overwrite each+ * other's changes.+ */+class ScheduledTaskStore internal constructor(+ private val prefs: SharedPreferences,+ private val attachmentsDir: File+) {++ constructor(context: Context) : this(+ SafeEncryptedSharedPreferences.create(context, PREFS_FILE),+ File(context.filesDir, ATTACHMENTS_DIR)+ )++ private val json = Json { ignoreUnknownKeys = true }+ private val tasksSerializer = ListSerializer(ScheduledTask.serializer())+ private val attachmentsSerializer = ListSerializer(ComposerAttachment.serializer())++ /** Oldest first. */+ fun all(): List<ScheduledTask> = synchronized(LOCK) { read() }++ fun get(id: String): ScheduledTask? = all().firstOrNull { it.id == id }++ /**+ * Replaces the task [id] with what [transform] makes of it (null deletes it)+ * and returns the result. Returns null, changing nothing, when there is no such task.+ */+ fun update(id: String, transform: (ScheduledTask) -> ScheduledTask?): ScheduledTask? = synchronized(LOCK) {+ val tasks = read()+ val current = tasks.firstOrNull { it.id == id } ?: return null+ val changed = transform(current)+ write(if (changed == null) tasks.filterNot { it.id == id } else tasks.map { if (it.id == id) changed else it })+ if (changed == null) attachmentsFile(id).delete()+ changed+ }++ /** Adds [task], or replaces the one with its id. */+ fun put(task: ScheduledTask) = synchronized(LOCK) {+ val tasks = read()+ write(if (tasks.any { it.id == task.id }) tasks.map { if (it.id == task.id) task else it } else tasks + task)+ }++ fun delete(id: String) {+ update(id) { null }+ }++ /** 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()+ if (tasks.none { it.chatSessionId == sessionId }) return+ write(tasks.map { if (it.chatSessionId == sessionId) it.copy(chatSessionId = null) else it })+ }++ // ---- files ----++ fun saveAttachments(id: String, attachments: List<ComposerAttachment>) {+ val file = attachmentsFile(id)+ if (attachments.isEmpty()) {+ file.delete()+ return+ }+ attachmentsDir.mkdirs()+ file.writeText(json.encodeToString(attachmentsSerializer, attachments))+ }++ /**+ * The files stored with task [id]: empty when it has none, null when it+ * should have some but they can't be read any more.+ */+ fun loadAttachments(task: ScheduledTask): List<ComposerAttachment>? {+ if (task.attachmentNames.isEmpty()) return emptyList()+ val file = attachmentsFile(task.id)+ if (!file.isFile) return null+ return runCatching { json.decodeFromString(attachmentsSerializer, file.readText()) }.getOrNull()+ }++ private fun attachmentsFile(id: String) = File(+ attachmentsDir,+ "${id.filter { it.isLetterOrDigit() || it == '-' }}.json"+ )++ private fun read(): List<ScheduledTask> =+ prefs.getString(KEY_TASKS, null)+ ?.let { runCatching { json.decodeFromString(tasksSerializer, it) }.getOrNull() }+ .orEmpty()++ private fun write(tasks: List<ScheduledTask>) {+ // commit, not apply: the alarm receiver writes here just before its process may go.+ prefs.edit().putString(KEY_TASKS, json.encodeToString(tasksSerializer, tasks)).commit()+ }++ private companion object {+ const val PREFS_FILE = "gotcha_scheduled_tasks"+ const val KEY_TASKS = "tasks"+ const val ATTACHMENTS_DIR = "scheduled_tasks"+ val LOCK = Any()+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.ktnew file mode 100644index 0000000..42686a2--- /dev/null+++ b/app/src/main/java/com/gotcha/tools/ScheduledTaskTool.kt@@ -0,0 +1,427 @@+package com.gotcha.tools++import android.content.Context+import com.gotcha.agent.AttachmentFiles+import com.gotcha.agent.ComposerAttachment+import com.gotcha.scheduled.Repeat+import com.gotcha.scheduled.RepeatKind+import com.gotcha.scheduled.ScheduledTask+import com.gotcha.scheduled.ScheduledTaskPlanner+import com.gotcha.scheduled.ScheduledTaskScheduler+import com.gotcha.scheduled.ScheduledTaskStore+import kotlinx.serialization.Serializable+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonArray+import kotlinx.serialization.json.JsonObject+import kotlinx.serialization.json.JsonPrimitive+import kotlinx.serialization.json.booleanOrNull+import kotlinx.serialization.json.intOrNull+import java.io.File+import java.time.DayOfWeek+import java.time.Instant+import java.time.LocalDateTime+import java.time.ZoneId+import java.time.format.DateTimeFormatter+import java.time.format.DateTimeParseException+import java.time.format.TextStyle+import java.util.Base64+import java.util.Locale+import java.util.UUID++/**+ * A create or an edit of a scheduled task the agent asked for (issue #132),+ * carried in a [ScheduledTaskTool.CONFIRM_PREFIX] result until the user answers.+ * Null fields of an edit are left as they are. [files] are canonical paths,+ * checked when the call was made and read only once the user approves.+ */+@Serializable+data class ScheduleRequest(+ val taskId: String? = null,+ val name: String? = null,+ val prompt: String? = null,+ val startLocal: String? = null,+ val repeat: Repeat? = null,+ val sameChat: Boolean? = null,+ val mode: String? = null,+ val files: List<String>? = null,+ val enabled: Boolean? = null+) {+ val isCreate: Boolean get() = taskId == null+}++/**+ * The agent's side of scheduled tasks (issue #132): schedule_agent_task,+ * edit_scheduled_task, list_scheduled_tasks and delete_scheduled_task.+ *+ * A task runs the agent later with nobody watching, so nothing here saves a+ * task by itself. A create or an edit is checked and returned as a+ * [CONFIRM_PREFIX] marker; `AgentEngine` shows the user exactly what would be+ * scheduled and only then calls [apply], with the chat's own mode as the+ * ceiling for the task's. A delete goes through the engine's delete+ * confirmation. None of the four is offered to Monitor (bar the list), to a+ * sub-agent, or to a run a schedule started.+ */+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 fileResolver by lazy { FileResolver(context) }++ fun prepareCreate(args: JsonObject): ToolResult {+ val name = args.string("name")?.trim()?.take(MAX_NAME) ?: return missing("name")+ val prompt = args.string("prompt")?.trim()?.take(MAX_PROMPT) ?: return missing("prompt")+ if (name.isEmpty()) return missing("name")+ if (prompt.isEmpty()) return missing("prompt")+ val startText = args.string("start") ?: return missing("start")+ val start = parseStart(startText) ?: return ToolResult.error(+ "Invalid 'start' \"$startText\": use the phone's local time as YYYY-MM-DDTHH:MM, e.g. 2026-10-19T08:00."+ )+ val repeat = parseRepeat(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ if (repeat.kind == RepeatKind.NONE && start.atZone(zone()).toInstant().toEpochMilli() <= clock()) {+ return ToolResult.error("That time has already passed. Pick a time in the future, or a repeat rule.")+ }+ if (store.all().count { it.createdByAgent } >= MAX_AGENT_TASKS) {+ return ToolResult.error(+ "You already set up $MAX_AGENT_TASKS scheduled tasks, the most allowed. Ask the user to delete " ++ "one first (list_scheduled_tasks shows them), or to add this one in Settings."+ )+ }+ val mode = parseMode(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ val files = checkFiles(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ return confirm(+ ScheduleRequest(+ name = name,+ prompt = prompt,+ startLocal = start.toString(),+ repeat = repeat,+ sameChat = args.boolean("same_chat") ?: false,+ mode = mode?.name,+ files = files+ )+ )+ }++ fun prepareEdit(args: JsonObject): ToolResult {+ val id = args.string("task_id") ?: return missing("task_id")+ val existing = store.get(id) ?: return unknownTask(id)+ val start = args.string("start")?.let { text ->+ parseStart(text) ?: return ToolResult.error(+ "Invalid 'start' \"$text\": use the phone's local time as YYYY-MM-DDTHH:MM."+ )+ }+ val repeat = if (args.containsKey("repeat") || args.containsKey("interval") || args.containsKey("weekdays")) {+ parseRepeat(args, existing.repeat).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ } else {+ null+ }+ val mode = parseMode(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ val files = checkFiles(args).getOrElse { return ToolResult.error(it.message.orEmpty()) }+ val request = ScheduleRequest(+ taskId = existing.id,+ name = args.string("name")?.trim()?.take(MAX_NAME)?.ifEmpty { null },+ prompt = args.string("prompt")?.trim()?.take(MAX_PROMPT)?.ifEmpty { null },+ startLocal = start?.toString(),+ repeat = repeat,+ sameChat = args.boolean("same_chat"),+ mode = mode?.name,+ files = files,+ enabled = args.boolean("enabled")+ )+ if (request == ScheduleRequest(taskId = existing.id)) {+ return ToolResult.error("Nothing to change: pass at least one field to edit.")+ }+ return confirm(request)+ }++ fun list(): ToolResult {+ val tasks = store.all()+ if (tasks.isEmpty()) return ToolResult.ok("No scheduled tasks.")+ return ToolResult.ok(+ tasks.joinToString("\n") { task ->+ buildString {+ append("- ${task.id}: \"${task.name}\"")+ append(if (task.enabled) "" else " (paused)")+ append(" — ${describeSchedule(task.start, task.repeat)}")+ append("; next: ${task.dueAt?.let(::formatInstant) ?: "none"}")+ append("; ${task.mode.name.lowercase()} mode")+ append(if (task.sameChat) "; same chat" else "; new chat each time")+ if (task.attachmentNames.isNotEmpty()) append("; files: ${task.attachmentNames.joinToString()}")+ append(if (task.createdByAgent) "; set up by you" else "; set up by the user")+ task.lastRun?.let { append("; last run: ${it.status.name.lowercase()} at ${formatInstant(it.at)}") }+ append("\n prompt: ${task.prompt.take(LIST_PROMPT_CHARS)}")+ }+ }+ )+ }++ fun prepareDelete(args: JsonObject): ToolResult {+ val id = args.string("task_id") ?: return missing("task_id")+ val task = store.get(id) ?: return unknownTask(id)+ return ToolResult.ok("$DELETE_CONFIRM_PREFIX${task.id}:${task.name}")+ }++ /** Deletes task [id]; only called once the user has confirmed. */+ fun doDelete(id: String): ToolResult {+ val task = store.get(id) ?: return unknownTask(id)+ store.delete(id)+ ScheduledTaskScheduler.reschedule(context)+ return ToolResult.ok("Deleted the scheduled task \"${task.name}\".")+ }++ /**+ * 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.+ */+ fun describe(request: ScheduleRequest, 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+ 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}\"")+ append(". It will run on its own, without asking you first.\n")+ 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")+ 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}")+ }+ }++ /**+ * Saves [request] once the user approved it. [sessionId] is the chat it was+ * asked from (a same-chat task runs there), [chatMode] the ceiling for the+ * task's mode.+ */+ fun apply(request: ScheduleRequest, sessionId: String?, chatMode: AgentMode): ToolResult {+ 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()) }+ }+ 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 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+ if (attachments != null) store.saveAttachments(saved.id, attachments)+ store.put(saved)+ ScheduledTaskScheduler.reschedule(context)+ val next = saved.dueAt?.let(::formatInstant) ?: "none"+ return ToolResult.ok(+ (if (existing == null) "Scheduled" else "Updated") ++ " \"${saved.name}\" (task_id ${saved.id}), ${saved.mode.name.lowercase()} mode. Next run: $next. " ++ "The user can pause or delete it in Settings ▸ Scheduled tasks."+ )+ }++ // ---- parsing ----++ private fun confirm(request: ScheduleRequest): ToolResult =+ ToolResult.ok(CONFIRM_PREFIX + encodePayload(request))++ private fun parseMode(args: JsonObject): Result<AgentMode?> {+ val text = args.string("mode") ?: return Result.success(null)+ return AgentMode.entries.firstOrNull { it.name.equals(text.trim(), ignoreCase = true) }+ ?.let { Result.success(it) }+ ?: Result.failure(IllegalArgumentException("Invalid 'mode' \"$text\": use monitor or operator."))+ }++ private fun parseRepeat(args: JsonObject, current: Repeat = Repeat()): Result<Repeat> {+ val kindText = args.string("repeat")+ val kind = if (kindText == null) {+ current.kind+ } else {+ RepeatKind.entries.firstOrNull { it.name.equals(kindText.trim(), ignoreCase = true) }+ ?: return Result.failure(+ IllegalArgumentException(+ "Invalid 'repeat' \"$kindText\": use none, hourly, daily, weekly or monthly."+ )+ )+ }+ val interval = (args["interval"] as? JsonPrimitive)?.let { it.intOrNull ?: it.content.trim().toIntOrNull() }+ ?: if (kind == current.kind) current.interval else 1+ if (interval !in 1..ScheduledTask.MAX_INTERVAL) {+ return Result.failure(+ IllegalArgumentException("Invalid 'interval' $interval: use 1 to ${ScheduledTask.MAX_INTERVAL}.")+ )+ }+ val weekdays = (args["weekdays"] as? JsonArray)?.map { element ->+ val text = (element as? JsonPrimitive)?.content?.trim().orEmpty()+ parseWeekday(text) ?: return Result.failure(+ IllegalArgumentException("Invalid weekday \"$text\": use mon, tue, wed, thu, fri, sat or sun.")+ )+ }?.distinct()?.sorted() ?: if (kind == current.kind) current.weekdays else emptyList()+ return Result.success(+ Repeat(+ kind = kind,+ interval = if (kind == RepeatKind.HOURLY || kind == RepeatKind.DAILY) interval else 1,+ weekdays = if (kind == RepeatKind.WEEKLY) weekdays else emptyList()+ )+ )+ }++ /** The `files` argument, each checked to be a readable file and made canonical. */+ private fun checkFiles(args: JsonObject): Result<List<String>?> {+ val paths = (args["files"] as? JsonArray)?.mapNotNull { (it as? JsonPrimitive)?.content?.trim() }+ ?.filter { it.isNotEmpty() }+ ?: return Result.success(null)+ if (paths.size > ComposerAttachment.MAX_PER_MESSAGE) {+ return Result.failure(+ IllegalArgumentException("At most ${ComposerAttachment.MAX_PER_MESSAGE} files can go with a task.")+ )+ }+ return Result.success(+ paths.map { path ->+ val file = when (val resolved = fileResolver.resolveForRead(path)) {+ is FileResolver.ResolveResult.Ok -> resolved.file+ is FileResolver.ResolveResult.PermissionNeeded ->+ return Result.failure(IllegalArgumentException(resolved.result.message))+ is FileResolver.ResolveResult.Error -> return Result.failure(+ IllegalArgumentException(resolved.message)+ )+ }+ if (!file.isFile || !file.canRead()) {+ return Result.failure(IllegalArgumentException("No readable file at '$path'."))+ }+ if (file.length() > MAX_FILE_BYTES) {+ return Result.failure(+ IllegalArgumentException("'$path' is too large to go with a task (over 20 MB).")+ )+ }+ file.canonicalPath+ }+ )+ }++ private fun loadFiles(paths: List<String>): Result<List<ComposerAttachment>> = runCatching {+ val loaded = paths.map { path ->+ val file = File(path)+ val bytes = file.readBytes()+ requireNotNull(AttachmentFiles.fromBytes(bytes, file.name, AttachmentFiles.mimeTypeFor(file.name))) {+ "Could not read '${file.name}' as an image."+ }+ }+ require(AttachmentFiles.documentChars(loaded) <= ComposerAttachment.MAX_TOTAL_DOCUMENT_CHARS) {+ "Those documents hold too much text to go with one task. Use fewer."+ }+ loaded+ }++ private fun resolveMode(request: ScheduleRequest, existing: ScheduledTask?, chatMode: AgentMode): AgentMode {+ val asked = request.mode?.let { runCatching { AgentMode.valueOf(it) }.getOrNull() }+ ?: existing?.mode+ ?: chatMode+ // Never stronger than the chat the request came from.+ return if (asked.ordinal > chatMode.ordinal) chatMode else asked+ }++ private fun unknownTask(id: String) =+ ToolResult.error("No scheduled task with task_id '$id'. Call list_scheduled_tasks for the ids.")++ private fun missing(param: String) = ToolResult.error("Missing or invalid required parameter '$param'.")++ private fun formatInstant(at: Long): String =+ LocalDateTime.ofInstant(Instant.ofEpochMilli(at), zone()).format(DISPLAY_FORMAT)++ private fun JsonObject.string(key: String): String? =+ (this[key] as? JsonPrimitive)?.takeIf { it.isString || it.content.isNotEmpty() }?.content++ private fun JsonObject.boolean(key: String): Boolean? =+ (this[key] as? JsonPrimitive)?.let { it.booleanOrNull ?: it.content.trim().toBooleanStrictOrNull() }++ companion object {+ const val CONFIRM_PREFIX = "CONFIRM_SCHEDULE_TASK:"+ const val DELETE_CONFIRM_PREFIX = "CONFIRM_DELETE_SCHEDULED_TASK:"++ val TOOL_NAMES = setOf(+ "schedule_agent_task",+ "edit_scheduled_task",+ "list_scheduled_tasks",+ "delete_scheduled_task"+ )++ /** The most tasks the agent may have set up at once. The user's own, from Settings, don't count. */+ const val MAX_AGENT_TASKS = 10++ private const val MAX_NAME = 80+ private const val MAX_PROMPT = 4000+ private const val LIST_PROMPT_CHARS = 200+ private const val MAX_FILE_BYTES = 20L * 1024L * 1024L++ private val DISPLAY_FORMAT = DateTimeFormatter.ofPattern("EEE d MMM yyyy, HH:mm", Locale.ENGLISH)+ private val json = Json { ignoreUnknownKeys = true }++ fun encodePayload(request: ScheduleRequest): String =+ Base64.getEncoder().encodeToString(json.encodeToString(ScheduleRequest.serializer(), request).toByteArray())++ fun decodePayload(payload: String): ScheduleRequest? = runCatching {+ json.decodeFromString(ScheduleRequest.serializer(), String(Base64.getDecoder().decode(payload)))+ }.getOrNull()++ /** Local date-time as the model writes it: "2026-10-19T08:00", with a space or seconds also taken. */+ internal fun parseStart(text: String): LocalDateTime? = try {+ LocalDateTime.parse(text.trim().replace(' ', 'T')).withSecond(0).withNano(0)+ } catch (_: DateTimeParseException) {+ null+ }++ internal fun parseWeekday(text: String): Int? {+ text.toIntOrNull()?.let { return it.takeIf { n -> n in 1..7 } }+ val lower = text.lowercase()+ if (lower.length < 2) return null+ return DayOfWeek.entries.firstOrNull { it.name.lowercase().startsWith(lower) }?.value+ }++ /** The schedule in English, for the model and the approval prompt. */+ internal fun describeSchedule(start: LocalDateTime, repeat: Repeat): String {+ val first = start.format(DISPLAY_FORMAT)+ val time = start.toLocalTime().toString()+ return when (repeat.kind) {+ RepeatKind.NONE -> "once, on $first"+ RepeatKind.HOURLY ->+ if (repeat.interval == 1) "every hour from $first" else "every ${repeat.interval} hours from $first"+ RepeatKind.DAILY ->+ if (repeat.interval == 1) "every day at $time, from $first" else "every ${repeat.interval} days at $time, from $first"+ RepeatKind.WEEKLY -> {+ val days = repeat.weekdays.ifEmpty { listOf(start.dayOfWeek.value) }+ .joinToString { DayOfWeek.of(it).getDisplayName(TextStyle.FULL, Locale.ENGLISH) }+ "every week on $days at $time, from $first"+ }+ RepeatKind.MONTHLY -> "every month on day ${start.dayOfMonth} at $time, from $first"+ }+ }+ }+}diff --git a/app/src/main/java/com/gotcha/tools/ToolCategories.kt b/app/src/main/java/com/gotcha/tools/ToolCategories.ktindex 1d66faa..537b187 100644--- a/app/src/main/java/com/gotcha/tools/ToolCategories.kt+++ b/app/src/main/java/com/gotcha/tools/ToolCategories.kt@@ -28,6 +28,7 @@ object ToolCategories {"call_number", "send_sms", "add_contact","create_calendar_event", "edit_calendar_event","set_alarm", "set_timer", "snooze_alarm", "dismiss_timer",+ "schedule_agent_task", "edit_scheduled_task", "delete_scheduled_task","take_photo","start_audio_recording", "stop_audio_recording","pause_audio_recording", "resume_audio_recording",diff --git a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt b/app/src/main/java/com/gotcha/tools/ToolDefinitions.ktindex a4a723a..92ceb9c 100644--- a/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt+++ b/app/src/main/java/com/gotcha/tools/ToolDefinitions.kt@@ -3005,6 +3005,129 @@ object ToolDefinitions {})+ // ---- Scheduled tasks (issue #132) ----++ /** The fields schedule_agent_task and edit_scheduled_task share. */+ private fun kotlinx.serialization.json.JsonObjectBuilder.scheduledTaskFields() {+ putJsonObject("name") {+ put("type", "string")+ put("description", "Short name the user will recognise, e.g. 'Morning news'.")+ }+ putJsonObject("prompt") {+ put("type", "string")+ put(+ "description",+ "The instruction sent as the user's message each time the task fires. It runs with no " ++ "one watching and none of this conversation unless same_chat is true, so make it " ++ "self-contained: say what to do and how to report back."+ )+ }+ putJsonObject("start") {+ put("type", "string")+ put(+ "description",+ "First run, in the phone's local time: YYYY-MM-DDTHH:MM, e.g. 2026-10-19T08:00. Its time of " ++ "day (and weekday, day of month) anchors the repeat."+ )+ }+ putJsonObject("repeat") {+ put("type", "string")+ putJsonArray("enum") { listOf("none", "hourly", "daily", "weekly", "monthly").forEach { add(it) } }+ put("description", "How it comes round again. Default none (once).")+ }+ putJsonObject("interval") {+ put("type", "integer")+ put("description", "For hourly or daily: every N hours or days. Default 1.")+ }+ putJsonObject("weekdays") {+ put("type", "array")+ putJsonObject("items") { put("type", "string") }+ put("description", "For weekly: days to run, e.g. [\"mon\",\"wed\",\"fri\"]. Default the start's weekday.")+ }+ putJsonObject("same_chat") {+ put("type", "boolean")+ put(+ "description",+ "True to add each run to this chat (it keeps the conversation); false (default) to start a " ++ "new chat each time."+ )+ }+ putJsonObject("mode") {+ put("type", "string")+ putJsonArray("enum") {+ add("monitor")+ add("operator")+ }+ put(+ "description",+ "Mode the runs use; never more than this chat's. Default this chat's mode. Prefer monitor " ++ "when the task only reads or reports."+ )+ }+ putJsonObject("files") {+ put("type", "array")+ putJsonObject("items") { put("type", "string") }+ put("description", "Paths of files sent with the prompt each time (read once, when saved). At most 10.")+ }+ }++ val scheduleAgentTask = tool(+ "schedule_agent_task",+ "Schedule a prompt for Gotcha to run by itself later, once or on repeat, e.g. 'every weekday " ++ "at 8, summarise my unread mail'. Each run is a normal agent run whose result lands in a chat " ++ "and a notification. The user approves the exact task before it is saved; if they decline, " ++ "don't retry unless asked. For a plain reminder or alarm use set_alarm or the calendar instead.",+ schema {+ putJsonObject("properties") { scheduledTaskFields() }+ putJsonArray("required") {+ add("name")+ add("prompt")+ add("start")+ }+ }+ )++ val editScheduledTask = tool(+ "edit_scheduled_task",+ "Change, pause or resume a scheduled task. Pass task_id (from list_scheduled_tasks) and only " ++ "the fields to change. The user approves the change.",+ schema {+ putJsonObject("properties") {+ putJsonObject("task_id") {+ put("type", "string")+ put("description", "The task's id, from list_scheduled_tasks.")+ }+ scheduledTaskFields()+ putJsonObject("enabled") {+ put("type", "boolean")+ put("description", "False to pause the task, true to resume it.")+ }+ }+ putJsonArray("required") { add("task_id") }+ }+ )++ val listScheduledTasks = tool(+ "list_scheduled_tasks",+ "List the scheduled tasks with their ids, schedules, next and last runs, and prompts.",+ schema { putJsonObject("properties") {} }+ )++ val deleteScheduledTask = tool(+ "delete_scheduled_task",+ "Delete a scheduled task for good. The user confirms first. To stop it for a while, pause it " ++ "with edit_scheduled_task instead.",+ schema {+ putJsonObject("properties") {+ putJsonObject("task_id") {+ put("type", "string")+ put("description", "The task's id, from list_scheduled_tasks.")+ }+ }+ putJsonArray("required") { add("task_id") }+ }+ )+val all: List<ToolDefinition> = listOf(aboutSamosaAi,aboutGotcha,@@ -3018,6 +3141,7 @@ object ToolDefinitions {listCalendarEvents, createCalendarEvent, editCalendarEvent, deleteCalendarEvent,checkAvailability,setAlarm, setTimer, listAlarms, listTimers, editAlarm, deleteAlarm, deleteTimer,+ scheduleAgentTask, editScheduledTask, listScheduledTasks, deleteScheduledTask,toggleTorch, setVolume, getVolume, setRingerMode, vibrate, setDnd,getLocation, listInstalledApps, uninstallApp, getAppUsage, getDataUsage,getClipboard, setClipboard, takePhoto, startAudioRecording, stopAudioRecording,diff --git a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt b/app/src/main/java/com/gotcha/tools/ToolExecutor.ktindex 42d36bf..35d413a 100644--- a/app/src/main/java/com/gotcha/tools/ToolExecutor.kt+++ b/app/src/main/java/com/gotcha/tools/ToolExecutor.kt@@ -62,6 +62,13 @@ class ToolExecutor(private val smsTool = SmsTool(appContext)private val calendarTool = CalendarTool(appContext)private val alarmTool = AlarmTool(appContext)++ /**+ * The scheduled-task tools (issue #132). The engine reaches it directly to+ * describe and save a request the user approved. Lazy: its store opens+ * encrypted prefs, which only the schedule tools need.+ */+ val scheduledTaskTool by lazy { ScheduledTaskTool(appContext) }private val deviceTool = DeviceTool(appContext)private val locationTool = LocationTool(appContext)private val appsTool = AppsTool(appContext)@@ -413,6 +420,10 @@ class ToolExecutor(minutes = args.requireInt("minutes"),system = args["system"]?.jsonPrimitive?.booleanOrNull ?: false)+ "schedule_agent_task" -> scheduledTaskTool.prepareCreate(args)+ "edit_scheduled_task" -> scheduledTaskTool.prepareEdit(args)+ "list_scheduled_tasks" -> scheduledTaskTool.list()+ "delete_scheduled_task" -> scheduledTaskTool.prepareDelete(args)"list_alarms" -> alarmTool.listAlarms()"list_timers" -> alarmTool.listTimers()"show_alarms" -> alarmTool.showAlarms()diff --git a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt b/app/src/main/java/com/gotcha/tools/ToolRegistry.ktindex 1d2bd06..cfa278c 100644--- a/app/src/main/java/com/gotcha/tools/ToolRegistry.kt+++ b/app/src/main/java/com/gotcha/tools/ToolRegistry.kt@@ -102,7 +102,8 @@ object ToolRegistry {"uninstall_app","delete_calendar_event","delete_alarm",- "delete_timer"+ "delete_timer",+ "delete_scheduled_task")/**@@ -119,7 +120,7 @@ object ToolRegistry {"get_app_usage", "get_data_usage","open_app", "list_installed_apps","list_files", "read_file", "grep", "glob",- "todowrite", "list_alarms", "list_timers", "show_alarms",+ "todowrite", "list_alarms", "list_timers", "show_alarms", "list_scheduled_tasks","question","sleep","finish_task",@@ -141,19 +142,30 @@ object ToolRegistry {val monitorTools: Set<String>get() = baseMonitorTools + ConnectorCatalog.monitorTools + dynamicSet.readOnlyNames+ /** Tools a sub-agent never gets; see [subAgentTools]. */+ private val subAgentExcluded = setOf(+ "task",+ "navigate_app",+ "finish_task",+ "update_user_profile",+ "update_gotcha_settings",+ "schedule_agent_task",+ "edit_scheduled_task",+ "delete_scheduled_task"+ )+/*** Full Operator tool set minus task + navigate_app (sub-agents cannot delegate* further), minus finish_task, which ends the *top-level* run — a sub-agent* reports back with ask_final_answer instead — minus update_user_profile,* whose modify-and-extend directive lives only in the top-level Operator prompt,- * and minus update_gotcha_settings, whose approval prompt belongs to the run the- * user is watching, not to a delegated one.+ * and minus update_gotcha_settings and the scheduled-task writes, whose approval+ * prompts belong to the run the user is watching, not to a delegated one.* Dynamic tools are included while registered; they are hidden by the* hidden-tools mechanism when their connector is not active.*/val subAgentTools: Set<String>- get() = definitions.keys + dynamicSet.definitions.keys -- setOf("task", "navigate_app", "finish_task", "update_user_profile", "update_gotcha_settings")+ get() = definitions.keys + dynamicSet.definitions.keys - subAgentExcluded/** Tools available to the App Navigator sub-agent. */val navigatorTools: Set<String> = setOf(@@ -497,8 +509,7 @@ object ToolRegistry {fun toolsForSubAgent(hiddenTools: Set<String> = emptySet()): List<ToolDefinition> {val dynamic = dynamicSet- val allowed = definitions.keys + dynamic.definitions.keys -- setOf("task", "navigate_app", "finish_task", "update_user_profile", "update_gotcha_settings")+ val allowed = definitions.keys + dynamic.definitions.keys - subAgentExcludedreturn (definitions + dynamic.definitions).filterKeys { it in allowed && it !in hiddenTools }.values.toList()diff --git a/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.ktnew file mode 100644index 0000000..a28407a--- /dev/null+++ b/app/src/main/java/com/gotcha/ui/ScheduledTasksScreen.kt@@ -0,0 +1,725 @@+package com.gotcha.ui++import android.app.Application+import android.app.DatePickerDialog+import android.app.TimePickerDialog+import android.content.Context+import android.content.Intent+import android.net.Uri+import android.os.Build+import android.provider.OpenableColumns+import android.text.format.DateFormat+import androidx.activity.compose.rememberLauncherForActivityResult+import androidx.activity.result.contract.ActivityResultContracts+import androidx.compose.foundation.layout.Arrangement+import androidx.compose.foundation.layout.Column+import androidx.compose.foundation.layout.ExperimentalLayoutApi+import androidx.compose.foundation.layout.FlowRow+import androidx.compose.foundation.layout.Row+import androidx.compose.foundation.layout.fillMaxWidth+import androidx.compose.foundation.layout.size+import androidx.compose.foundation.text.KeyboardOptions+import androidx.compose.material.icons.Icons+import androidx.compose.material.icons.filled.Check+import androidx.compose.material3.Button+import androidx.compose.material3.FilterChip+import androidx.compose.material3.FilterChipDefaults+import androidx.compose.material3.HorizontalDivider+import androidx.compose.material3.Icon+import androidx.compose.material3.MaterialTheme+import androidx.compose.material3.OutlinedButton+import androidx.compose.material3.OutlinedTextField+import androidx.compose.material3.Switch+import androidx.compose.material3.Text+import androidx.compose.material3.TextButton+import androidx.compose.runtime.Composable+import androidx.compose.runtime.DisposableEffect+import androidx.compose.runtime.LaunchedEffect+import androidx.compose.runtime.getValue+import androidx.compose.runtime.mutableStateOf+import androidx.compose.runtime.remember+import androidx.compose.runtime.rememberCoroutineScope+import androidx.compose.runtime.setValue+import androidx.compose.ui.Alignment+import androidx.compose.ui.Modifier+import androidx.compose.ui.platform.LocalContext+import androidx.compose.ui.platform.LocalLifecycleOwner+import androidx.compose.ui.platform.testTag+import androidx.compose.ui.res.pluralStringResource+import androidx.compose.ui.res.stringResource+import androidx.compose.ui.text.font.FontWeight+import androidx.compose.ui.text.input.KeyboardType+import androidx.compose.ui.unit.dp+import androidx.lifecycle.Lifecycle+import androidx.lifecycle.LifecycleEventObserver+import com.gotcha.R+import com.gotcha.agent.AttachmentFiles+import com.gotcha.agent.ChatTitle+import com.gotcha.agent.ComposerAttachment+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.i18n.stringLookup+import com.gotcha.scheduled.Repeat+import com.gotcha.scheduled.RepeatKind+import com.gotcha.scheduled.ScheduledStart+import com.gotcha.scheduled.ScheduledTask+import com.gotcha.scheduled.ScheduledTaskPlanner+import com.gotcha.scheduled.ScheduledTaskRuns+import com.gotcha.scheduled.ScheduledTaskScheduler+import com.gotcha.scheduled.ScheduledTaskStore+import com.gotcha.scheduled.TaskRun+import com.gotcha.scheduled.TaskRunStatus+import com.gotcha.tools.AgentMode+import com.gotcha.ui.theme.SkinAlertDialog+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.launch+import kotlinx.coroutines.withContext+import java.time.DayOfWeek+import java.time.Instant+import java.time.LocalDate+import java.time.LocalDateTime+import java.time.LocalTime+import java.time.ZoneId+import java.time.format.DateTimeFormatter+import java.time.format.FormatStyle+import java.time.format.TextStyle+import java.util.Locale+import java.util.UUID++/** [editing] value for the add form, as opposed to a task id. */+private const val NEW_TASK = "+new"++/**+ * Settings ▸ Scheduled tasks (issue #132): prompts Gotcha sends itself at set+ * times, each run landing in a chat like any other. One row per task with its+ * switch, schedule, next and last run, and its history, failures included;+ * the add/edit form is inline, like the connector cards'.+ */+@Composable+fun ScheduledTasksScreen(onBack: () -> Unit, onOpenChat: (String) -> Unit) {+ val context = LocalContext.current+ val store = remember { ScheduledTaskStore(context) }+ val scope = rememberCoroutineScope()+ val overlay = rememberSettingsOverlayState()+ // Bumped after every change, and on resume (the run may have ended, or the+ // exact-alarm grant changed), so the list is read again.+ var tick by remember { mutableStateOf(0) }+ var editing by remember { mutableStateOf<String?>(null) }+ var deleting by remember { mutableStateOf<ScheduledTask?>(null) }+ val tasks = remember(tick) { store.all() }+ val canRunUnattended = remember(tick) { ScheduledTaskScheduler.canRunUnattended(context) }++ val lifecycle = LocalLifecycleOwner.current.lifecycle+ DisposableEffect(lifecycle) {+ val observer = LifecycleEventObserver { _, event -> if (event == Lifecycle.Event.ON_RESUME) tick++ }+ lifecycle.addObserver(observer)+ onDispose { lifecycle.removeObserver(observer) }+ }++ /** Saves [task] as edited, re-armed, and the alarm with it. */+ fun changed(task: ScheduledTask) {+ scope.launch {+ withContext(Dispatchers.IO) {+ store.put(ScheduledTaskPlanner.armed(task, System.currentTimeMillis(), ZoneId.systemDefault()))+ ScheduledTaskScheduler.reschedule(context)+ }+ tick+++ }+ }++ val startedText = stringResource(R.string.scheduled_run_now_started)+ val busyText = stringResource(R.string.scheduled_run_now_busy)+ 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)+ if (tasks.isEmpty() && editing != NEW_TASK) {+ Text(+ stringResource(R.string.scheduled_empty),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ }+ tasks.forEach { task ->+ HorizontalDivider()+ if (editing == task.id) {+ TaskEditor(+ store = store,+ initial = task,+ onSaved = {+ editing = null+ tick+++ },+ onCancel = { editing = null }+ )+ } else {+ TaskRow(+ task = task,+ onEnabledChange = { changed(task.copy(enabled = it)) },+ onEdit = { editing = task.id },+ onRunNow = {+ scope.launch {+ val result = withContext(Dispatchers.IO) {+ ScheduledTaskRuns.runNow(context.applicationContext as Application, task.id)+ }+ overlay.show(+ when (result) {+ is ScheduledStart.Started -> startedText+ ScheduledStart.Busy -> busyText+ is ScheduledStart.Failed -> result.detail+ }+ )+ tick+++ }+ },+ onDelete = { deleting = task },+ onOpenChat = onOpenChat+ )+ }+ }+ HorizontalDivider()+ if (editing == NEW_TASK) {+ TaskEditor(+ store = store,+ initial = null,+ onSaved = {+ editing = null+ tick+++ },+ onCancel = { editing = null }+ )+ } else {+ Button(+ onClick = { editing = NEW_TASK },+ modifier = Modifier.fillMaxWidth().testTag("scheduled_add_task")+ ) { Text(stringResource(R.string.scheduled_add_task)) }+ }+ }++ deleting?.let { task ->+ SkinAlertDialog(+ onDismissRequest = { deleting = null },+ title = { Text(stringResource(R.string.scheduled_delete_title, task.name)) },+ text = { Text(stringResource(R.string.scheduled_delete_body)) },+ confirmButton = {+ TextButton(onClick = {+ deleting = null+ scope.launch {+ withContext(Dispatchers.IO) {+ store.delete(task.id)+ ScheduledTaskScheduler.reschedule(context)+ }+ if (editing == task.id) editing = null+ tick+++ }+ }) { Text(stringResource(R.string.scheduled_delete)) }+ },+ dismissButton = {+ TextButton(onClick = { deleting = null }) { Text(stringResource(R.string.scheduled_cancel)) }+ }+ )+ }+}++/** Shown while Gotcha may not set exact alarms: tasks then wait for a tap instead of running. */+@Composable+private fun ExactAlarmHint(context: Context) {+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Text(+ stringResource(R.string.scheduled_exact_alarm_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.error+ )+ if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.S) {+ OutlinedButton(+ onClick = {+ runCatching {+ context.startActivity(+ Intent(+ android.provider.Settings.ACTION_REQUEST_SCHEDULE_EXACT_ALARM,+ Uri.parse("package:${context.packageName}")+ ).addFlags(Intent.FLAG_ACTIVITY_NEW_TASK)+ )+ }+ },+ modifier = Modifier.testTag("scheduled_allow_exact_alarms")+ ) { Text(stringResource(R.string.scheduled_exact_alarm_allow)) }+ }+ }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun TaskRow(+ task: ScheduledTask,+ onEnabledChange: (Boolean) -> Unit,+ onEdit: () -> Unit,+ onRunNow: () -> Unit,+ onDelete: () -> Unit,+ onOpenChat: (String) -> Unit+) {+ val context = LocalContext.current+ var showHistory by remember { mutableStateOf(false) }+ Column(verticalArrangement = Arrangement.spacedBy(4.dp)) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Column(modifier = Modifier.weight(1f)) {+ Text(task.name, style = MaterialTheme.typography.bodyLarge, fontWeight = FontWeight.SemiBold)+ Text(scheduleText(context, task.start, task.repeat), style = MaterialTheme.typography.bodySmall)+ }+ Switch(+ checked = task.enabled,+ onCheckedChange = onEnabledChange,+ modifier = Modifier.testTag("scheduled_task_enabled_${task.id}")+ )+ }+ if (task.createdByAgent) {+ Text(+ stringResource(R.string.scheduled_set_up_by_gotcha),+ style = MaterialTheme.typography.labelSmall,+ color = MaterialTheme.colorScheme.primary+ )+ }+ val next = task.dueAt+ Text(+ when {+ !task.enabled -> stringResource(R.string.scheduled_paused)+ next == null -> stringResource(R.string.scheduled_no_more_runs)+ else -> stringResource(R.string.scheduled_next_run, formatDateTime(next))+ },+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ Text(+ stringResource(+ if (task.sameChat) R.string.scheduled_target_same_chat else R.string.scheduled_target_new_chat+ ) + " · " + stringResource(task.mode.labelRes()),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ task.lastRun?.let { run ->+ Text(+ stringResource(R.string.scheduled_last_run, statusText(run.status), formatDateTime(run.at)),+ style = MaterialTheme.typography.bodySmall,+ color = if (run.status.isProblem()) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurfaceVariant+ )+ }+ FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ TextButton(onClick = onEdit) { Text(stringResource(R.string.scheduled_edit)) }+ TextButton(onClick = onRunNow, modifier = Modifier.testTag("scheduled_run_now_${task.id}")) {+ Text(stringResource(R.string.scheduled_run_now))+ }+ if (task.history.isNotEmpty()) {+ TextButton(onClick = { showHistory = !showHistory }) {+ Text(+ stringResource(if (showHistory) R.string.scheduled_hide_history else R.string.scheduled_history)+ )+ }+ }+ TextButton(onClick = onDelete) { Text(stringResource(R.string.scheduled_delete)) }+ }+ if (showHistory) {+ task.history.asReversed().forEach { run -> HistoryRow(run, onOpenChat) }+ }+ }+}++@Composable+private fun HistoryRow(run: TaskRun, onOpenChat: (String) -> Unit) {+ Row(verticalAlignment = Alignment.CenterVertically) {+ Column(modifier = Modifier.weight(1f)) {+ Text(+ formatDateTime(run.at) + " · " + statusText(run.status),+ style = MaterialTheme.typography.bodySmall,+ color = if (run.status.isProblem()) MaterialTheme.colorScheme.error else MaterialTheme.colorScheme.onSurface+ )+ run.detail?.let {+ Text(it, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant)+ }+ }+ run.sessionId?.let { id ->+ TextButton(onClick = { onOpenChat(id) }) { Text(stringResource(R.string.scheduled_open_chat)) }+ }+ }+}++/** The add/edit form. [initial] null adds a task. */+@OptIn(ExperimentalLayoutApi::class)+@Composable+@Suppress("LongMethod", "CyclomaticComplexMethod")+private fun TaskEditor(+ store: ScheduledTaskStore,+ initial: ScheduledTask?,+ onSaved: () -> Unit,+ onCancel: () -> Unit+) {+ val context = LocalContext.current+ val scope = rememberCoroutineScope()+ val start = remember { initial?.start ?: defaultStart() }+ var name by remember { mutableStateOf(initial?.name.orEmpty()) }+ var prompt by remember { mutableStateOf(initial?.prompt.orEmpty()) }+ var date by remember { mutableStateOf(start.toLocalDate()) }+ var time by remember { mutableStateOf(start.toLocalTime()) }+ var kind by remember { mutableStateOf(initial?.repeat?.kind ?: RepeatKind.NONE) }+ var interval by remember { mutableStateOf((initial?.repeat?.interval ?: 1).toString()) }+ var weekdays by remember { mutableStateOf(initial?.repeat?.weekdays?.toSet() ?: emptySet()) }+ var mode by remember { mutableStateOf(initial?.mode ?: AgentMode.MONITOR) }+ var personaId by remember { mutableStateOf(initial?.personaId) }+ var sameChat by remember { mutableStateOf(initial?.sameChat ?: false) }+ var chatSessionId by remember { mutableStateOf(initial?.chatSessionId) }+ var retries by remember { mutableStateOf(initial?.maxRetries ?: ScheduledTask.DEFAULT_MAX_RETRIES) }+ var files by remember { mutableStateOf<List<ComposerAttachment>>(emptyList()) }+ var error by remember { mutableStateOf("") }+ var chats by remember { mutableStateOf<List<Pair<String, String>>>(emptyList()) }++ LaunchedEffect(Unit) {+ withContext(Dispatchers.IO) {+ initial?.let { files = store.loadAttachments(it).orEmpty() }+ chats = ChatHistoryRepository(context).mapSessions { if (it.isSample) null else it.id to it.title }+ .filterNotNull()+ }+ }++ val unreadable = stringResource(R.string.scheduled_file_unreadable)+ val tooMany = stringResource(R.string.scheduled_too_many_files, ComposerAttachment.MAX_PER_MESSAGE)+ val picker = rememberLauncherForActivityResult(ActivityResultContracts.OpenMultipleDocuments()) { uris ->+ if (uris.isEmpty()) return@rememberLauncherForActivityResult+ scope.launch {+ val loaded = withContext(Dispatchers.IO) { uris.map { readPickedFile(context, it) } }+ val ok = loaded.filterNotNull()+ val room = ComposerAttachment.MAX_PER_MESSAGE - files.size+ files = files + ok.take(room.coerceAtLeast(0))+ error = when {+ ok.size > room -> tooMany+ ok.size < loaded.size -> unreadable+ else -> ""+ }+ }+ }++ val missingName = stringResource(R.string.scheduled_error_name)+ val missingPrompt = stringResource(R.string.scheduled_error_prompt)+ val pastTime = stringResource(R.string.scheduled_error_past)+ val badInterval = stringResource(R.string.scheduled_error_interval, ScheduledTask.MAX_INTERVAL)+ val tooMuchText = stringResource(R.string.scheduled_error_too_much_text)++ Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedTextField(+ value = name,+ onValueChange = { name = it.take(80) },+ label = { Text(stringResource(R.string.scheduled_field_name)) },+ singleLine = true,+ modifier = Modifier.fillMaxWidth().testTag("scheduled_field_name")+ )+ OutlinedTextField(+ value = prompt,+ onValueChange = { prompt = it.take(4000) },+ label = { Text(stringResource(R.string.scheduled_field_prompt)) },+ minLines = 3,+ modifier = Modifier.fillMaxWidth().testTag("scheduled_field_prompt")+ )++ Text(stringResource(R.string.scheduled_field_when), style = MaterialTheme.typography.labelLarge)+ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ OutlinedButton(onClick = { showDatePicker(context, date) { date = it } }) {+ Text(date.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.MEDIUM)))+ }+ OutlinedButton(onClick = { showTimePicker(context, time) { time = it } }) {+ Text(time.format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT)))+ }+ }++ Text(stringResource(R.string.scheduled_field_repeat), style = MaterialTheme.typography.labelLarge)+ ChoiceChips(+ options = listOf(+ RepeatKind.NONE to stringResource(R.string.scheduled_repeat_none),+ RepeatKind.HOURLY to stringResource(R.string.scheduled_repeat_hourly),+ RepeatKind.DAILY to stringResource(R.string.scheduled_repeat_daily),+ RepeatKind.WEEKLY to stringResource(R.string.scheduled_repeat_weekly),+ RepeatKind.MONTHLY to stringResource(R.string.scheduled_repeat_monthly)+ ),+ selected = kind,+ onSelect = { kind = it }+ )+ if (kind == RepeatKind.HOURLY || kind == RepeatKind.DAILY) {+ OutlinedTextField(+ value = interval,+ onValueChange = { interval = it.filter(Char::isDigit).take(3) },+ label = {+ Text(+ stringResource(+ if (kind == RepeatKind.HOURLY) R.string.scheduled_field_every_hours else R.string.scheduled_field_every_days+ )+ )+ },+ singleLine = true,+ keyboardOptions = KeyboardOptions(keyboardType = KeyboardType.Number),+ modifier = Modifier.fillMaxWidth()+ )+ }+ if (kind == RepeatKind.WEEKLY) {+ FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ val shown = weekdays.ifEmpty { setOf(date.dayOfWeek.value) }+ DayOfWeek.entries.forEach { day ->+ val chosen = day.value in shown+ SolidChip(+ label = day.getDisplayName(TextStyle.SHORT, Locale.getDefault()),+ selected = chosen,+ onClick = {+ val next = if (chosen) shown - day.value else shown + day.value+ weekdays = next.ifEmpty { shown }+ }+ )+ }+ }+ }++ Text(stringResource(R.string.scheduled_field_mode), style = MaterialTheme.typography.labelLarge)+ ChoiceChips(+ options = AgentMode.entries.map { it to stringResource(it.labelRes()) },+ selected = mode,+ onSelect = { mode = it }+ )+ Text(+ stringResource(R.string.scheduled_mode_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )++ Text(stringResource(R.string.scheduled_field_persona), style = MaterialTheme.typography.labelLarge)+ ChoiceChips(+ options = listOf<Pair<String?, String>>(null to stringResource(R.string.scheduled_persona_none)) ++ PERSONAS.map { it.id to stringResource(it.name) },+ selected = personaId,+ onSelect = { personaId = it }+ )++ Text(stringResource(R.string.scheduled_field_target), style = MaterialTheme.typography.labelLarge)+ ChoiceChips(+ options = listOf(+ false to stringResource(R.string.scheduled_target_new_chat),+ true to stringResource(R.string.scheduled_target_same_chat)+ ),+ selected = sameChat,+ onSelect = { sameChat = it }+ )+ if (sameChat) {+ val strings = context.stringLookup()+ Text(+ stringResource(R.string.scheduled_same_chat_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ ChoiceChips(+ options = listOf<Pair<String?, String>>(null to stringResource(R.string.scheduled_chat_first_run)) ++ chats.take(MAX_CHATS_OFFERED).map { (id, title) -> id to ChatTitle.display(title, strings) },+ selected = chatSessionId,+ onSelect = { chatSessionId = it }+ )+ }++ Text(stringResource(R.string.scheduled_field_files), style = MaterialTheme.typography.labelLarge)+ files.forEach { file ->+ Row(verticalAlignment = Alignment.CenterVertically) {+ Text(file.name, style = MaterialTheme.typography.bodySmall, modifier = Modifier.weight(1f))+ TextButton(onClick = { files = files.filterNot { it.id == file.id } }) {+ Text(stringResource(R.string.scheduled_remove_file))+ }+ }+ }+ OutlinedButton(onClick = { picker.launch(arrayOf("*/*")) }) {+ Text(stringResource(R.string.scheduled_add_files))+ }++ Text(stringResource(R.string.scheduled_field_retries), style = MaterialTheme.typography.labelLarge)+ ChoiceChips(+ options = (0..3).map { it to pluralStringResource(R.plurals.scheduled_retries, it, it) },+ selected = retries,+ onSelect = { retries = it }+ )+ Text(+ stringResource(R.string.scheduled_unattended_hint),+ style = MaterialTheme.typography.bodySmall,+ color = MaterialTheme.colorScheme.onSurfaceVariant+ )+ if (error.isNotBlank()) {+ Text(error, style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.error)+ }++ Row(horizontalArrangement = Arrangement.spacedBy(8.dp)) {+ Button(+ onClick = {+ val every = interval.toIntOrNull()+ val startAt = LocalDateTime.of(date, time.withSecond(0).withNano(0))+ error = when {+ name.isBlank() -> missingName+ prompt.isBlank() -> missingPrompt+ (kind == RepeatKind.HOURLY || kind == RepeatKind.DAILY) &&+ (every == null || every !in 1..ScheduledTask.MAX_INTERVAL) -> badInterval+ kind == RepeatKind.NONE &&+ !startAt.atZone(ZoneId.systemDefault()).toInstant().isAfter(Instant.now()) -> pastTime+ AttachmentFiles.documentChars(files) > ComposerAttachment.MAX_TOTAL_DOCUMENT_CHARS -> tooMuchText+ else -> ""+ }+ if (error.isNotEmpty()) return@Button+ val task = (+ initial ?: ScheduledTask(+ id = UUID.randomUUID().toString(),+ name = "",+ prompt = "",+ startLocal = "",+ createdAt = System.currentTimeMillis()+ )+ ).copy(+ name = name.trim(),+ prompt = prompt.trim(),+ startLocal = startAt.toString(),+ repeat = Repeat(+ kind = kind,+ interval = if (kind == RepeatKind.HOURLY || kind == RepeatKind.DAILY) every ?: 1 else 1,+ weekdays = if (kind == RepeatKind.WEEKLY) weekdays.sorted() else emptyList()+ ),+ agentMode = mode.name,+ personaId = personaId,+ sameChat = sameChat,+ chatSessionId = if (sameChat) chatSessionId else null,+ 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)+ }+ onSaved()+ }+ },+ modifier = Modifier.testTag("scheduled_save")+ ) { Text(stringResource(R.string.scheduled_save)) }+ TextButton(onClick = onCancel) { Text(stringResource(R.string.scheduled_cancel)) }+ }+ }+}++@OptIn(ExperimentalLayoutApi::class)+@Composable+private fun <T> ChoiceChips(options: List<Pair<T, String>>, selected: T, onSelect: (T) -> Unit) {+ FlowRow(horizontalArrangement = Arrangement.spacedBy(4.dp)) {+ options.forEach { (value, label) ->+ SolidChip(label = label, selected = value == selected, onClick = { onSelect(value) })+ }+ }+}++/** Solid when chosen, like the persona chips: the default fill goes translucent on the glass skins. */+@Composable+private fun SolidChip(label: String, selected: Boolean, onClick: () -> Unit) {+ FilterChip(+ selected = selected,+ onClick = onClick,+ label = { Text(label) },+ leadingIcon = if (selected) {+ { Icon(Icons.Default.Check, contentDescription = null, modifier = Modifier.size(18.dp)) }+ } else {+ null+ },+ colors = FilterChipDefaults.filterChipColors(+ selectedContainerColor = MaterialTheme.colorScheme.primary,+ selectedLabelColor = MaterialTheme.colorScheme.onPrimary,+ selectedLeadingIconColor = MaterialTheme.colorScheme.onPrimary+ )+ )+}++/** The schedule in the user's language: "Every 2 days at 08:00", "Once, 19 Oct 2026, 08:00". */+internal fun scheduleText(context: Context, start: LocalDateTime, repeat: Repeat): String {+ val time = start.toLocalTime().format(DateTimeFormatter.ofLocalizedTime(FormatStyle.SHORT))+ val res = context.resources+ return when (repeat.kind) {+ RepeatKind.NONE -> context.getString(+ R.string.scheduled_schedule_once,+ start.format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT))+ )+ // "Every hour" has a string of its own: in some languages the plural for+ // one also covers zero, so it has to show the number.+ RepeatKind.HOURLY -> if (repeat.interval == 1) {+ context.getString(R.string.scheduled_schedule_every_hour)+ } else {+ res.getQuantityString(R.plurals.scheduled_schedule_hours, repeat.interval, repeat.interval)+ }+ RepeatKind.DAILY -> if (repeat.interval == 1) {+ context.getString(R.string.scheduled_schedule_every_day, time)+ } else {+ res.getQuantityString(R.plurals.scheduled_schedule_days, repeat.interval, repeat.interval, time)+ }+ RepeatKind.WEEKLY -> context.getString(+ R.string.scheduled_schedule_weekly,+ repeat.weekdays.ifEmpty { listOf(start.dayOfWeek.value) }+ .joinToString { DayOfWeek.of(it).getDisplayName(TextStyle.SHORT, Locale.getDefault()) },+ time+ )+ RepeatKind.MONTHLY -> context.getString(R.string.scheduled_schedule_monthly, start.dayOfMonth, time)+ }+}++@Composable+private fun statusText(status: TaskRunStatus): String = stringResource(+ when (status) {+ TaskRunStatus.DONE -> R.string.scheduled_status_done+ TaskRunStatus.FAILED -> R.string.scheduled_status_failed+ TaskRunStatus.STOPPED -> R.string.scheduled_status_stopped+ TaskRunStatus.MISSED -> R.string.scheduled_status_missed+ TaskRunStatus.SKIPPED_BUSY -> R.string.scheduled_status_skipped_busy+ TaskRunStatus.NEEDS_TAP -> R.string.scheduled_status_needs_tap+ TaskRunStatus.NOT_STARTED -> R.string.scheduled_status_not_started+ }+)++private fun AgentMode.labelRes(): Int = when (this) {+ AgentMode.MONITOR -> R.string.chat_monitor+ AgentMode.OPERATOR -> R.string.chat_operator+}++private fun TaskRunStatus.isProblem(): Boolean = this != TaskRunStatus.DONE && this != TaskRunStatus.STOPPED++private fun formatDateTime(at: Long): String =+ LocalDateTime.ofInstant(Instant.ofEpochMilli(at), ZoneId.systemDefault())+ .format(DateTimeFormatter.ofLocalizedDateTime(FormatStyle.MEDIUM, FormatStyle.SHORT))++/** A new task starts on the next whole hour. */+private fun defaultStart(): LocalDateTime =+ LocalDateTime.now().withMinute(0).withSecond(0).withNano(0).plusHours(1)++private fun showDatePicker(context: Context, date: LocalDate, onPick: (LocalDate) -> Unit) {+ DatePickerDialog(+ context,+ { _, year, month, day -> onPick(LocalDate.of(year, month + 1, day)) },+ date.year,+ date.monthValue - 1,+ date.dayOfMonth+ ).show()+}++private fun showTimePicker(context: Context, time: LocalTime, onPick: (LocalTime) -> Unit) {+ TimePickerDialog(+ context,+ { _, hour, minute -> onPick(LocalTime.of(hour, minute)) },+ time.hour,+ time.minute,+ DateFormat.is24HourFormat(context)+ ).show()+}++/** Reads one picked file into an attachment, as the composer does; null when it can't be read. */+private fun readPickedFile(context: Context, uri: Uri): ComposerAttachment? = runCatching {+ val resolver = context.contentResolver+ val bytes = resolver.openInputStream(uri)?.use { it.readBytes() } ?: return null+ val name = resolver.query(uri, null, null, null, null)?.use { cursor ->+ val index = cursor.getColumnIndex(OpenableColumns.DISPLAY_NAME)+ if (cursor.moveToFirst() && index >= 0) cursor.getString(index) else null+ }?.takeIf { it.isNotBlank() } ?: uri.lastPathSegment.orEmpty().ifBlank { "file" }+ AttachmentFiles.fromBytes(bytes, name, resolver.getType(uri))+}.getOrNull()++/** How many recent chats the same-chat picker offers. */+private const val MAX_CHATS_OFFERED = 8diff --git a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt b/app/src/main/java/com/gotcha/ui/SettingsCommon.ktindex a4263c3..05a4f44 100644--- a/app/src/main/java/com/gotcha/ui/SettingsCommon.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsCommon.kt@@ -164,6 +164,11 @@ enum class SettingsPage(R.string.settings_page_skills_summary,"settings_skills_row"),+ SCHEDULED_TASKS(+ R.string.settings_page_scheduled_tasks,+ R.string.settings_page_scheduled_tasks_summary,+ "settings_scheduled_tasks_row"+ ),PROACTIVE(R.string.settings_page_proactive,R.string.settings_page_proactive_summary,diff --git a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt b/app/src/main/java/com/gotcha/ui/SettingsScreen.ktindex 3bd22cd..45fa2bc 100644--- a/app/src/main/java/com/gotcha/ui/SettingsScreen.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsScreen.kt@@ -125,6 +125,8 @@ fun SettingsScreen(onStartTour: () -> Unit = {},/** Opens the in-app feedback consent sheet (hidden when no form is configured). */onSendFeedback: () -> Unit = {},+ /** Leaves Settings for chat [String], e.g. the one a scheduled task's run went into. */+ onOpenChat: (String) -> Unit = {},/*** Which sub-page is open; null is the home list.*@@ -250,6 +252,10 @@ fun SettingsScreen(onSave = onSave,onBack = backToHome)+ SettingsPage.SCHEDULED_TASKS -> ScheduledTasksScreen(+ onBack = backToHome,+ onOpenChat = onOpenChat+ )SettingsPage.PROACTIVE -> ProactiveScreen(load = load,onSave = onSave,diff --git a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.ktindex 2d32683..c6abebf 100644--- a/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt+++ b/app/src/main/java/com/gotcha/ui/SettingsSearchEntry.kt@@ -226,6 +226,10 @@ private fun entryFor(page: SettingsPage): SettingsSearchEntry = when (page) {page,words("plugin, skill, community, import, mcp"))+ SettingsPage.SCHEDULED_TASKS -> SettingsSearchEntry(+ page,+ words("schedule, scheduled, routine, recurring, repeat, automation, cron, every morning, daily, weekly")+ )SettingsPage.PROACTIVE -> SettingsSearchEntry(page,words("privacy"),diff --git a/app/src/main/res/values-de/strings.xml b/app/src/main/res/values-de/strings.xmlindex 0372625..503fed3 100644--- a/app/src/main/res/values-de/strings.xml+++ b/app/src/main/res/values-de/strings.xml@@ -1464,4 +1464,93 @@<string name="mcp_error_rpc">Der Server hat einen Fehler gemeldet: %1$s</string><string name="mcp_error_network">Der Server ist nicht erreichbar: %1$s</string><string name="mcp_error_bad_token">Token und Header-Werte dürfen nur einfache ASCII-Zeichen enthalten.</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">Geplante Aufgaben</string>+ <string name="channel_scheduled_tasks_description">Eine geplante Aufgabe, die zum Start ein Tippen braucht</string>+ <string name="scheduled_needs_tap_title">„%1$s“ ist fällig</string>+ <string name="scheduled_needs_tap_body">Tippe, um sie jetzt auszuführen. Damit Aufgaben von selbst laufen, erlaube Gotcha, Wecker und Erinnerungen zu stellen.</string>+ <string name="scheduled_needs_tap_public_title">Eine geplante Aufgabe ist fällig</string>+ <string name="scheduled_task_gone">Diese Aufgabe gibt es nicht mehr.</string>+ <string name="scheduled_task_files_missing">Die mit dieser Aufgabe gespeicherten Dateien lassen sich nicht mehr lesen. Füge sie in den Einstellungen erneut hinzu.</string>+ <string name="scheduled_task_needs_exact_alarms">Wartet auf ein Tippen: Gotcha darf keine exakten Wecker stellen.</string>+ <string name="settings_page_scheduled_tasks">Geplante Aufgaben</string>+ <string name="settings_page_scheduled_tasks_summary">Prompts, die Gotcha zu festen Zeiten selbst ausführt</string>+ <string name="scheduled_intro">Gotcha schickt sich zur eingestellten Zeit einen Prompt und arbeitet ihn ab wie jeden Chat. Das Ergebnis landet in einem Chat, mit einer Benachrichtigung, wenn du nicht in der App bist.</string>+ <string name="scheduled_empty">Noch keine geplanten Aufgaben. Füge hier eine hinzu oder bitte Gotcha im Chat darum, z. B. „jeden Werktag um 8 meine ungelesenen Mails zusammenfassen“.</string>+ <string name="scheduled_add_task">Aufgabe hinzufügen</string>+ <string name="scheduled_exact_alarm_hint">Gotcha darf keine exakten Wecker stellen, daher kann eine Aufgabe nicht von selbst starten: Sie bittet dich stattdessen, auf eine Benachrichtigung zu tippen.</string>+ <string name="scheduled_exact_alarm_allow">Wecker und Erinnerungen erlauben</string>+ <string name="scheduled_set_up_by_gotcha">Von Gotcha in einem Chat eingerichtet</string>+ <string name="scheduled_paused">Pausiert</string>+ <string name="scheduled_no_more_runs">Keine weiteren Ausführungen</string>+ <string name="scheduled_next_run">Nächste: %1$s</string>+ <string name="scheduled_target_new_chat">Jedes Mal ein neuer Chat</string>+ <string name="scheduled_target_same_chat">Jedes Mal derselbe Chat</string>+ <string name="scheduled_last_run">Zuletzt: %1$s, %2$s</string>+ <string name="scheduled_edit">Bearbeiten</string>+ <string name="scheduled_run_now">Jetzt ausführen</string>+ <string name="scheduled_run_now_started">Gestartet. Sie läuft in ihrem Chat.</string>+ <string name="scheduled_run_now_busy">Gotcha arbeitet gerade an einer anderen Aufgabe. Versuche es, wenn sie fertig ist.</string>+ <string name="scheduled_history">Verlauf</string>+ <string name="scheduled_hide_history">Verlauf ausblenden</string>+ <string name="scheduled_open_chat">Chat öffnen</string>+ <string name="scheduled_delete">Löschen</string>+ <string name="scheduled_delete_title">„%1$s“ löschen?</string>+ <string name="scheduled_delete_body">Die Aufgabe und ihr Verlauf werden entfernt. Die Chats ihrer Ausführungen bleiben erhalten.</string>+ <string name="scheduled_cancel">Abbrechen</string>+ <string name="scheduled_save">Speichern</string>+ <string name="scheduled_field_name">Name</string>+ <string name="scheduled_field_prompt">Was Gotcha tun soll</string>+ <string name="scheduled_field_when">Erste Ausführung</string>+ <string name="scheduled_field_repeat">Wiederholen</string>+ <string name="scheduled_repeat_none">Einmal</string>+ <string name="scheduled_repeat_hourly">Alle paar Stunden</string>+ <string name="scheduled_repeat_daily">Alle paar Tage</string>+ <string name="scheduled_repeat_weekly">Wöchentlich</string>+ <string name="scheduled_repeat_monthly">Monatlich</string>+ <string name="scheduled_field_every_hours">Alle wie viele Stunden</string>+ <string name="scheduled_field_every_days">Alle wie viele Tage</string>+ <string name="scheduled_field_mode">Modus</string>+ <string name="scheduled_mode_hint">Monitor kann nur nachsehen und berichten. Operator kann auf deinem Handy handeln, ohne dass jemand zusieht: Wähle ihn nur für Aufgaben, die ihn brauchen.</string>+ <string name="scheduled_field_persona">Persona</string>+ <string name="scheduled_persona_none">Keine</string>+ <string name="scheduled_field_target">Wo sie läuft</string>+ <string name="scheduled_same_chat_hint">Jede Ausführung wird diesem Chat angehängt, sodass Gotcha die früheren sieht.</string>+ <string name="scheduled_chat_first_run">Ein neuer Chat, der für spätere Ausführungen bleibt</string>+ <string name="scheduled_field_files">Dateien zum Prompt</string>+ <string name="scheduled_add_files">Dateien hinzufügen</string>+ <string name="scheduled_remove_file">Entfernen</string>+ <string name="scheduled_field_retries">Wenn eine Ausführung fehlschlägt</string>+ <string name="scheduled_unattended_hint">Eine Ausführung, die deine Antwort braucht, wartet zwei Minuten darauf und macht dann weiter, als hättest du Nein gesagt.</string>+ <string name="scheduled_file_unreadable">Einige Dateien ließen sich nicht lesen und wurden weggelassen.</string>+ <string name="scheduled_too_many_files">Mit einer Aufgabe gehen höchstens %1$d Dateien.</string>+ <string name="scheduled_error_name">Gib der Aufgabe einen Namen.</string>+ <string name="scheduled_error_prompt">Sag, was Gotcha tun soll.</string>+ <string name="scheduled_error_past">Diese Zeit ist schon vorbei. Wähle eine spätere oder eine Wiederholung.</string>+ <string name="scheduled_error_interval">Nimm eine Zahl von 1 bis %1$d.</string>+ <string name="scheduled_error_too_much_text">Diese Dokumente enthalten zu viel Text für eine Aufgabe. Entferne einige.</string>+ <string name="scheduled_schedule_every_hour">Jede Stunde</string>+ <string name="scheduled_schedule_every_day">Jeden Tag um %1$s</string>+ <string name="scheduled_schedule_once">Einmal, %1$s</string>+ <string name="scheduled_schedule_weekly">Jeden %1$s um %2$s</string>+ <string name="scheduled_schedule_monthly">Monatlich am %1$d. um %2$s</string>+ <string name="scheduled_status_done">Erledigt</string>+ <string name="scheduled_status_failed">Fehlgeschlagen</string>+ <string name="scheduled_status_stopped">Gestoppt</string>+ <string name="scheduled_status_missed">Verpasst: Das Handy war aus oder im Ruhezustand</string>+ <string name="scheduled_status_skipped_busy">Übersprungen: Gotcha war beschäftigt</string>+ <string name="scheduled_status_needs_tap">Wartet auf ein Tippen</string>+ <string name="scheduled_status_not_started">Konnte nicht starten</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="one">Alle %1$d Stunden</item>+ <item quantity="other">Alle %1$d Stunden</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="one">Alle %1$d Tage um %2$s</item>+ <item quantity="other">Alle %1$d Tage um %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="one">%1$d-mal wiederholen</item>+ <item quantity="other">%1$d-mal wiederholen</item>+ </plurals></resources>diff --git a/app/src/main/res/values-es/strings.xml b/app/src/main/res/values-es/strings.xmlindex 9a09b07..da12278 100644--- a/app/src/main/res/values-es/strings.xml+++ b/app/src/main/res/values-es/strings.xml@@ -1483,4 +1483,96 @@<string name="mcp_error_rpc">El servidor devolvió un error: %1$s</string><string name="mcp_error_network">No se pudo conectar con el servidor: %1$s</string><string name="mcp_error_bad_token">El token y los valores de las cabeceras solo pueden contener caracteres ASCII simples.</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">Tareas programadas</string>+ <string name="channel_scheduled_tasks_description">Una tarea programada que necesita un toque para ejecutarse</string>+ <string name="scheduled_needs_tap_title">«%1$s» toca ahora</string>+ <string name="scheduled_needs_tap_body">Toca para ejecutarla ahora. Para que las tareas se ejecuten solas, permite que Gotcha programe alarmas y recordatorios.</string>+ <string name="scheduled_needs_tap_public_title">Toca una tarea programada</string>+ <string name="scheduled_task_gone">Esta tarea ya no existe.</string>+ <string name="scheduled_task_files_missing">Los archivos guardados con esta tarea ya no se pueden leer. Vuelve a añadirlos en Ajustes.</string>+ <string name="scheduled_task_needs_exact_alarms">Esperando un toque: Gotcha no puede programar alarmas exactas.</string>+ <string name="settings_page_scheduled_tasks">Tareas programadas</string>+ <string name="settings_page_scheduled_tasks_summary">Prompts que Gotcha ejecuta por su cuenta a horas fijas</string>+ <string name="scheduled_intro">A la hora que elijas, Gotcha se envía un prompt y trabaja en él como en cualquier chat. El resultado llega a un chat, con una notificación si no estás en la app.</string>+ <string name="scheduled_empty">Aún no hay tareas programadas. Añade una aquí o pídeselo a Gotcha en un chat, p. ej. «cada día laborable a las 8, resume mis correos sin leer».</string>+ <string name="scheduled_add_task">Añadir una tarea</string>+ <string name="scheduled_exact_alarm_hint">Gotcha no puede programar alarmas exactas, así que una tarea no puede empezar sola: te pedirá que toques una notificación.</string>+ <string name="scheduled_exact_alarm_allow">Permitir alarmas y recordatorios</string>+ <string name="scheduled_set_up_by_gotcha">Creada por Gotcha en un chat</string>+ <string name="scheduled_paused">En pausa</string>+ <string name="scheduled_no_more_runs">No hay más ejecuciones</string>+ <string name="scheduled_next_run">Próxima: %1$s</string>+ <string name="scheduled_target_new_chat">Un chat nuevo cada vez</string>+ <string name="scheduled_target_same_chat">El mismo chat cada vez</string>+ <string name="scheduled_last_run">Última: %1$s, %2$s</string>+ <string name="scheduled_edit">Editar</string>+ <string name="scheduled_run_now">Ejecutar ahora</string>+ <string name="scheduled_run_now_started">Iniciada. Se está ejecutando en su chat.</string>+ <string name="scheduled_run_now_busy">Gotcha está ocupado con otra tarea. Vuelve a intentarlo cuando termine.</string>+ <string name="scheduled_history">Historial</string>+ <string name="scheduled_hide_history">Ocultar historial</string>+ <string name="scheduled_open_chat">Abrir chat</string>+ <string name="scheduled_delete">Eliminar</string>+ <string name="scheduled_delete_title">¿Eliminar «%1$s»?</string>+ <string name="scheduled_delete_body">Se eliminan la tarea y su historial. Los chats de sus ejecuciones se conservan.</string>+ <string name="scheduled_cancel">Cancelar</string>+ <string name="scheduled_save">Guardar</string>+ <string name="scheduled_field_name">Nombre</string>+ <string name="scheduled_field_prompt">Qué debe hacer Gotcha</string>+ <string name="scheduled_field_when">Primera ejecución</string>+ <string name="scheduled_field_repeat">Repetir</string>+ <string name="scheduled_repeat_none">Una vez</string>+ <string name="scheduled_repeat_hourly">Cada pocas horas</string>+ <string name="scheduled_repeat_daily">Cada pocos días</string>+ <string name="scheduled_repeat_weekly">Cada semana</string>+ <string name="scheduled_repeat_monthly">Cada mes</string>+ <string name="scheduled_field_every_hours">Cada cuántas horas</string>+ <string name="scheduled_field_every_days">Cada cuántos días</string>+ <string name="scheduled_field_mode">Modo</string>+ <string name="scheduled_mode_hint">Monitor solo puede mirar e informar. Operator puede actuar en tu teléfono sin que nadie lo vea: elígelo solo para tareas que lo necesiten.</string>+ <string name="scheduled_field_persona">Persona</string>+ <string name="scheduled_persona_none">Ninguna</string>+ <string name="scheduled_field_target">Dónde se ejecuta</string>+ <string name="scheduled_same_chat_hint">Cada ejecución se añade a este chat, así Gotcha ve las anteriores.</string>+ <string name="scheduled_chat_first_run">Un chat nuevo, que se guarda para las siguientes</string>+ <string name="scheduled_field_files">Archivos enviados con el prompt</string>+ <string name="scheduled_add_files">Añadir archivos</string>+ <string name="scheduled_remove_file">Quitar</string>+ <string name="scheduled_field_retries">Si una ejecución falla</string>+ <string name="scheduled_unattended_hint">Una ejecución que necesita tu respuesta la espera dos minutos y luego sigue como si hubieras dicho que no.</string>+ <string name="scheduled_file_unreadable">Algunos archivos no se pudieron leer y se omitieron.</string>+ <string name="scheduled_too_many_files">Una tarea puede llevar como máximo %1$d archivos.</string>+ <string name="scheduled_error_name">Ponle un nombre a la tarea.</string>+ <string name="scheduled_error_prompt">Di qué debe hacer Gotcha.</string>+ <string name="scheduled_error_past">Esa hora ya pasó. Elige una posterior o una repetición.</string>+ <string name="scheduled_error_interval">Usa un número del 1 al %1$d.</string>+ <string name="scheduled_error_too_much_text">Esos documentos tienen demasiado texto para una tarea. Quita algunos.</string>+ <string name="scheduled_schedule_every_hour">Cada hora</string>+ <string name="scheduled_schedule_every_day">Cada día a las %1$s</string>+ <string name="scheduled_schedule_once">Una vez, %1$s</string>+ <string name="scheduled_schedule_weekly">Cada %1$s a las %2$s</string>+ <string name="scheduled_schedule_monthly">Cada mes el día %1$d a las %2$s</string>+ <string name="scheduled_status_done">Hecha</string>+ <string name="scheduled_status_failed">Fallida</string>+ <string name="scheduled_status_stopped">Detenida</string>+ <string name="scheduled_status_missed">Perdida: el teléfono estaba apagado o en reposo</string>+ <string name="scheduled_status_skipped_busy">Omitida: Gotcha estaba ocupado</string>+ <string name="scheduled_status_needs_tap">Esperando un toque</string>+ <string name="scheduled_status_not_started">No se pudo iniciar</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="one">Cada %1$d horas</item>+ <item quantity="many">Cada %1$d horas</item>+ <item quantity="other">Cada %1$d horas</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="one">Cada %1$d días a las %2$s</item>+ <item quantity="many">Cada %1$d días a las %2$s</item>+ <item quantity="other">Cada %1$d días a las %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="one">Reintentar %1$d vez</item>+ <item quantity="many">Reintentar %1$d veces</item>+ <item quantity="other">Reintentar %1$d veces</item>+ </plurals></resources>diff --git a/app/src/main/res/values-fr/strings.xml b/app/src/main/res/values-fr/strings.xmlindex 2574d65..c8cb0fb 100644--- a/app/src/main/res/values-fr/strings.xml+++ b/app/src/main/res/values-fr/strings.xml@@ -1483,4 +1483,96 @@<string name="mcp_error_rpc">Le serveur a renvoyé une erreur : %1$s</string><string name="mcp_error_network">Impossible de joindre le serveur : %1$s</string><string name="mcp_error_bad_token">Le jeton et les valeurs des en-têtes ne peuvent contenir que des caractères ASCII simples.</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">Tâches planifiées</string>+ <string name="channel_scheduled_tasks_description">Une tâche planifiée qui attend un appui pour se lancer</string>+ <string name="scheduled_needs_tap_title">« %1$s » est à faire</string>+ <string name="scheduled_needs_tap_body">Appuyez pour la lancer maintenant. Pour que les tâches se lancent seules, autorisez Gotcha à définir des alarmes et des rappels.</string>+ <string name="scheduled_needs_tap_public_title">Une tâche planifiée est à faire</string>+ <string name="scheduled_task_gone">Cette tâche n’existe plus.</string>+ <string name="scheduled_task_files_missing">Les fichiers enregistrés avec cette tâche ne sont plus lisibles. Ajoutez-les de nouveau dans les paramètres.</string>+ <string name="scheduled_task_needs_exact_alarms">En attente d’un appui : Gotcha ne peut pas définir d’alarmes exactes.</string>+ <string name="settings_page_scheduled_tasks">Tâches planifiées</string>+ <string name="settings_page_scheduled_tasks_summary">Des prompts que Gotcha exécute seul à heure fixe</string>+ <string name="scheduled_intro">À l’heure choisie, Gotcha s’envoie un prompt et le traite comme n’importe quel chat. Le résultat arrive dans un chat, avec une notification si vous n’êtes pas dans l’app.</string>+ <string name="scheduled_empty">Aucune tâche planifiée pour l’instant. Ajoutez-en une ici, ou demandez à Gotcha dans un chat, par ex. « chaque jour de semaine à 8 h, résume mes e-mails non lus ».</string>+ <string name="scheduled_add_task">Ajouter une tâche</string>+ <string name="scheduled_exact_alarm_hint">Gotcha ne peut pas définir d’alarmes exactes, donc une tâche ne peut pas se lancer seule : elle vous demandera d’appuyer sur une notification.</string>+ <string name="scheduled_exact_alarm_allow">Autoriser les alarmes et rappels</string>+ <string name="scheduled_set_up_by_gotcha">Créée par Gotcha dans un chat</string>+ <string name="scheduled_paused">En pause</string>+ <string name="scheduled_no_more_runs">Plus d’exécution prévue</string>+ <string name="scheduled_next_run">Prochaine : %1$s</string>+ <string name="scheduled_target_new_chat">Un nouveau chat à chaque fois</string>+ <string name="scheduled_target_same_chat">Le même chat à chaque fois</string>+ <string name="scheduled_last_run">Dernière : %1$s, %2$s</string>+ <string name="scheduled_edit">Modifier</string>+ <string name="scheduled_run_now">Lancer maintenant</string>+ <string name="scheduled_run_now_started">Lancée. Elle s’exécute dans son chat.</string>+ <string name="scheduled_run_now_busy">Gotcha est occupé par une autre tâche. Réessayez quand elle sera terminée.</string>+ <string name="scheduled_history">Historique</string>+ <string name="scheduled_hide_history">Masquer l’historique</string>+ <string name="scheduled_open_chat">Ouvrir le chat</string>+ <string name="scheduled_delete">Supprimer</string>+ <string name="scheduled_delete_title">Supprimer « %1$s » ?</string>+ <string name="scheduled_delete_body">La tâche et son historique sont supprimés. Les chats de ses exécutions sont conservés.</string>+ <string name="scheduled_cancel">Annuler</string>+ <string name="scheduled_save">Enregistrer</string>+ <string name="scheduled_field_name">Nom</string>+ <string name="scheduled_field_prompt">Ce que Gotcha doit faire</string>+ <string name="scheduled_field_when">Première exécution</string>+ <string name="scheduled_field_repeat">Répéter</string>+ <string name="scheduled_repeat_none">Une fois</string>+ <string name="scheduled_repeat_hourly">Toutes les quelques heures</string>+ <string name="scheduled_repeat_daily">Tous les quelques jours</string>+ <string name="scheduled_repeat_weekly">Chaque semaine</string>+ <string name="scheduled_repeat_monthly">Chaque mois</string>+ <string name="scheduled_field_every_hours">Toutes les combien d’heures</string>+ <string name="scheduled_field_every_days">Tous les combien de jours</string>+ <string name="scheduled_field_mode">Mode</string>+ <string name="scheduled_mode_hint">Monitor peut seulement regarder et rendre compte. Operator peut agir sur votre téléphone, sans personne pour surveiller : ne le choisissez que si la tâche en a besoin.</string>+ <string name="scheduled_field_persona">Persona</string>+ <string name="scheduled_persona_none">Aucune</string>+ <string name="scheduled_field_target">Où elle s’exécute</string>+ <string name="scheduled_same_chat_hint">Chaque exécution s’ajoute à ce chat, pour que Gotcha voie les précédentes.</string>+ <string name="scheduled_chat_first_run">Un nouveau chat, gardé pour les suivantes</string>+ <string name="scheduled_field_files">Fichiers envoyés avec le prompt</string>+ <string name="scheduled_add_files">Ajouter des fichiers</string>+ <string name="scheduled_remove_file">Retirer</string>+ <string name="scheduled_field_retries">Si une exécution échoue</string>+ <string name="scheduled_unattended_hint">Une exécution qui attend votre réponse patiente deux minutes, puis continue comme si vous aviez dit non.</string>+ <string name="scheduled_file_unreadable">Certains fichiers n’ont pas pu être lus et ont été laissés de côté.</string>+ <string name="scheduled_too_many_files">Une tâche peut emporter %1$d fichiers au plus.</string>+ <string name="scheduled_error_name">Donnez un nom à la tâche.</string>+ <string name="scheduled_error_prompt">Indiquez ce que Gotcha doit faire.</string>+ <string name="scheduled_error_past">Cette heure est passée. Choisissez-en une plus tard, ou une répétition.</string>+ <string name="scheduled_error_interval">Utilisez un nombre de 1 à %1$d.</string>+ <string name="scheduled_error_too_much_text">Ces documents contiennent trop de texte pour une seule tâche. Retirez-en quelques-uns.</string>+ <string name="scheduled_schedule_every_hour">Toutes les heures</string>+ <string name="scheduled_schedule_every_day">Chaque jour à %1$s</string>+ <string name="scheduled_schedule_once">Une fois, %1$s</string>+ <string name="scheduled_schedule_weekly">Chaque %1$s à %2$s</string>+ <string name="scheduled_schedule_monthly">Chaque mois le %1$d à %2$s</string>+ <string name="scheduled_status_done">Terminée</string>+ <string name="scheduled_status_failed">Échec</string>+ <string name="scheduled_status_stopped">Arrêtée</string>+ <string name="scheduled_status_missed">Manquée : le téléphone était éteint ou en veille</string>+ <string name="scheduled_status_skipped_busy">Sautée : Gotcha était occupé</string>+ <string name="scheduled_status_needs_tap">En attente d’un appui</string>+ <string name="scheduled_status_not_started">Impossible de lancer</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="one">Toutes les %1$d heures</item>+ <item quantity="many">Toutes les %1$d heures</item>+ <item quantity="other">Toutes les %1$d heures</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="one">Tous les %1$d jours à %2$s</item>+ <item quantity="many">Tous les %1$d jours à %2$s</item>+ <item quantity="other">Tous les %1$d jours à %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="one">Réessayer %1$d fois</item>+ <item quantity="many">Réessayer %1$d fois</item>+ <item quantity="other">Réessayer %1$d fois</item>+ </plurals></resources>diff --git a/app/src/main/res/values-hi/strings.xml b/app/src/main/res/values-hi/strings.xmlindex fceba37..b34bf4c 100644--- a/app/src/main/res/values-hi/strings.xml+++ b/app/src/main/res/values-hi/strings.xml@@ -1464,4 +1464,93 @@<string name="mcp_error_rpc">सर्वर ने एक त्रुटि लौटाई: %1$s</string><string name="mcp_error_network">सर्वर तक नहीं पहुँच सके: %1$s</string><string name="mcp_error_bad_token">टोकन और हेडर की वैल्यू में सिर्फ़ सामान्य ASCII अक्षर हो सकते हैं।</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">शेड्यूल किए गए काम</string>+ <string name="channel_scheduled_tasks_description">शेड्यूल किया गया काम, जिसे चलाने के लिए टैप चाहिए</string>+ <string name="scheduled_needs_tap_title">“%1$s” का समय हो गया</string>+ <string name="scheduled_needs_tap_body">अभी चलाने के लिए टैप करें। काम अपने-आप चलें, इसके लिए Gotcha को अलार्म और रिमाइंडर सेट करने की अनुमति दें।</string>+ <string name="scheduled_needs_tap_public_title">एक शेड्यूल किए गए काम का समय हो गया</string>+ <string name="scheduled_task_gone">यह काम अब मौजूद नहीं है।</string>+ <string name="scheduled_task_files_missing">इस काम के साथ सहेजी गई फ़ाइलें अब पढ़ी नहीं जा सकतीं। सेटिंग में उन्हें फिर से जोड़ें।</string>+ <string name="scheduled_task_needs_exact_alarms">टैप का इंतज़ार: Gotcha सटीक अलार्म सेट नहीं कर सकता।</string>+ <string name="settings_page_scheduled_tasks">शेड्यूल किए गए काम</string>+ <string name="settings_page_scheduled_tasks_summary">प्रॉम्प्ट जिन्हें Gotcha तय समय पर खुद चलाता है</string>+ <string name="scheduled_intro">आपके चुने समय पर Gotcha खुद को एक प्रॉम्प्ट भेजता है और उस पर किसी भी चैट की तरह काम करता है। नतीजा एक चैट में आता है, और आप ऐप में न हों तो एक सूचना भी।</string>+ <string name="scheduled_empty">अभी कोई शेड्यूल किया गया काम नहीं है। यहाँ जोड़ें, या चैट में Gotcha से कहें, जैसे “हर कार्यदिवस सुबह 8 बजे मेरे बिना पढ़े ईमेल का सार बताओ”।</string>+ <string name="scheduled_add_task">काम जोड़ें</string>+ <string name="scheduled_exact_alarm_hint">Gotcha सटीक अलार्म सेट नहीं कर सकता, इसलिए काम अपने-आप शुरू नहीं हो पाएगा: वह आपसे एक सूचना पर टैप करने को कहेगा।</string>+ <string name="scheduled_exact_alarm_allow">अलार्म और रिमाइंडर की अनुमति दें</string>+ <string name="scheduled_set_up_by_gotcha">Gotcha ने एक चैट में सेट किया</string>+ <string name="scheduled_paused">रोका गया</string>+ <string name="scheduled_no_more_runs">आगे कोई रन नहीं</string>+ <string name="scheduled_next_run">अगला: %1$s</string>+ <string name="scheduled_target_new_chat">हर बार नई चैट</string>+ <string name="scheduled_target_same_chat">हर बार वही चैट</string>+ <string name="scheduled_last_run">पिछला: %1$s, %2$s</string>+ <string name="scheduled_edit">बदलें</string>+ <string name="scheduled_run_now">अभी चलाएँ</string>+ <string name="scheduled_run_now_started">शुरू हो गया। यह अपनी चैट में चल रहा है।</string>+ <string name="scheduled_run_now_busy">Gotcha अभी किसी और काम में लगा है। उसके खत्म होने पर फिर कोशिश करें।</string>+ <string name="scheduled_history">इतिहास</string>+ <string name="scheduled_hide_history">इतिहास छिपाएँ</string>+ <string name="scheduled_open_chat">चैट खोलें</string>+ <string name="scheduled_delete">हटाएँ</string>+ <string name="scheduled_delete_title">“%1$s” हटाएँ?</string>+ <string name="scheduled_delete_body">काम और उसका इतिहास हट जाएगा। उसके रन वाली चैट बनी रहेंगी।</string>+ <string name="scheduled_cancel">रद्द करें</string>+ <string name="scheduled_save">सहेजें</string>+ <string name="scheduled_field_name">नाम</string>+ <string name="scheduled_field_prompt">Gotcha को क्या करना है</string>+ <string name="scheduled_field_when">पहला रन</string>+ <string name="scheduled_field_repeat">दोहराएँ</string>+ <string name="scheduled_repeat_none">एक बार</string>+ <string name="scheduled_repeat_hourly">कुछ घंटों में</string>+ <string name="scheduled_repeat_daily">कुछ दिनों में</string>+ <string name="scheduled_repeat_weekly">हर हफ़्ते</string>+ <string name="scheduled_repeat_monthly">हर महीने</string>+ <string name="scheduled_field_every_hours">हर कितने घंटे में</string>+ <string name="scheduled_field_every_days">हर कितने दिन में</string>+ <string name="scheduled_field_mode">मोड</string>+ <string name="scheduled_mode_hint">Monitor सिर्फ़ देख और बता सकता है। Operator आपके फ़ोन पर काम कर सकता है, बिना किसी के देखे: इसे सिर्फ़ उसी काम के लिए चुनें जिसे इसकी ज़रूरत हो।</string>+ <string name="scheduled_field_persona">पर्सोना</string>+ <string name="scheduled_persona_none">कोई नहीं</string>+ <string name="scheduled_field_target">कहाँ चलेगा</string>+ <string name="scheduled_same_chat_hint">हर रन इसी चैट में जुड़ता है, ताकि Gotcha पिछले रन देख सके।</string>+ <string name="scheduled_chat_first_run">नई चैट, जो अगले रन के लिए रखी जाएगी</string>+ <string name="scheduled_field_files">प्रॉम्प्ट के साथ भेजी जाने वाली फ़ाइलें</string>+ <string name="scheduled_add_files">फ़ाइलें जोड़ें</string>+ <string name="scheduled_remove_file">हटाएँ</string>+ <string name="scheduled_field_retries">अगर कोई रन विफल हो</string>+ <string name="scheduled_unattended_hint">जिस रन को आपके जवाब की ज़रूरत हो, वह दो मिनट इंतज़ार करता है, फिर ऐसे आगे बढ़ता है जैसे आपने मना किया हो।</string>+ <string name="scheduled_file_unreadable">कुछ फ़ाइलें पढ़ी नहीं जा सकीं और छोड़ दी गईं।</string>+ <string name="scheduled_too_many_files">एक काम के साथ ज़्यादा से ज़्यादा %1$d फ़ाइलें जा सकती हैं।</string>+ <string name="scheduled_error_name">काम को एक नाम दें।</string>+ <string name="scheduled_error_prompt">बताएँ कि Gotcha को क्या करना है।</string>+ <string name="scheduled_error_past">वह समय बीत चुका है। बाद का समय चुनें, या दोहराना।</string>+ <string name="scheduled_error_interval">1 से %1$d तक की कोई संख्या डालें।</string>+ <string name="scheduled_error_too_much_text">इन दस्तावेज़ों में एक काम के लिए बहुत ज़्यादा टेक्स्ट है। कुछ हटाएँ।</string>+ <string name="scheduled_schedule_every_hour">हर घंटे</string>+ <string name="scheduled_schedule_every_day">हर दिन %1$s बजे</string>+ <string name="scheduled_schedule_once">एक बार, %1$s</string>+ <string name="scheduled_schedule_weekly">हर %1$s को %2$s बजे</string>+ <string name="scheduled_schedule_monthly">हर महीने की %1$d तारीख को %2$s बजे</string>+ <string name="scheduled_status_done">हो गया</string>+ <string name="scheduled_status_failed">विफल</string>+ <string name="scheduled_status_stopped">रोका गया</string>+ <string name="scheduled_status_missed">छूट गया: फ़ोन बंद था या स्लीप में था</string>+ <string name="scheduled_status_skipped_busy">छोड़ा गया: Gotcha व्यस्त था</string>+ <string name="scheduled_status_needs_tap">टैप का इंतज़ार</string>+ <string name="scheduled_status_not_started">शुरू नहीं हो सका</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="one">हर %1$d घंटे में</item>+ <item quantity="other">हर %1$d घंटे में</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="one">हर %1$d दिन में %2$s बजे</item>+ <item quantity="other">हर %1$d दिन में %2$s बजे</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="one">%1$d बार फिर कोशिश करें</item>+ <item quantity="other">%1$d बार फिर कोशिश करें</item>+ </plurals></resources>diff --git a/app/src/main/res/values-it/strings.xml b/app/src/main/res/values-it/strings.xmlindex 236b536..8c4fe2d 100644--- a/app/src/main/res/values-it/strings.xml+++ b/app/src/main/res/values-it/strings.xml@@ -1483,4 +1483,96 @@<string name="mcp_error_rpc">Il server ha restituito un errore: %1$s</string><string name="mcp_error_network">Impossibile raggiungere il server: %1$s</string><string name="mcp_error_bad_token">Il token e i valori delle intestazioni possono contenere solo caratteri ASCII semplici.</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">Attività pianificate</string>+ <string name="channel_scheduled_tasks_description">Un’attività pianificata che aspetta un tocco per partire</string>+ <string name="scheduled_needs_tap_title">È ora di «%1$s»</string>+ <string name="scheduled_needs_tap_body">Tocca per eseguirla ora. Perché le attività partano da sole, consenti a Gotcha di impostare sveglie e promemoria.</string>+ <string name="scheduled_needs_tap_public_title">È ora di un’attività pianificata</string>+ <string name="scheduled_task_gone">Questa attività non esiste più.</string>+ <string name="scheduled_task_files_missing">I file salvati con questa attività non si possono più leggere. Aggiungili di nuovo nelle Impostazioni.</string>+ <string name="scheduled_task_needs_exact_alarms">In attesa di un tocco: Gotcha non può impostare sveglie esatte.</string>+ <string name="settings_page_scheduled_tasks">Attività pianificate</string>+ <string name="settings_page_scheduled_tasks_summary">Prompt che Gotcha esegue da solo a orari fissi</string>+ <string name="scheduled_intro">All’ora che imposti, Gotcha si manda un prompt e ci lavora come in qualsiasi chat. Il risultato arriva in una chat, con una notifica se non sei nell’app.</string>+ <string name="scheduled_empty">Ancora nessuna attività pianificata. Aggiungine una qui o chiedilo a Gotcha in una chat, ad es. «ogni giorno feriale alle 8, riassumi le mie email non lette».</string>+ <string name="scheduled_add_task">Aggiungi un’attività</string>+ <string name="scheduled_exact_alarm_hint">Gotcha non può impostare sveglie esatte, quindi un’attività non può partire da sola: ti chiederà di toccare una notifica.</string>+ <string name="scheduled_exact_alarm_allow">Consenti sveglie e promemoria</string>+ <string name="scheduled_set_up_by_gotcha">Creata da Gotcha in una chat</string>+ <string name="scheduled_paused">In pausa</string>+ <string name="scheduled_no_more_runs">Nessun’altra esecuzione</string>+ <string name="scheduled_next_run">Prossima: %1$s</string>+ <string name="scheduled_target_new_chat">Una nuova chat ogni volta</string>+ <string name="scheduled_target_same_chat">La stessa chat ogni volta</string>+ <string name="scheduled_last_run">Ultima: %1$s, %2$s</string>+ <string name="scheduled_edit">Modifica</string>+ <string name="scheduled_run_now">Esegui ora</string>+ <string name="scheduled_run_now_started">Avviata. È in esecuzione nella sua chat.</string>+ <string name="scheduled_run_now_busy">Gotcha è occupato con un’altra attività. Riprova quando finisce.</string>+ <string name="scheduled_history">Cronologia</string>+ <string name="scheduled_hide_history">Nascondi cronologia</string>+ <string name="scheduled_open_chat">Apri chat</string>+ <string name="scheduled_delete">Elimina</string>+ <string name="scheduled_delete_title">Eliminare «%1$s»?</string>+ <string name="scheduled_delete_body">L’attività e la sua cronologia vengono rimosse. Le chat delle sue esecuzioni restano.</string>+ <string name="scheduled_cancel">Annulla</string>+ <string name="scheduled_save">Salva</string>+ <string name="scheduled_field_name">Nome</string>+ <string name="scheduled_field_prompt">Cosa deve fare Gotcha</string>+ <string name="scheduled_field_when">Prima esecuzione</string>+ <string name="scheduled_field_repeat">Ripeti</string>+ <string name="scheduled_repeat_none">Una volta</string>+ <string name="scheduled_repeat_hourly">Ogni qualche ora</string>+ <string name="scheduled_repeat_daily">Ogni qualche giorno</string>+ <string name="scheduled_repeat_weekly">Ogni settimana</string>+ <string name="scheduled_repeat_monthly">Ogni mese</string>+ <string name="scheduled_field_every_hours">Ogni quante ore</string>+ <string name="scheduled_field_every_days">Ogni quanti giorni</string>+ <string name="scheduled_field_mode">Modalità</string>+ <string name="scheduled_mode_hint">Monitor può solo guardare e riferire. Operator può agire sul tuo telefono senza nessuno che controlli: sceglilo solo per le attività che ne hanno bisogno.</string>+ <string name="scheduled_field_persona">Persona</string>+ <string name="scheduled_persona_none">Nessuna</string>+ <string name="scheduled_field_target">Dove viene eseguita</string>+ <string name="scheduled_same_chat_hint">Ogni esecuzione si aggiunge a questa chat, così Gotcha vede quelle precedenti.</string>+ <string name="scheduled_chat_first_run">Una nuova chat, tenuta per le prossime</string>+ <string name="scheduled_field_files">File inviati con il prompt</string>+ <string name="scheduled_add_files">Aggiungi file</string>+ <string name="scheduled_remove_file">Rimuovi</string>+ <string name="scheduled_field_retries">Se un’esecuzione non riesce</string>+ <string name="scheduled_unattended_hint">Un’esecuzione che ha bisogno della tua risposta la aspetta due minuti, poi va avanti come se avessi detto di no.</string>+ <string name="scheduled_file_unreadable">Alcuni file non si potevano leggere e sono stati esclusi.</string>+ <string name="scheduled_too_many_files">Un’attività può portare al massimo %1$d file.</string>+ <string name="scheduled_error_name">Dai un nome all’attività.</string>+ <string name="scheduled_error_prompt">Di’ cosa deve fare Gotcha.</string>+ <string name="scheduled_error_past">Quell’ora è passata. Scegline una più tardi o una ripetizione.</string>+ <string name="scheduled_error_interval">Usa un numero da 1 a %1$d.</string>+ <string name="scheduled_error_too_much_text">Questi documenti contengono troppo testo per un’attività. Togline qualcuno.</string>+ <string name="scheduled_schedule_every_hour">Ogni ora</string>+ <string name="scheduled_schedule_every_day">Ogni giorno alle %1$s</string>+ <string name="scheduled_schedule_once">Una volta, %1$s</string>+ <string name="scheduled_schedule_weekly">Ogni %1$s alle %2$s</string>+ <string name="scheduled_schedule_monthly">Ogni mese il giorno %1$d alle %2$s</string>+ <string name="scheduled_status_done">Fatta</string>+ <string name="scheduled_status_failed">Non riuscita</string>+ <string name="scheduled_status_stopped">Interrotta</string>+ <string name="scheduled_status_missed">Persa: il telefono era spento o in standby</string>+ <string name="scheduled_status_skipped_busy">Saltata: Gotcha era occupato</string>+ <string name="scheduled_status_needs_tap">In attesa di un tocco</string>+ <string name="scheduled_status_not_started">Impossibile avviare</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="one">Ogni %1$d ore</item>+ <item quantity="many">Ogni %1$d ore</item>+ <item quantity="other">Ogni %1$d ore</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="one">Ogni %1$d giorni alle %2$s</item>+ <item quantity="many">Ogni %1$d giorni alle %2$s</item>+ <item quantity="other">Ogni %1$d giorni alle %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="one">Riprova %1$d volta</item>+ <item quantity="many">Riprova %1$d volte</item>+ <item quantity="other">Riprova %1$d volte</item>+ </plurals></resources>diff --git a/app/src/main/res/values-ja/strings.xml b/app/src/main/res/values-ja/strings.xmlindex 913ebf8..ba663e7 100644--- a/app/src/main/res/values-ja/strings.xml+++ b/app/src/main/res/values-ja/strings.xml@@ -1444,4 +1444,90 @@<string name="mcp_error_rpc">サーバーがエラーを返しました:%1$s</string><string name="mcp_error_network">サーバーに接続できません:%1$s</string><string name="mcp_error_bad_token">トークンとヘッダーの値には半角の ASCII 文字しか使えません。</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">スケジュールしたタスク</string>+ <string name="channel_scheduled_tasks_description">実行にタップが必要なスケジュールしたタスク</string>+ <string name="scheduled_needs_tap_title">「%1$s」の時間です</string>+ <string name="scheduled_needs_tap_body">タップすると今すぐ実行します。タスクを自動で実行するには、Gotcha にアラームとリマインダーの設定を許可してください。</string>+ <string name="scheduled_needs_tap_public_title">スケジュールしたタスクの時間です</string>+ <string name="scheduled_task_gone">このタスクはもうありません。</string>+ <string name="scheduled_task_files_missing">このタスクに保存したファイルを読み込めなくなりました。設定でもう一度追加してください。</string>+ <string name="scheduled_task_needs_exact_alarms">タップ待ち:Gotcha は正確なアラームを設定できません。</string>+ <string name="settings_page_scheduled_tasks">スケジュールしたタスク</string>+ <string name="settings_page_scheduled_tasks_summary">決めた時刻に Gotcha が自分で実行するプロンプト</string>+ <string name="scheduled_intro">設定した時刻に Gotcha が自分宛てにプロンプトを送り、通常のチャットと同じように取り組みます。結果はチャットに届き、アプリを離れているときは通知も届きます。</string>+ <string name="scheduled_empty">スケジュールしたタスクはまだありません。ここで追加するか、チャットで Gotcha に頼んでください(例:「平日の8時に未読メールを要約して」)。</string>+ <string name="scheduled_add_task">タスクを追加</string>+ <string name="scheduled_exact_alarm_hint">Gotcha は正確なアラームを設定できないため、タスクは自動で始められません。代わりに通知をタップするよう求めます。</string>+ <string name="scheduled_exact_alarm_allow">アラームとリマインダーを許可</string>+ <string name="scheduled_set_up_by_gotcha">Gotcha がチャットで設定</string>+ <string name="scheduled_paused">一時停止中</string>+ <string name="scheduled_no_more_runs">今後の実行なし</string>+ <string name="scheduled_next_run">次回:%1$s</string>+ <string name="scheduled_target_new_chat">毎回新しいチャット</string>+ <string name="scheduled_target_same_chat">毎回同じチャット</string>+ <string name="scheduled_last_run">前回:%1$s、%2$s</string>+ <string name="scheduled_edit">編集</string>+ <string name="scheduled_run_now">今すぐ実行</string>+ <string name="scheduled_run_now_started">開始しました。専用のチャットで実行中です。</string>+ <string name="scheduled_run_now_busy">Gotcha は別のタスクを実行中です。終わってからもう一度お試しください。</string>+ <string name="scheduled_history">履歴</string>+ <string name="scheduled_hide_history">履歴を隠す</string>+ <string name="scheduled_open_chat">チャットを開く</string>+ <string name="scheduled_delete">削除</string>+ <string name="scheduled_delete_title">「%1$s」を削除しますか?</string>+ <string name="scheduled_delete_body">タスクとその履歴が削除されます。実行したチャットは残ります。</string>+ <string name="scheduled_cancel">キャンセル</string>+ <string name="scheduled_save">保存</string>+ <string name="scheduled_field_name">名前</string>+ <string name="scheduled_field_prompt">Gotcha にしてほしいこと</string>+ <string name="scheduled_field_when">初回の実行</string>+ <string name="scheduled_field_repeat">繰り返し</string>+ <string name="scheduled_repeat_none">1回のみ</string>+ <string name="scheduled_repeat_hourly">数時間ごと</string>+ <string name="scheduled_repeat_daily">数日ごと</string>+ <string name="scheduled_repeat_weekly">毎週</string>+ <string name="scheduled_repeat_monthly">毎月</string>+ <string name="scheduled_field_every_hours">何時間ごと</string>+ <string name="scheduled_field_every_days">何日ごと</string>+ <string name="scheduled_field_mode">モード</string>+ <string name="scheduled_mode_hint">Monitor は見て報告するだけです。Operator は誰も見ていない間にスマートフォンを操作できます。必要なタスクにだけ選んでください。</string>+ <string name="scheduled_field_persona">ペルソナ</string>+ <string name="scheduled_persona_none">なし</string>+ <string name="scheduled_field_target">実行する場所</string>+ <string name="scheduled_same_chat_hint">毎回の実行がこのチャットに追加されるので、Gotcha は以前の実行を参照できます。</string>+ <string name="scheduled_chat_first_run">新しいチャット(以後の実行にも使用)</string>+ <string name="scheduled_field_files">プロンプトと一緒に送るファイル</string>+ <string name="scheduled_add_files">ファイルを追加</string>+ <string name="scheduled_remove_file">削除</string>+ <string name="scheduled_field_retries">実行に失敗したとき</string>+ <string name="scheduled_unattended_hint">あなたの回答が必要な実行は2分間待ち、その後は「いいえ」と答えたものとして続行します。</string>+ <string name="scheduled_file_unreadable">一部のファイルを読み込めなかったため、除外しました。</string>+ <string name="scheduled_too_many_files">1つのタスクに付けられるファイルは最大 %1$d 個です。</string>+ <string name="scheduled_error_name">タスクに名前を付けてください。</string>+ <string name="scheduled_error_prompt">Gotcha にしてほしいことを書いてください。</string>+ <string name="scheduled_error_past">その時刻は過ぎています。後の時刻か繰り返しを選んでください。</string>+ <string name="scheduled_error_interval">1〜%1$d の数字を入力してください。</string>+ <string name="scheduled_error_too_much_text">これらの文書はテキストが多すぎて1つのタスクに収まりません。いくつか外してください。</string>+ <string name="scheduled_schedule_every_hour">1時間ごと</string>+ <string name="scheduled_schedule_every_day">毎日 %1$s</string>+ <string name="scheduled_schedule_once">1回のみ、%1$s</string>+ <string name="scheduled_schedule_weekly">毎週%1$s %2$s</string>+ <string name="scheduled_schedule_monthly">毎月%1$d日 %2$s</string>+ <string name="scheduled_status_done">完了</string>+ <string name="scheduled_status_failed">失敗</string>+ <string name="scheduled_status_stopped">停止</string>+ <string name="scheduled_status_missed">未実行:スマートフォンの電源が切れているかスリープ中でした</string>+ <string name="scheduled_status_skipped_busy">スキップ:Gotcha が別の作業中でした</string>+ <string name="scheduled_status_needs_tap">タップ待ち</string>+ <string name="scheduled_status_not_started">開始できませんでした</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="other">%1$d時間ごと</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="other">%1$d日ごと %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="other">%1$d回再試行</item>+ </plurals></resources>diff --git a/app/src/main/res/values-pt-rBR/strings.xml b/app/src/main/res/values-pt-rBR/strings.xmlindex a4d4515..673dba9 100644--- a/app/src/main/res/values-pt-rBR/strings.xml+++ b/app/src/main/res/values-pt-rBR/strings.xml@@ -1483,4 +1483,96 @@<string name="mcp_error_rpc">O servidor retornou um erro: %1$s</string><string name="mcp_error_network">Não foi possível acessar o servidor: %1$s</string><string name="mcp_error_bad_token">O token e os valores dos cabeçalhos só podem conter caracteres ASCII simples.</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">Tarefas agendadas</string>+ <string name="channel_scheduled_tasks_description">Uma tarefa agendada que precisa de um toque para rodar</string>+ <string name="scheduled_needs_tap_title">Hora de “%1$s”</string>+ <string name="scheduled_needs_tap_body">Toque para rodar agora. Para as tarefas rodarem sozinhas, permita que o Gotcha defina alarmes e lembretes.</string>+ <string name="scheduled_needs_tap_public_title">Hora de uma tarefa agendada</string>+ <string name="scheduled_task_gone">Esta tarefa não existe mais.</string>+ <string name="scheduled_task_files_missing">Os arquivos salvos com esta tarefa não podem mais ser lidos. Adicione-os de novo nas Configurações.</string>+ <string name="scheduled_task_needs_exact_alarms">Aguardando um toque: o Gotcha não pode definir alarmes exatos.</string>+ <string name="settings_page_scheduled_tasks">Tarefas agendadas</string>+ <string name="settings_page_scheduled_tasks_summary">Prompts que o Gotcha roda sozinho em horários definidos</string>+ <string name="scheduled_intro">No horário que você definir, o Gotcha manda um prompt para si mesmo e trabalha nele como em qualquer chat. O resultado chega em um chat, com uma notificação se você estiver fora do app.</string>+ <string name="scheduled_empty">Nenhuma tarefa agendada ainda. Adicione uma aqui ou peça ao Gotcha em um chat, por ex. “todo dia útil às 8, resuma meus e-mails não lidos”.</string>+ <string name="scheduled_add_task">Adicionar uma tarefa</string>+ <string name="scheduled_exact_alarm_hint">O Gotcha não pode definir alarmes exatos, então uma tarefa não consegue começar sozinha: ela vai pedir que você toque em uma notificação.</string>+ <string name="scheduled_exact_alarm_allow">Permitir alarmes e lembretes</string>+ <string name="scheduled_set_up_by_gotcha">Criada pelo Gotcha em um chat</string>+ <string name="scheduled_paused">Pausada</string>+ <string name="scheduled_no_more_runs">Sem mais execuções</string>+ <string name="scheduled_next_run">Próxima: %1$s</string>+ <string name="scheduled_target_new_chat">Um chat novo a cada vez</string>+ <string name="scheduled_target_same_chat">O mesmo chat a cada vez</string>+ <string name="scheduled_last_run">Última: %1$s, %2$s</string>+ <string name="scheduled_edit">Editar</string>+ <string name="scheduled_run_now">Rodar agora</string>+ <string name="scheduled_run_now_started">Iniciada. Está rodando no chat dela.</string>+ <string name="scheduled_run_now_busy">O Gotcha está ocupado com outra tarefa. Tente de novo quando ela terminar.</string>+ <string name="scheduled_history">Histórico</string>+ <string name="scheduled_hide_history">Ocultar histórico</string>+ <string name="scheduled_open_chat">Abrir chat</string>+ <string name="scheduled_delete">Excluir</string>+ <string name="scheduled_delete_title">Excluir “%1$s”?</string>+ <string name="scheduled_delete_body">A tarefa e o histórico dela são removidos. Os chats das execuções são mantidos.</string>+ <string name="scheduled_cancel">Cancelar</string>+ <string name="scheduled_save">Salvar</string>+ <string name="scheduled_field_name">Nome</string>+ <string name="scheduled_field_prompt">O que o Gotcha deve fazer</string>+ <string name="scheduled_field_when">Primeira execução</string>+ <string name="scheduled_field_repeat">Repetir</string>+ <string name="scheduled_repeat_none">Uma vez</string>+ <string name="scheduled_repeat_hourly">A cada algumas horas</string>+ <string name="scheduled_repeat_daily">A cada alguns dias</string>+ <string name="scheduled_repeat_weekly">Toda semana</string>+ <string name="scheduled_repeat_monthly">Todo mês</string>+ <string name="scheduled_field_every_hours">A cada quantas horas</string>+ <string name="scheduled_field_every_days">A cada quantos dias</string>+ <string name="scheduled_field_mode">Modo</string>+ <string name="scheduled_mode_hint">O Monitor só pode olhar e relatar. O Operator pode agir no seu celular sem ninguém acompanhando: escolha-o só para tarefas que precisem dele.</string>+ <string name="scheduled_field_persona">Persona</string>+ <string name="scheduled_persona_none">Nenhuma</string>+ <string name="scheduled_field_target">Onde roda</string>+ <string name="scheduled_same_chat_hint">Cada execução é adicionada a este chat, assim o Gotcha vê as anteriores.</string>+ <string name="scheduled_chat_first_run">Um chat novo, mantido para as próximas</string>+ <string name="scheduled_field_files">Arquivos enviados com o prompt</string>+ <string name="scheduled_add_files">Adicionar arquivos</string>+ <string name="scheduled_remove_file">Remover</string>+ <string name="scheduled_field_retries">Se uma execução falhar</string>+ <string name="scheduled_unattended_hint">Uma execução que precisa da sua resposta espera dois minutos e depois segue como se você tivesse dito não.</string>+ <string name="scheduled_file_unreadable">Alguns arquivos não puderam ser lidos e ficaram de fora.</string>+ <string name="scheduled_too_many_files">Uma tarefa pode levar no máximo %1$d arquivos.</string>+ <string name="scheduled_error_name">Dê um nome à tarefa.</string>+ <string name="scheduled_error_prompt">Diga o que o Gotcha deve fazer.</string>+ <string name="scheduled_error_past">Esse horário já passou. Escolha um mais tarde ou uma repetição.</string>+ <string name="scheduled_error_interval">Use um número de 1 a %1$d.</string>+ <string name="scheduled_error_too_much_text">Esses documentos têm texto demais para uma tarefa. Remova alguns.</string>+ <string name="scheduled_schedule_every_hour">A cada hora</string>+ <string name="scheduled_schedule_every_day">Todo dia às %1$s</string>+ <string name="scheduled_schedule_once">Uma vez, %1$s</string>+ <string name="scheduled_schedule_weekly">Toda %1$s às %2$s</string>+ <string name="scheduled_schedule_monthly">Todo mês no dia %1$d às %2$s</string>+ <string name="scheduled_status_done">Concluída</string>+ <string name="scheduled_status_failed">Falhou</string>+ <string name="scheduled_status_stopped">Parada</string>+ <string name="scheduled_status_missed">Perdida: o celular estava desligado ou em repouso</string>+ <string name="scheduled_status_skipped_busy">Pulada: o Gotcha estava ocupado</string>+ <string name="scheduled_status_needs_tap">Aguardando um toque</string>+ <string name="scheduled_status_not_started">Não foi possível iniciar</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="one">A cada %1$d horas</item>+ <item quantity="many">A cada %1$d horas</item>+ <item quantity="other">A cada %1$d horas</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="one">A cada %1$d dias às %2$s</item>+ <item quantity="many">A cada %1$d dias às %2$s</item>+ <item quantity="other">A cada %1$d dias às %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="one">Tentar de novo %1$d vez</item>+ <item quantity="many">Tentar de novo %1$d vezes</item>+ <item quantity="other">Tentar de novo %1$d vezes</item>+ </plurals></resources>diff --git a/app/src/main/res/values-zh-rCN/strings.xml b/app/src/main/res/values-zh-rCN/strings.xmlindex 5dbd70e..6b05f91 100644--- a/app/src/main/res/values-zh-rCN/strings.xml+++ b/app/src/main/res/values-zh-rCN/strings.xml@@ -1444,4 +1444,90 @@<string name="mcp_error_rpc">服务器返回了错误:%1$s</string><string name="mcp_error_network">无法连接到服务器:%1$s</string><string name="mcp_error_bad_token">令牌和请求头的值只能包含普通 ASCII 字符。</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">定时任务</string>+ <string name="channel_scheduled_tasks_description">需要点按才能运行的定时任务</string>+ <string name="scheduled_needs_tap_title">“%1$s”到时间了</string>+ <string name="scheduled_needs_tap_body">点按即可立即运行。要让任务自动运行,请允许 Gotcha 设置闹钟和提醒。</string>+ <string name="scheduled_needs_tap_public_title">有一个定时任务到时间了</string>+ <string name="scheduled_task_gone">此任务已不存在。</string>+ <string name="scheduled_task_files_missing">随此任务保存的文件已无法读取。请在设置中重新添加。</string>+ <string name="scheduled_task_needs_exact_alarms">等待点按:Gotcha 无法设置精确闹钟。</string>+ <string name="settings_page_scheduled_tasks">定时任务</string>+ <string name="settings_page_scheduled_tasks_summary">Gotcha 在设定时间自行运行的提示词</string>+ <string name="scheduled_intro">到了你设定的时间,Gotcha 会给自己发送一条提示词,并像处理任何聊天一样完成它。结果会出现在一个聊天里;你不在应用中时还会收到通知。</string>+ <string name="scheduled_empty">还没有定时任务。可以在这里添加,或在聊天中告诉 Gotcha,例如“每个工作日早上 8 点总结我的未读邮件”。</string>+ <string name="scheduled_add_task">添加任务</string>+ <string name="scheduled_exact_alarm_hint">Gotcha 无法设置精确闹钟,所以任务无法自行开始:它会请你点按一条通知。</string>+ <string name="scheduled_exact_alarm_allow">允许闹钟和提醒</string>+ <string name="scheduled_set_up_by_gotcha">由 Gotcha 在聊天中设置</string>+ <string name="scheduled_paused">已暂停</string>+ <string name="scheduled_no_more_runs">没有后续运行</string>+ <string name="scheduled_next_run">下次:%1$s</string>+ <string name="scheduled_target_new_chat">每次新建聊天</string>+ <string name="scheduled_target_same_chat">每次使用同一聊天</string>+ <string name="scheduled_last_run">上次:%1$s,%2$s</string>+ <string name="scheduled_edit">编辑</string>+ <string name="scheduled_run_now">立即运行</string>+ <string name="scheduled_run_now_started">已开始,正在其聊天中运行。</string>+ <string name="scheduled_run_now_busy">Gotcha 正在处理另一个任务。等它结束后再试。</string>+ <string name="scheduled_history">历史记录</string>+ <string name="scheduled_hide_history">隐藏历史记录</string>+ <string name="scheduled_open_chat">打开聊天</string>+ <string name="scheduled_delete">删除</string>+ <string name="scheduled_delete_title">删除“%1$s”?</string>+ <string name="scheduled_delete_body">任务及其历史记录将被删除。它运行过的聊天会保留。</string>+ <string name="scheduled_cancel">取消</string>+ <string name="scheduled_save">保存</string>+ <string name="scheduled_field_name">名称</string>+ <string name="scheduled_field_prompt">Gotcha 要做什么</string>+ <string name="scheduled_field_when">首次运行</string>+ <string name="scheduled_field_repeat">重复</string>+ <string name="scheduled_repeat_none">仅一次</string>+ <string name="scheduled_repeat_hourly">每隔几小时</string>+ <string name="scheduled_repeat_daily">每隔几天</string>+ <string name="scheduled_repeat_weekly">每周</string>+ <string name="scheduled_repeat_monthly">每月</string>+ <string name="scheduled_field_every_hours">每隔几小时</string>+ <string name="scheduled_field_every_days">每隔几天</string>+ <string name="scheduled_field_mode">模式</string>+ <string name="scheduled_mode_hint">Monitor 只能查看和汇报。Operator 能在无人看着时操作你的手机:只为确实需要的任务选择它。</string>+ <string name="scheduled_field_persona">角色</string>+ <string name="scheduled_persona_none">无</string>+ <string name="scheduled_field_target">在哪里运行</string>+ <string name="scheduled_same_chat_hint">每次运行都会添加到这个聊天中,Gotcha 能看到之前的运行。</string>+ <string name="scheduled_chat_first_run">新建聊天,并留给之后的运行</string>+ <string name="scheduled_field_files">随提示词发送的文件</string>+ <string name="scheduled_add_files">添加文件</string>+ <string name="scheduled_remove_file">移除</string>+ <string name="scheduled_field_retries">运行失败时</string>+ <string name="scheduled_unattended_hint">需要你回答的运行会等待两分钟,之后按你拒绝来继续。</string>+ <string name="scheduled_file_unreadable">部分文件无法读取,已略过。</string>+ <string name="scheduled_too_many_files">一个任务最多可附带 %1$d 个文件。</string>+ <string name="scheduled_error_name">请为任务命名。</string>+ <string name="scheduled_error_prompt">请说明 Gotcha 要做什么。</string>+ <string name="scheduled_error_past">该时间已过。请选择更晚的时间,或设置重复。</string>+ <string name="scheduled_error_interval">请输入 1 到 %1$d 之间的数字。</string>+ <string name="scheduled_error_too_much_text">这些文档的文字太多,一个任务放不下。请移除一些。</string>+ <string name="scheduled_schedule_every_hour">每小时</string>+ <string name="scheduled_schedule_every_day">每天 %1$s</string>+ <string name="scheduled_schedule_once">仅一次,%1$s</string>+ <string name="scheduled_schedule_weekly">每%1$s %2$s</string>+ <string name="scheduled_schedule_monthly">每月 %1$d 日 %2$s</string>+ <string name="scheduled_status_done">已完成</string>+ <string name="scheduled_status_failed">失败</string>+ <string name="scheduled_status_stopped">已停止</string>+ <string name="scheduled_status_missed">已错过:手机当时关机或处于休眠</string>+ <string name="scheduled_status_skipped_busy">已跳过:Gotcha 当时正忙</string>+ <string name="scheduled_status_needs_tap">等待点按</string>+ <string name="scheduled_status_not_started">无法开始</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="other">每 %1$d 小时</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="other">每 %1$d 天 %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="other">重试 %1$d 次</item>+ </plurals></resources>diff --git a/app/src/main/res/values/strings.xml b/app/src/main/res/values/strings.xmlindex 408ff31..1e50023 100644--- a/app/src/main/res/values/strings.xml+++ b/app/src/main/res/values/strings.xml@@ -1691,4 +1691,93 @@<string name="mcp_error_rpc">The server returned an error: %1$s</string><string name="mcp_error_network">Couldn\'t reach the server: %1$s</string><string name="mcp_error_bad_token">The token and header values can only contain plain ASCII characters.</string>+ <!-- Scheduled tasks (issue #132) -->+ <string name="channel_scheduled_tasks">Scheduled tasks</string>+ <string name="channel_scheduled_tasks_description">A scheduled task that needs a tap to run</string>+ <string name="scheduled_needs_tap_title">“%1$s” is due</string>+ <string name="scheduled_needs_tap_body">Tap to run it now. To have tasks run on their own, allow Gotcha to set alarms and reminders.</string>+ <string name="scheduled_needs_tap_public_title">A scheduled task is due</string>+ <string name="scheduled_task_gone">This task no longer exists.</string>+ <string name="scheduled_task_files_missing">The files saved with this task can\'t be read any more. Add them again in Settings.</string>+ <string name="scheduled_task_needs_exact_alarms">Waiting for a tap: Gotcha may not set exact alarms.</string>+ <string name="settings_page_scheduled_tasks">Scheduled tasks</string>+ <string name="settings_page_scheduled_tasks_summary">Prompts Gotcha runs by itself at set times</string>+ <string name="scheduled_intro">Gotcha sends itself a prompt at the time you set and works on it like any chat. The result lands in a chat, with a notification when you\'re away.</string>+ <string name="scheduled_empty">No scheduled tasks yet. Add one here, or ask Gotcha in a chat, e.g. “every weekday at 8, summarise my unread mail”.</string>+ <string name="scheduled_add_task">Add a task</string>+ <string name="scheduled_exact_alarm_hint">Gotcha may not set exact alarms, so a task can\'t start on its own: it will ask you to tap a notification instead.</string>+ <string name="scheduled_exact_alarm_allow">Allow alarms and reminders</string>+ <string name="scheduled_set_up_by_gotcha">Set up by Gotcha in a chat</string>+ <string name="scheduled_paused">Paused</string>+ <string name="scheduled_no_more_runs">No more runs</string>+ <string name="scheduled_next_run">Next: %1$s</string>+ <string name="scheduled_target_new_chat">A new chat each time</string>+ <string name="scheduled_target_same_chat">The same chat each time</string>+ <string name="scheduled_last_run">Last run: %1$s, %2$s</string>+ <string name="scheduled_edit">Edit</string>+ <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_history">History</string>+ <string name="scheduled_hide_history">Hide history</string>+ <string name="scheduled_open_chat">Open chat</string>+ <string name="scheduled_delete">Delete</string>+ <string name="scheduled_delete_title">Delete “%1$s”?</string>+ <string name="scheduled_delete_body">The task and its history are removed. The chats its runs went into are kept.</string>+ <string name="scheduled_cancel">Cancel</string>+ <string name="scheduled_save">Save</string>+ <string name="scheduled_field_name">Name</string>+ <string name="scheduled_field_prompt">What Gotcha should do</string>+ <string name="scheduled_field_when">First run</string>+ <string name="scheduled_field_repeat">Repeat</string>+ <string name="scheduled_repeat_none">Once</string>+ <string name="scheduled_repeat_hourly">Every few hours</string>+ <string name="scheduled_repeat_daily">Every few days</string>+ <string name="scheduled_repeat_weekly">Weekly</string>+ <string name="scheduled_repeat_monthly">Monthly</string>+ <string name="scheduled_field_every_hours">Every how many hours</string>+ <string name="scheduled_field_every_days">Every how many days</string>+ <string name="scheduled_field_mode">Mode</string>+ <string name="scheduled_mode_hint">Monitor can only look and report. Operator can act on your phone, with nobody watching: choose it only for a task that needs it.</string>+ <string name="scheduled_field_persona">Persona</string>+ <string name="scheduled_persona_none">None</string>+ <string name="scheduled_field_target">Where it runs</string>+ <string name="scheduled_same_chat_hint">Each run is added to this chat, so Gotcha sees the earlier runs.</string>+ <string name="scheduled_chat_first_run">A new chat, kept for later runs</string>+ <string name="scheduled_field_files">Files sent with the prompt</string>+ <string name="scheduled_add_files">Add files</string>+ <string name="scheduled_remove_file">Remove</string>+ <string name="scheduled_field_retries">If a run fails</string>+ <string name="scheduled_unattended_hint">A run that needs your answer waits two minutes for it, then goes on as if you said no.</string>+ <string name="scheduled_file_unreadable">Some files couldn\'t be read and were left out.</string>+ <string name="scheduled_too_many_files">At most %1$d files can go with a task.</string>+ <string name="scheduled_error_name">Give the task a name.</string>+ <string name="scheduled_error_prompt">Say what Gotcha should do.</string>+ <string name="scheduled_error_past">That time has passed. Pick a later one, or a repeat.</string>+ <string name="scheduled_error_interval">Use a number from 1 to %1$d.</string>+ <string name="scheduled_error_too_much_text">Those documents hold too much text for one task. Remove some.</string>+ <string name="scheduled_schedule_every_hour">Every hour</string>+ <string name="scheduled_schedule_every_day">Every day at %1$s</string>+ <string name="scheduled_schedule_once">Once, %1$s</string>+ <string name="scheduled_schedule_weekly">Every %1$s at %2$s</string>+ <string name="scheduled_schedule_monthly">Monthly on day %1$d at %2$s</string>+ <string name="scheduled_status_done">Done</string>+ <string name="scheduled_status_failed">Failed</string>+ <string name="scheduled_status_stopped">Stopped</string>+ <string name="scheduled_status_missed">Missed: the phone was off or asleep</string>+ <string name="scheduled_status_skipped_busy">Skipped: Gotcha was busy</string>+ <string name="scheduled_status_needs_tap">Waiting for a tap</string>+ <string name="scheduled_status_not_started">Couldn\'t start</string>+ <plurals name="scheduled_schedule_hours">+ <item quantity="one">Every %1$d hour</item>+ <item quantity="other">Every %1$d hours</item>+ </plurals>+ <plurals name="scheduled_schedule_days">+ <item quantity="one">Every %1$d day at %2$s</item>+ <item quantity="other">Every %1$d days at %2$s</item>+ </plurals>+ <plurals name="scheduled_retries">+ <item quantity="one">Retry %1$d time</item>+ <item quantity="other">Retry %1$d times</item>+ </plurals></resources>diff --git a/app/src/test/java/com/gotcha/agent/ScheduleTaskLoopTest.kt b/app/src/test/java/com/gotcha/agent/ScheduleTaskLoopTest.ktnew file mode 100644index 0000000..b9be272--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/ScheduleTaskLoopTest.kt@@ -0,0 +1,168 @@+package com.gotcha.agent++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.LlmProvider+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import com.gotcha.llm.LLMClient+import com.gotcha.scheduled.ScheduledTaskStore+import com.gotcha.testsupport.FakeAndroidKeyStore+import com.gotcha.testsupport.ShadowExternalStorageManager+import com.gotcha.tools.AgentMode+import kotlinx.coroutines.test.runTest+import okhttp3.mockwebserver.MockResponse+import okhttp3.mockwebserver.MockWebServer+import org.junit.After+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+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.annotation.Config+import java.io.File++/**+ * `schedule_agent_task` end to end (issue #132): model call → checks →+ * approval → [ScheduledTaskStore] → audit log, and the tools withheld where+ * they must not be offered. Driven by a scripted server.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34], shadows = [ShadowExternalStorageManager::class])+class ScheduleTaskLoopTest {++ private val context: Context = ApplicationProvider.getApplicationContext()++ private lateinit var server: MockWebServer+ private lateinit var events: RecordingAgentEvents+ private lateinit var engine: AgentEngine+ private lateinit var store: ScheduledTaskStore+ private lateinit var workDir: File+ private val actionLog: File get() = File(context.filesDir, "action_log.txt")++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ server = MockWebServer()+ server.start()+ workDir = File(context.filesDir, "schedule-loop-test").apply {+ deleteRecursively()+ mkdirs()+ }+ actionLog.delete()+ store = ScheduledTaskStore(context)+ store.all().forEach { store.delete(it.id) }++ val repository = SettingsRepository(context)+ repository.save(+ Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ apiKey = "test-key",+ baseUrl = server.url("/").toString(),+ model = "gpt-4o",+ maxToolRounds = 4+ )+ )+ events = RecordingAgentEvents()+ engine = AgentEngine(+ appContext = context,+ events = events,+ historyRepository = ChatHistoryRepository(context, "schedule-loop-test-chats"),+ settingsProvider = { repository.load() },+ clientProvider = { LLMClient(apiKey = "test-key", baseUrl = server.url("/").toString()) },+ workingDirRoot = workDir.absolutePath+ )+ engine.sessionId = "schedule-loop-chat"+ }++ @After+ fun tearDown() {+ server.shutdown()+ workDir.deleteRecursively()+ actionLog.delete()+ }++ private fun enqueueScheduleCall(argsJson: String) {+ val args = argsJson.replace("\\", "\\\\").replace("\"", "\\\"")+ server.enqueue(+ MockResponse().setBody(+ """{"choices":[{"message":{"role":"assistant","tool_calls":[+ {"id":"call_1","type":"function",+ "function":{"name":"schedule_agent_task","arguments":"$args"}}]}}]}"""+ )+ )+ }++ private fun enqueueTextReply(text: String) {+ server.enqueue(MockResponse().setBody("""{"choices":[{"message":{"role":"assistant","content":"$text"}}]}"""))+ }++ private fun requestBodies(): List<String> = List(server.requestCount) { server.takeRequest().body.readUtf8() }++ private val newsTask = """{"name":"News","prompt":"Summarise the news","start":"2099-10-19T08:00","repeat":"daily"}"""++ @Test+ fun `approving saves the task, asked from this chat, and audits it`() = runTest {+ enqueueScheduleCall(newsTask)+ enqueueTextReply("Scheduled.")++ engine.run(AgentMode.OPERATOR)++ val prompt = events.confirmationRequests.single()+ assertTrue(prompt, prompt.startsWith("schedule_agent_task:"))+ assertTrue(prompt, prompt.contains("Prompt: Summarise the news"))+ val saved = store.all().single()+ assertEquals("News", saved.name)+ assertEquals(AgentMode.OPERATOR, saved.mode)+ assertTrue(saved.createdByAgent)+ assertTrue(requestBodies().last().contains("task_id ${saved.id}"))+ assertTrue(actionLog.readText().contains("schedule_agent_task\t(approved) News"))+ }++ @Test+ fun `declining saves nothing and tells the model not to retry`() = runTest {+ events.confirmationAnswer = false+ enqueueScheduleCall(newsTask)+ enqueueTextReply("Okay.")++ engine.run(AgentMode.OPERATOR)++ assertEquals(1, events.confirmationRequests.size)+ assertTrue(store.all().isEmpty())+ assertTrue(requestBodies().last().contains("declined"))+ assertTrue(actionLog.readText().contains("schedule_agent_task\t(denied)"))+ }++ @Test+ fun `monitor is offered only the list, and refused the rest`() = runTest {+ enqueueScheduleCall(newsTask)+ enqueueTextReply("I can't.")++ engine.run(AgentMode.MONITOR)++ val bodies = requestBodies()+ assertTrue(bodies.first().contains("\"list_scheduled_tasks\""))+ assertFalse(bodies.first().contains("\"schedule_agent_task\""))+ assertTrue(events.confirmationRequests.isEmpty())+ assertTrue(store.all().isEmpty())+ }++ @Test+ fun `a run a schedule started is offered none of the schedule tools`() = runTest {+ engine.scheduledRun = true+ enqueueScheduleCall(newsTask)+ enqueueTextReply("I can't.")++ engine.run(AgentMode.OPERATOR)++ val first = requestBodies().first()+ listOf("schedule_agent_task", "edit_scheduled_task", "list_scheduled_tasks", "delete_scheduled_task").forEach {+ assertFalse(it, first.contains("\"$it\""))+ }+ assertTrue(events.confirmationRequests.isEmpty())+ assertTrue(store.all().isEmpty())+ }+}diff --git a/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt b/app/src/test/java/com/gotcha/agent/ScheduledRunTest.ktnew file mode 100644index 0000000..f95f2c1--- /dev/null+++ b/app/src/test/java/com/gotcha/agent/ScheduledRunTest.kt@@ -0,0 +1,222 @@+package com.gotcha.agent++import android.Manifest+import android.app.Application+import android.app.NotificationManager+import androidx.core.app.NotificationCompat+import androidx.lifecycle.ViewModelProvider+import androidx.lifecycle.ViewModelStore+import androidx.test.core.app.ApplicationProvider+import com.gotcha.data.ChatHistoryRepository+import com.gotcha.data.ChatSession+import com.gotcha.data.LlmProvider+import com.gotcha.data.Settings+import com.gotcha.data.SettingsRepository+import com.gotcha.llm.ChatMessage+import com.gotcha.scheduled.ScheduledStart+import com.gotcha.scheduled.ScheduledTask+import com.gotcha.scheduled.ScheduledTaskRuns+import com.gotcha.scheduled.ScheduledTaskStore+import com.gotcha.scheduled.TaskRunStatus+import com.gotcha.service.ChatRunService+import com.gotcha.testsupport.FakeAndroidKeyStore+import com.gotcha.tools.AgentMode+import kotlinx.coroutines.CoroutineScope+import kotlinx.coroutines.Dispatchers+import kotlinx.coroutines.async+import kotlinx.coroutines.runBlocking+import kotlinx.serialization.json.JsonPrimitive+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNotNull+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+import org.robolectric.shadows.ShadowLooper+import java.net.ServerSocket+import kotlin.concurrent.thread++/**+ * A scheduled task's run (issue #132) on the app's [ChatRunner]: its prompt+ * starts a normal run in a new chat or at the end of its own one, never+ * alongside another run, without moving the screen, and how it ended goes into+ * the task's history. The LLM base URL refuses connections, so a run ends as a+ * failure.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScheduledRunTest {++ private val application: Application = ApplicationProvider.getApplicationContext()+ private val manager = application.getSystemService(NotificationManager::class.java)+ private val historyRepository = ChatHistoryRepository(application)+ private lateinit var store: ScheduledTaskStore++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ shadowOf(application).grantPermissions(Manifest.permission.POST_NOTIFICATIONS)+ manager.cancelAll()+ ChatRunService.stop()+ refusingModel()+ store = ScheduledTaskStore(application)+ store.all().forEach { store.delete(it.id) }+ }++ private fun refusingModel() {+ SettingsRepository(application).save(+ Settings(provider = LlmProvider.OPENAI_COMPATIBLE, apiKey = "test-key", baseUrl = "http://127.0.0.1:1/v1")+ )+ runner().refreshSettings()+ }++ private fun runner() = ChatRunner.of(application)++ private fun task(id: String = "news", sameChat: Boolean = false, chat: String? = null) = ScheduledTask(+ id = id,+ name = "Morning news",+ prompt = "Summarise the news",+ startLocal = "2099-01-01T08:00",+ agentMode = AgentMode.MONITOR.name,+ sameChat = sameChat,+ chatSessionId = chat+ ).also { store.put(it) }++ /** Runs [id] as "Run now" does, letting the main looper turn until it has started. */+ private fun runNow(id: String): ScheduledStart {+ val started = CoroutineScope(Dispatchers.Unconfined).async { ScheduledTaskRuns.runNow(application, id) }+ val deadline = System.currentTimeMillis() + 5_000+ while (!started.isCompleted && System.currentTimeMillis() < deadline) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(10)+ }+ return runBlocking { started.await() }+ }++ private fun waitForRunToFinish() {+ val deadline = System.currentTimeMillis() + 5_000+ ShadowLooper.idleMainLooper()+ while (System.currentTimeMillis() < deadline && runner().isRunning) {+ ShadowLooper.idleMainLooper()+ Thread.sleep(10)+ }+ ShadowLooper.idleMainLooper()+ }++ @Test+ fun `a task's prompt starts a run in a new chat, and the failure is in its history`() {+ task()++ val result = runNow("news") as ScheduledStart.Started+ waitForRunToFinish()++ val chat = runBlocking { historyRepository.loadSession(result.sessionId) }!!+ assertEquals("Summarise the news", chat.displayMessages.first().text)+ val saved = store.get("news")!!+ val run = saved.lastRun!!+ assertEquals(TaskRunStatus.FAILED, run.status)+ assertEquals(result.sessionId, run.sessionId)+ assertNotNull(run.detail)+ // One retry by default: it is armed.+ assertNotNull(saved.retryAt)+ }++ @Test+ fun `a run out of sight ends in a notification named after the task`() {+ task()++ runNow("news")+ waitForRunToFinish()++ val finished = shadowOf(manager).allNotifications.single()+ val title = finished.extras.getString(NotificationCompat.EXTRA_TITLE)!!+ assertTrue(title, title.contains("Morning news"))+ }++ @Test+ fun `same-chat mode adds the prompt to the end of its chat`() {+ runBlocking {+ historyRepository.saveSession(+ ChatSession(+ id = "kept",+ title = "Daily news",+ lastModified = 0L,+ messages = listOf(ChatMessage(role = "user", content = JsonPrimitive("Yesterday"))),+ displayMessages = listOf(UiMessage(0, MessageKind.USER, "Yesterday"))+ )+ )+ }+ task(sameChat = true, chat = "kept")++ val result = runNow("news") as ScheduledStart.Started+ waitForRunToFinish()++ assertEquals("kept", result.sessionId)+ val shown = runBlocking { historyRepository.loadSession("kept") }!!.displayMessages.map { it.text }+ assertEquals(listOf("Yesterday", "Summarise the news"), shown.take(2))+ }++ @Test+ fun `a same-chat task whose chat is gone starts one and keeps it`() {+ task(sameChat = true, chat = "deleted")++ val result = runNow("news") as ScheduledStart.Started+ waitForRunToFinish()++ assertTrue(result.sessionId != "deleted")+ assertEquals(result.sessionId, store.get("news")!!.chatSessionId)+ }++ @Test+ fun `a task never runs alongside another run`() {+ ServerSocket(0).use { silent ->+ // Holds the run's request unanswered; later ones (the title, as the+ // stopped run saves) are dropped at once.+ thread(isDaemon = true) {+ val held = runCatching { silent.accept() }.getOrNull()+ while (!silent.isClosed) runCatching { silent.accept().close() }+ held?.close()+ }+ SettingsRepository(application).save(+ Settings(+ provider = LlmProvider.OPENAI_COMPATIBLE,+ apiKey = "test-key",+ baseUrl = "http://127.0.0.1:${silent.localPort}/v1"+ )+ )+ runner().refreshSettings()+ task()+ val first = runNow("news")+ assertTrue(first is ScheduledStart.Started)++ task(id = "second")+ assertEquals(ScheduledStart.Busy, runNow("second"))++ runner().stop()+ waitForRunToFinish()+ }+ assertEquals(TaskRunStatus.STOPPED, store.get("news")!!.lastRun!!.status)+ }++ @Test+ fun `the screen stays on the chat it shows`() {+ val viewModel = ViewModelProvider(+ ViewModelStore(),+ ViewModelProvider.AndroidViewModelFactory(application)+ )[ChatViewModel::class.java]+ val viewed = viewModel.uiState.value.activeSessionId+ task()++ val result = runNow("news") as ScheduledStart.Started+ ShadowLooper.idleMainLooper()++ assertEquals(viewed, viewModel.uiState.value.activeSessionId)+ assertTrue(viewModel.uiState.value.messages.isEmpty())+ assertTrue(result.sessionId != viewed)+ waitForRunToFinish()+ assertTrue(viewModel.uiState.value.messages.isEmpty())+ }+}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.ktnew file mode 100644index 0000000..5008963--- /dev/null+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskPlannerTest.kt@@ -0,0 +1,180 @@+package com.gotcha.scheduled++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Assert.assertTrue+import org.junit.Test+import java.time.LocalDateTime+import java.time.ZoneId++/** [ScheduledTaskPlanner]: what a task does when it fires, and how it moves on (issue #132). */+class ScheduledTaskPlannerTest {++ private val zone = ZoneId.of("UTC")+ private val minute = 60_000L+ private val hour = 60 * minute++ private fun at(local: String): Long = LocalDateTime.parse(local).atZone(zone).toInstant().toEpochMilli()++ private fun daily(now: Long = at("2026-10-19T07:00"), retries: Int = 1) = ScheduledTaskPlanner.armed(+ ScheduledTask(+ id = "t",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-19T08:00",+ repeat = Repeat(RepeatKind.DAILY),+ maxRetries = retries+ ),+ now,+ zone+ )++ @Test+ fun `arming sets the next time from now`() {+ assertEquals(at("2026-10-19T08:00"), daily().nextRunAt)+ assertEquals(at("2026-10-20T08:00"), daily(now = at("2026-10-19T09:00")).nextRunAt)+ }++ @Test+ fun `a task waits until its time, then runs`() {+ val task = daily()+ assertEquals(+ ScheduledTaskPlanner.Decision.Wait,+ ScheduledTaskPlanner.decide(task, at("2026-10-19T07:59"), zone)+ )+ assertEquals(ScheduledTaskPlanner.Decision.Run, ScheduledTaskPlanner.decide(task, at("2026-10-19T08:00"), zone))+ // An alarm a few seconds early still counts.+ assertEquals(+ ScheduledTaskPlanner.Decision.Run,+ ScheduledTaskPlanner.decide(task, at("2026-10-19T08:00") - 10_000, zone)+ )+ }++ @Test+ fun `a paused task never runs`() {+ val task = daily().copy(enabled = false)+ assertNull(task.dueAt)+ assertEquals(+ ScheduledTaskPlanner.Decision.Wait,+ ScheduledTaskPlanner.decide(task, at("2026-10-19T08:00"), zone)+ )+ }++ @Test+ fun `a task found well past its time is recorded as missed and moves on`() {+ val decision = ScheduledTaskPlanner.decide(daily(), at("2026-10-19T10:00"), zone)+ val missed = (decision as ScheduledTaskPlanner.Decision.Missed).task+ assertEquals(TaskRunStatus.MISSED, missed.lastRun!!.status)+ assertEquals(at("2026-10-20T08:00"), missed.nextRunAt)+ }++ @Test+ fun `a task a little late still runs`() {+ assertEquals(+ ScheduledTaskPlanner.Decision.Run,+ ScheduledTaskPlanner.decide(daily(), at("2026-10-19T08:40"), zone)+ )+ }++ @Test+ fun `starting the run moves the task to its next time`() {+ val started = ScheduledTaskPlanner.started(daily(), "chat", at("2026-10-19T08:00"), zone)+ assertEquals(at("2026-10-20T08:00"), started.nextRunAt)+ assertNull(started.retryAt)+ }++ @Test+ fun `a failure is retried after the delay, without skipping the next time`() {+ val now = at("2026-10-19T08:00")+ val started = ScheduledTaskPlanner.started(daily(), "chat", now, zone)+ val failed = ScheduledTaskPlanner.finished(started, TaskRunStatus.FAILED, "chat", "No network", now + minute)+ assertEquals(now + minute + 10 * minute, failed.retryAt)+ assertEquals(failed.retryAt, failed.dueAt)+ assertEquals("No network", failed.lastRun!!.detail)++ // The retry fires; its start must leave tomorrow's run where it is.+ val retryAt = failed.retryAt!!+ assertEquals(ScheduledTaskPlanner.Decision.Run, ScheduledTaskPlanner.decide(failed, retryAt, zone))+ val retried = ScheduledTaskPlanner.started(failed, "chat", retryAt, zone)+ assertEquals(at("2026-10-20T08:00"), retried.nextRunAt)++ // Out of retries: the second failure is final.+ val failedAgain = ScheduledTaskPlanner.finished(retried, TaskRunStatus.FAILED, "chat", null, retryAt + minute)+ assertNull(failedAgain.retryAt)+ assertEquals(at("2026-10-20T08:00"), failedAgain.dueAt)+ assertEquals(2, failedAgain.history.size)+ }++ @Test+ fun `a task with no retries gives a failure up at once`() {+ val now = at("2026-10-19T08:00")+ val started = ScheduledTaskPlanner.started(daily(retries = 0), "chat", now, zone)+ assertNull(ScheduledTaskPlanner.finished(started, TaskRunStatus.FAILED, "chat", null, now).retryAt)+ }++ @Test+ fun `a busy runner makes the task wait, then give the occurrence up`() {+ val now = at("2026-10-19T08:00")+ val waiting = ScheduledTaskPlanner.busy(daily(), now, zone)+ // The past time is claimed, so it can't keep the alarm firing.+ assertEquals(now + ScheduledTaskPlanner.BUSY_RECHECK_MS, waiting.dueAt)+ assertEquals(at("2026-10-20T08:00"), waiting.nextRunAt)+ assertEquals(now, ScheduledTaskPlanner.busy(waiting, now + 2 * minute, zone).busySince)+ // A long wait is not "missed": it was due all along.+ val later = now + 50 * minute+ assertEquals(+ ScheduledTaskPlanner.Decision.Run,+ ScheduledTaskPlanner.decide(waiting.copy(retryAt = later), later, zone)+ )++ val gaveUp = ScheduledTaskPlanner.busy(waiting, now + hour, zone)+ assertEquals(TaskRunStatus.SKIPPED_BUSY, gaveUp.lastRun!!.status)+ assertEquals(at("2026-10-20T08:00"), gaveUp.dueAt)+ }++ @Test+ fun `a run that waited for a busy runner still moves to the next time when it starts`() {+ val now = at("2026-10-19T08:00")+ val waiting = ScheduledTaskPlanner.busy(daily(), now, zone)+ val started = ScheduledTaskPlanner.started(waiting, "chat", now + 4 * minute, zone)+ assertEquals(at("2026-10-20T08:00"), started.nextRunAt)+ assertNull(started.busySince)+ }++ @Test+ fun `a same-chat task keeps the chat its first run made`() {+ val task = daily().copy(sameChat = true)+ assertEquals("chat-1", ScheduledTaskPlanner.started(task, "chat-1", at("2026-10-19T08:00"), zone).chatSessionId)+ assertNull(ScheduledTaskPlanner.started(daily(), "chat-1", at("2026-10-19T08:00"), zone).chatSessionId)+ }++ @Test+ fun `a one-time task has nothing left once it has run`() {+ val once = ScheduledTaskPlanner.armed(+ ScheduledTask(id = "t", name = "n", prompt = "p", startLocal = "2026-10-19T08:00"),+ at("2026-10-19T07:00"),+ zone+ )+ val started = ScheduledTaskPlanner.started(once, "chat", at("2026-10-19T08:00"), zone)+ assertNull(started.dueAt)+ assertNull(ScheduledTaskPlanner.nextAlarm(listOf(started)))+ }++ @Test+ fun `the alarm is set for the soonest task`() {+ val soon = daily()+ val later = daily(now = at("2026-10-19T09:00")).copy(id = "u")+ assertEquals(soon.nextRunAt, ScheduledTaskPlanner.nextAlarm(listOf(later, soon)))+ assertTrue(ScheduledTaskPlanner.nextAlarm(emptyList()) == null)+ }++ @Test+ fun `history keeps the newest runs only`() {+ var task = daily()+ repeat(+ ScheduledTask.MAX_HISTORY + 5+ ) { task = task.withRun(TaskRun(at = it.toLong(), status = TaskRunStatus.DONE)) }+ assertEquals(ScheduledTask.MAX_HISTORY, task.history.size)+ assertEquals((ScheduledTask.MAX_HISTORY + 4).toLong(), task.history.last().at)+ }+}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.ktnew file mode 100644index 0000000..e92dce0--- /dev/null+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskScheduleTest.kt@@ -0,0 +1,109 @@+package com.gotcha.scheduled++import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+import org.junit.Test+import java.time.LocalDateTime+import java.time.ZoneId++/** [nextOccurrence]: the calendar rules of scheduled tasks (issue #132). */+class ScheduledTaskScheduleTest {++ private val zone = ZoneId.of("Europe/Berlin")++ private fun task(start: String, repeat: Repeat = Repeat()) =+ ScheduledTask(id = "t", name = "n", prompt = "p", startLocal = start, repeat = repeat)++ private fun at(local: String): Long = LocalDateTime.parse(local).atZone(zone).toInstant().toEpochMilli()++ private fun next(task: ScheduledTask, after: String): String? =+ nextOccurrence(task, at(after), zone)?.let {+ LocalDateTime.ofInstant(java.time.Instant.ofEpochMilli(it), zone).toString()+ }++ @Test+ fun `a one-time task is due at its time, and never after`() {+ val once = task("2026-10-19T08:00")+ assertEquals("2026-10-19T08:00", next(once, "2026-10-18T12:00"))+ assertNull(next(once, "2026-10-19T08:00"))+ assertNull(next(once, "2026-10-20T08:00"))+ }++ @Test+ fun `a daily task comes round at the same local time`() {+ val daily = task("2026-10-19T08:00", Repeat(RepeatKind.DAILY))+ assertEquals("2026-10-19T08:00", next(daily, "2026-10-01T00:00"))+ assertEquals("2026-10-20T08:00", next(daily, "2026-10-19T08:00"))+ assertEquals("2026-10-21T08:00", next(daily, "2026-10-20T09:30"))+ }++ @Test+ fun `a daily task keeps its local time across a summer-time change`() {+ val daily = task("2026-10-24T08:00", Repeat(RepeatKind.DAILY))+ // Clocks go back on 25 October 2026 in Berlin; 8:00 stays 8:00.+ assertEquals("2026-10-25T08:00", next(daily, "2026-10-24T08:00"))+ assertEquals("2026-10-26T08:00", next(daily, "2026-10-25T08:00"))+ }++ @Test+ fun `a time the clocks skip runs just after the gap`() {+ val daily = task("2026-03-28T02:30", Repeat(RepeatKind.DAILY))+ // 02:30 does not exist on 29 March 2026 in Berlin.+ assertEquals("2026-03-29T03:30", next(daily, "2026-03-28T02:30"))+ }++ @Test+ fun `every few days counts from the start date`() {+ val everyThird = task("2026-10-19T08:00", Repeat(RepeatKind.DAILY, interval = 3))+ assertEquals("2026-10-22T08:00", next(everyThird, "2026-10-19T08:00"))+ assertEquals("2026-10-22T08:00", next(everyThird, "2026-10-21T23:59"))+ assertEquals("2026-10-25T08:00", next(everyThird, "2026-10-22T08:01"))+ }++ @Test+ fun `an hourly task counts real hours, summer time or not`() {+ val everyTwoHours = task("2026-10-25T00:00", Repeat(RepeatKind.HOURLY, interval = 2))+ val first = at("2026-10-25T00:00")+ // The clocks go back at 03:00 that night: the next run is two real hours on, whatever the clock says.+ val twoHoursLater = nextOccurrence(everyTwoHours, first, zone)!!+ assertEquals(2L * 60 * 60 * 1000, twoHoursLater - first)+ }++ @Test+ fun `a weekly task runs on each listed weekday`() {+ // 19 October 2026 is a Monday.+ val weekdays = task("2026-10-19T08:00", Repeat(RepeatKind.WEEKLY, weekdays = listOf(1, 3, 5)))+ assertEquals("2026-10-19T08:00", next(weekdays, "2026-10-18T00:00"))+ assertEquals("2026-10-21T08:00", next(weekdays, "2026-10-19T08:00"))+ assertEquals("2026-10-23T08:00", next(weekdays, "2026-10-21T09:00"))+ assertEquals("2026-10-26T08:00", next(weekdays, "2026-10-23T08:00"))+ }++ @Test+ fun `a weekly task starting on an unlisted day waits for a listed one`() {+ // Starts on a Monday but runs on Saturdays only.+ val saturdays = task("2026-10-19T08:00", Repeat(RepeatKind.WEEKLY, weekdays = listOf(6)))+ assertEquals("2026-10-24T08:00", next(saturdays, "2026-10-18T00:00"))+ }++ @Test+ fun `a weekly task with no days listed runs on its start's weekday`() {+ val mondays = task("2026-10-19T08:00", Repeat(RepeatKind.WEEKLY))+ assertEquals("2026-10-26T08:00", next(mondays, "2026-10-19T08:00"))+ }++ @Test+ fun `a monthly task on the 31st falls on the last day of shorter months`() {+ val monthEnd = task("2026-01-31T09:00", Repeat(RepeatKind.MONTHLY))+ assertEquals("2026-02-28T09:00", next(monthEnd, "2026-01-31T09:00"))+ assertEquals("2026-03-31T09:00", next(monthEnd, "2026-02-28T09:00"))+ assertEquals("2026-04-30T09:00", next(monthEnd, "2026-03-31T09:00"))+ }++ @Test+ fun `a monthly task later in the month is due this month`() {+ val fifteenth = task("2026-01-15T09:00", Repeat(RepeatKind.MONTHLY))+ assertEquals("2026-10-15T09:00", next(fifteenth, "2026-10-01T00:00"))+ assertEquals("2026-11-15T09:00", next(fifteenth, "2026-10-15T09:00"))+ }+}diff --git a/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.ktnew file mode 100644index 0000000..723d079--- /dev/null+++ b/app/src/test/java/com/gotcha/scheduled/ScheduledTaskStoreTest.kt@@ -0,0 +1,90 @@+package com.gotcha.scheduled++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.agent.Attachment+import com.gotcha.agent.ComposerAttachment+import org.junit.Assert.assertEquals+import org.junit.Assert.assertNull+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.annotation.Config+import java.io.File++/** [ScheduledTaskStore]: the tasks and the files kept with them (issue #132). */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScheduledTaskStoreTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val dir = File(context.filesDir, "scheduled-store-test")+ private lateinit var store: ScheduledTaskStore++ @Before+ fun setUp() {+ dir.deleteRecursively()+ store = ScheduledTaskStore(context.getSharedPreferences("scheduled-store-test", Context.MODE_PRIVATE), dir)+ }++ private fun task(id: String, chat: String? = null) =+ ScheduledTask(id = id, name = "Task $id", prompt = "p", startLocal = "2026-10-19T08:00", chatSessionId = chat)++ private val document = ComposerAttachment.Document(+ "a",+ Attachment(name = "notes.txt", mimeType = "text/plain", size = 5, text = "hello")+ )++ @Test+ fun `tasks are added, replaced and deleted`() {+ store.put(task("1"))+ store.put(task("2"))+ store.put(task("1").copy(name = "Renamed"))++ assertEquals(listOf("Renamed", "Task 2"), store.all().map { it.name })++ store.delete("1")+ assertEquals(listOf("2"), store.all().map { it.id })+ }++ @Test+ fun `update changes one task and reports a missing one`() {+ store.put(task("1"))+ val updated = store.update("1") { it.copy(enabled = false) }+ assertEquals(false, updated!!.enabled)+ assertEquals(false, store.get("1")!!.enabled)+ assertNull(store.update("nope") { it })+ }++ @Test+ fun `files are kept with the task and go with it`() {+ val withFile = task("1").copy(attachmentNames = listOf("notes.txt"))+ store.put(withFile)+ store.saveAttachments("1", listOf(document))++ assertEquals(listOf(document), store.loadAttachments(withFile))++ store.delete("1")+ assertTrue(dir.listFiles().orEmpty().isEmpty())+ }++ @Test+ fun `a task whose files are gone reports them unreadable`() {+ val withFile = task("1").copy(attachmentNames = listOf("notes.txt"))+ assertNull(store.loadAttachments(withFile))+ assertEquals(emptyList<ComposerAttachment>(), store.loadAttachments(task("2")))+ }++ @Test+ fun `a deleted chat is forgotten by the tasks pinned to it`() {+ store.put(task("1", chat = "chat-a"))+ store.put(task("2", chat = "chat-b"))++ store.forgetChat("chat-a")++ assertNull(store.get("1")!!.chatSessionId)+ assertEquals("chat-b", store.get("2")!!.chatSessionId)+ }+}diff --git a/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt b/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.ktnew file mode 100644index 0000000..34906c5--- /dev/null+++ b/app/src/test/java/com/gotcha/tools/ScheduledTaskToolTest.kt@@ -0,0 +1,252 @@+package com.gotcha.tools++import android.content.Context+import androidx.test.core.app.ApplicationProvider+import com.gotcha.agent.ComposerAttachment+import com.gotcha.scheduled.RepeatKind+import com.gotcha.scheduled.ScheduledTask+import com.gotcha.scheduled.ScheduledTaskStore+import com.gotcha.testsupport.FakeAndroidKeyStore+import kotlinx.serialization.json.Json+import kotlinx.serialization.json.JsonObject+import org.junit.Assert.assertEquals+import org.junit.Assert.assertFalse+import org.junit.Assert.assertNotNull+import org.junit.Assert.assertNull+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.annotation.Config+import java.io.File+import java.time.LocalDateTime+import java.time.ZoneId++/**+ * The scheduled-task tools' own checks (issue #132): what a request must hold+ * before the user is asked anything, and what an approved one saves.+ */+@RunWith(RobolectricTestRunner::class)+@Config(sdk = [34])+class ScheduledTaskToolTest {++ private val context: Context = ApplicationProvider.getApplicationContext()+ private val zone = ZoneId.of("UTC")+ private val now = LocalDateTime.parse("2026-10-18T12:00").atZone(zone).toInstant().toEpochMilli()+ private lateinit var store: ScheduledTaskStore+ private lateinit var tool: ScheduledTaskTool++ @Before+ fun setUp() {+ FakeAndroidKeyStore.setUp()+ store = ScheduledTaskStore(context)+ store.all().forEach { store.delete(it.id) }+ tool = ScheduledTaskTool(context, store, zone = { zone }, clock = { now })+ }++ private fun args(json: String): JsonObject = Json.parseToJsonElement(json) as JsonObject++ private fun request(result: ToolResult): ScheduleRequest {+ assertTrue(result.message, result.success)+ assertTrue(result.message, result.message.startsWith(ScheduledTaskTool.CONFIRM_PREFIX))+ return ScheduledTaskTool.decodePayload(result.message.removePrefix(ScheduledTaskTool.CONFIRM_PREFIX))!!+ }++ @Test+ fun `a valid create asks for approval and saves nothing yet`() {+ val result = tool.prepareCreate(+ args(+ """{"name":"News","prompt":"Summarise the news","start":"2026-10-19T08:00","repeat":"weekly","weekdays":["mon","fri"]}"""+ )+ )++ val request = request(result)+ assertEquals("2026-10-19T08:00", request.startLocal)+ assertEquals(RepeatKind.WEEKLY, request.repeat!!.kind)+ assertEquals(listOf(1, 5), request.repeat!!.weekdays)+ assertTrue(store.all().isEmpty())+ }++ @Test+ fun `a create missing its fields or with bad ones is refused before any prompt`() {+ assertFalse(tool.prepareCreate(args("""{"prompt":"p","start":"2026-10-19T08:00"}""")).success)+ assertFalse(tool.prepareCreate(args("""{"name":"n","start":"2026-10-19T08:00"}""")).success)+ assertFalse(tool.prepareCreate(args("""{"name":"n","prompt":"p"}""")).success)+ val badStart = tool.prepareCreate(args("""{"name":"n","prompt":"p","start":"tomorrow"}"""))+ assertTrue(badStart.message, badStart.message.contains("YYYY-MM-DDTHH:MM"))+ val badRepeat = tool.prepareCreate(+ args("""{"name":"n","prompt":"p","start":"2026-10-19T08:00","repeat":"minutely"}""")+ )+ assertTrue(badRepeat.message, badRepeat.message.contains("Invalid 'repeat'"))+ val badDay = tool.prepareCreate(+ args("""{"name":"n","prompt":"p","start":"2026-10-19T08:00","repeat":"weekly","weekdays":["funday"]}""")+ )+ assertTrue(badDay.message, badDay.message.contains("Invalid weekday"))+ val badInterval = tool.prepareCreate(+ args("""{"name":"n","prompt":"p","start":"2026-10-19T08:00","repeat":"hourly","interval":0}""")+ )+ assertTrue(badInterval.message, badInterval.message.contains("Invalid 'interval'"))+ }++ @Test+ fun `a one-time task in the past is refused`() {+ val result = tool.prepareCreate(args("""{"name":"n","prompt":"p","start":"2026-10-18T11:00"}"""))+ assertFalse(result.success)+ assertTrue(result.message, result.message.contains("already passed"))+ }++ @Test+ fun `the agent can set up only so many tasks`() {+ repeat(ScheduledTaskTool.MAX_AGENT_TASKS) {+ store.put(+ ScheduledTask(+ id = "a$it",+ name = "n",+ prompt = "p",+ startLocal = "2026-10-19T08:00",+ createdByAgent = true+ )+ )+ }+ // The user's own don't count.+ store.put(ScheduledTask(id = "u", name = "n", prompt = "p", startLocal = "2026-10-19T08:00"))++ val result = tool.prepareCreate(args("""{"name":"n","prompt":"p","start":"2026-10-19T08:00"}"""))++ assertFalse(result.success)+ assertTrue(result.message, result.message.contains("the most allowed"))+ }++ @Test+ fun `an approved create is saved, armed and capped at the chat's mode`() {+ val request = request(+ tool.prepareCreate(+ args(+ """{"name":"News","prompt":"Summarise","start":"2026-10-19T08:00","repeat":"daily",""" ++ """"mode":"operator","same_chat":true}"""+ )+ )+ )++ val result = tool.apply(request, sessionId = "chat-1", chatMode = AgentMode.MONITOR)++ assertTrue(result.message, result.success)+ val saved = store.all().single()+ assertEquals(AgentMode.MONITOR, saved.mode)+ assertTrue(saved.createdByAgent)+ assertTrue(saved.sameChat)+ assertEquals("chat-1", saved.chatSessionId)+ assertEquals(LocalDateTime.parse("2026-10-19T08:00").atZone(zone).toInstant().toEpochMilli(), saved.nextRunAt)+ assertTrue(result.message, result.message.contains(saved.id))+ }++ @Test+ fun `the mode defaults to the chat's`() {+ val request = request(tool.prepareCreate(args("""{"name":"n","prompt":"p","start":"2026-10-19T08:00"}""")))+ tool.apply(request, sessionId = "chat", chatMode = AgentMode.OPERATOR)+ assertEquals(AgentMode.OPERATOR, store.all().single().mode)+ }++ @Test+ fun `files are checked when asked and read when approved`() {+ val notes = File(context.filesDir, "notes.txt").apply { writeText("Buy milk") }+ val missing = tool.prepareCreate(+ args(+ """{"name":"n","prompt":"p","start":"2026-10-19T08:00","files":["${File(+ context.filesDir,+ "nope.txt"+ ).path}"]}"""+ )+ )+ assertFalse(missing.success)++ val request = request(+ tool.prepareCreate(+ args("""{"name":"n","prompt":"p","start":"2026-10-19T08:00","files":["${notes.path}"]}""")+ )+ )+ tool.apply(request, sessionId = "chat", chatMode = AgentMode.OPERATOR)++ val saved = store.all().single()+ assertEquals(listOf("notes.txt"), saved.attachmentNames)+ val document = store.loadAttachments(saved)!!.single() as ComposerAttachment.Document+ assertTrue(document.attachment.text, document.attachment.text.contains("Buy milk"))+ }++ @Test+ fun `an edit changes only what it names and re-arms a new schedule`() {+ store.put(+ ScheduledTask(+ id = "t",+ name = "Old",+ prompt = "Old prompt",+ startLocal = "2026-10-19T08:00",+ nextRunAt = 1L+ )+ )++ val request = request(tool.prepareEdit(args("""{"task_id":"t","start":"2026-10-20T09:00","enabled":false}""")))+ assertNull(request.name)+ tool.apply(request, sessionId = "chat", chatMode = AgentMode.OPERATOR)++ val saved = store.get("t")!!+ assertEquals("Old", saved.name)+ assertEquals("Old prompt", saved.prompt)+ assertEquals("2026-10-20T09:00", saved.startLocal)+ assertFalse(saved.enabled)+ assertNull(saved.dueAt)+ }++ @Test+ fun `an edit of an unknown task or with nothing in it is refused`() {+ assertTrue(tool.prepareEdit(args("""{"task_id":"nope","name":"x"}""")).message.contains("No scheduled task"))+ store.put(ScheduledTask(id = "t", name = "n", prompt = "p", startLocal = "2026-10-19T08:00"))+ assertTrue(tool.prepareEdit(args("""{"task_id":"t"}""")).message.contains("Nothing to change"))+ }++ @Test+ fun `the approval prompt shows the whole task`() {+ val request = request(+ tool.prepareCreate(+ args(+ """{"name":"News","prompt":"Summarise the news","start":"2026-10-19T08:00","repeat":"daily","interval":2}"""+ )+ )+ )++ val prompt = tool.describe(request, AgentMode.OPERATOR)++ assertTrue(prompt, prompt.contains("Name: News"))+ assertTrue(prompt, prompt.contains("every 2 days at 08:00"))+ assertTrue(prompt, prompt.contains("Mode: Operator"))+ assertTrue(prompt, prompt.contains("a new chat each time"))+ assertTrue(prompt, prompt.contains("Prompt: Summarise the news"))+ assertTrue(prompt, prompt.contains("without asking you first"))+ }++ @Test+ fun `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"))++ val listed = tool.list().message+ assertTrue(listed, listed.contains("t: \"News\""))+ assertTrue(listed, listed.contains("prompt: Summarise"))++ val delete = tool.prepareDelete(args("""{"task_id":"t"}"""))+ assertEquals("${ScheduledTaskTool.DELETE_CONFIRM_PREFIX}t:News", delete.message)+ assertNotNull(store.get("t"))++ assertTrue(tool.doDelete("t").success)+ assertNull(store.get("t"))+ }++ @Test+ fun `weekdays and start times are read the ways a model writes them`() {+ assertEquals(1, ScheduledTaskTool.parseWeekday("Monday"))+ assertEquals(7, ScheduledTaskTool.parseWeekday("su"))+ assertEquals(3, ScheduledTaskTool.parseWeekday("3"))+ assertNull(ScheduledTaskTool.parseWeekday("m"))+ assertEquals(LocalDateTime.parse("2026-10-19T08:00"), ScheduledTaskTool.parseStart("2026-10-19 08:00:30"))+ }+}diff --git a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.ktindex 6a2d3bc..3a5e739 100644--- a/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt+++ b/app/src/test/java/com/gotcha/tools/ToolArgValidationTest.kt@@ -132,6 +132,8 @@ class ToolArgValidationTest {* - `update_gotcha_settings` is likewise refused to sub-agents: its approval prompt* belongs to the run the user is watching. `GotchaSettingsUpdateTest` and* `SettingsUpdateLoopTest` cover its argument checks at the top level.+ * - the scheduled-task writes are refused to sub-agents for the same reason;+ * `ScheduledTaskToolTest` covers their argument checks.*/val NOT_PARAMETER_NAMED = setOf("create_task",@@ -143,7 +145,10 @@ class ToolArgValidationTest {"notion_mark_todo","notion_delete_item","set_timer",- "update_gotcha_settings"+ "update_gotcha_settings",+ "schedule_agent_task",+ "edit_scheduled_task",+ "delete_scheduled_task")}}diff --git a/app/src/test/resources/feature-test-coverage.json b/app/src/test/resources/feature-test-coverage.jsonindex 2e79c15..5db1996 100644--- a/app/src/test/resources/feature-test-coverage.json+++ b/app/src/test/resources/feature-test-coverage.json@@ -238,6 +238,43 @@"reason": "Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier.","manualSteps": "With a timer running, ask 'what timers are running?'; confirm the remaining time is right."},+ {+ "tool": "schedule_agent_task",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.ScheduledTaskToolTest",+ "com.gotcha.agent.ScheduleTaskLoopTest",+ "com.gotcha.agent.ScheduledRunTest",+ "com.gotcha.scheduled.ScheduledTaskPlannerTest",+ "com.gotcha.scheduled.ScheduledTaskScheduleTest"+ ],+ "notes": "argument checks before any prompt, the cap on agent-made tasks, approval on every create (denial saves nothing), the mode capped at the chat's, files read on approval, withheld from Monitor, sub-agents and scheduled runs; the schedule math and the runs it starts"+ },+ {+ "tool": "edit_scheduled_task",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.ScheduledTaskToolTest"+ ],+ "notes": "only the named fields change, a new schedule is re-armed, pausing clears the next run, unknown ids and empty edits are refused"+ },+ {+ "tool": "list_scheduled_tasks",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.ScheduledTaskToolTest",+ "com.gotcha.agent.ScheduleTaskLoopTest"+ ],+ "notes": "each task with its id, schedule and prompt; the one schedule tool Monitor is offered"+ },+ {+ "tool": "delete_scheduled_task",+ "tier": "ROBOLECTRIC",+ "tests": [+ "com.gotcha.tools.ScheduledTaskToolTest"+ ],+ "notes": "returns the destructive-delete confirmation marker; the task is only removed once confirmed"+ },{"tool": "edit_alarm","tier": "MANUAL_ONLY",diff --git a/docs/FEATURE_TEST_COVERAGE.md b/docs/FEATURE_TEST_COVERAGE.mdindex f2b4009..a82c147 100644--- a/docs/FEATURE_TEST_COVERAGE.md+++ b/docs/FEATURE_TEST_COVERAGE.md@@ -14,12 +14,12 @@ Every tool the assistant can call is listed below, together with how it is verif| Tier | Tools | What it means ||---|---:|---|| `UNIT` | 24 | Plain JVM unit test — no Android framework needed. |-| `ROBOLECTRIC` | 30 | JVM test against Robolectric's Android framework, often across several API levels. |+| `ROBOLECTRIC` | 34 | JVM test against Robolectric's Android framework, often across several API levels. || `INSTRUMENTED` | 0 | Runs on a real device or emulator (`app/src/androidTest`). || `MANUAL_ONLY` | 64 | No automated test — verified by hand, see the checklist below. |-| **Total** | **118** | |+| **Total** | **122** | |-**54 of 118** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.+**58 of 122** tools are covered by an automated test; the remaining 64 are manual-QA-only with a recorded reason.## Foreground tools (act on the screen)@@ -55,6 +55,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `create_task` | `MANUAL_ONLY` | Routed to a live Microsoft Graph account; only the underlying GraphApi has JVM coverage today. || `delete_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `delete_calendar_event` | `UNIT` | `CalendarToolsTest` — connector path only; destructive, so also gated by the confirmation flow |+| `delete_scheduled_task` | `ROBOLECTRIC` | `ScheduledTaskToolTest` — returns the destructive-delete confirmation marker; the task is only removed once confirmed || `delete_timer` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `disable_camera` | `MANUAL_ONLY` | Needs an active Device Admin registration, which cannot be granted non-interactively. || `dismiss_notifications` | `MANUAL_ONLY` | Needs NotificationListenerService bound with the user's explicit grant; not bindable from a test host. |@@ -62,6 +63,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `edit` | `ROBOLECTRIC` | `FileToolsTest` — unique match, replaceAll, no-match and blank-argument rejection || `edit_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `edit_calendar_event` | `UNIT` | `CalendarToolsTest` — connector path only; the on-device CalendarProvider path is manual |+| `edit_scheduled_task` | `ROBOLECTRIC` | `ScheduledTaskToolTest` — only the named fields change, a new schedule is re-armed, pausing clears the next run, unknown ids and empty edits are refused || `hide_overlay` | `MANUAL_ONLY` | Draws a real SYSTEM_ALERT_WINDOW; needs the 'Display over other apps' grant and a visible screen to verify. || `lock_screen` | `MANUAL_ONLY` | Needs an active Device Admin registration, which cannot be granted non-interactively. || `mark_email_read` | `UNIT` | `EmailToolsTest` — read/unread toggle routed to the right backend |@@ -77,6 +79,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `run_command` | `UNIT` | `TerminalToolTest` — argument splitting, timeout, exit codes, output truncation || `run_root_command` | `MANUAL_ONLY` | Requires a rooted device and an interactive superuser grant. || `run_termux_command` | `ROBOLECTRIC` | `TermuxToolTest`, `ActionLogRedactionTest` — installed/granted decision table, deny-list, size guard, result-bundle parsing, truncation, timeout path; the live round-trip needs a real Termux install and is verified by hand |+| `schedule_agent_task` | `ROBOLECTRIC` | `ScheduledTaskToolTest`, `ScheduleTaskLoopTest`, `ScheduledRunTest`, `ScheduledTaskPlannerTest`, `ScheduledTaskScheduleTest` — argument checks before any prompt, the cap on agent-made tasks, approval on every create (denial saves nothing), the mode capped at the chat's, files read on approval, withheld from Monitor, sub-agents and scheduled runs; the schedule math and the runs it starts || `send_email` | `UNIT` | `EmailToolsTest`, `MimeMessageBuilderTest` — confirmation flow, recipient handling, MIME construction with attachments || `send_sms` | `MANUAL_ONLY` | Needs real device hardware; the emulator has no faithful stand-in for this sensor/radio. || `set_alarm` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. |@@ -133,6 +136,7 @@ Every tool the assistant can call is listed below, together with how it is verif| `list_emails` | `UNIT` | `EmailToolsTest` — backend routing, unread filter, result limits || `list_files` | `ROBOLECTRIC` | `FileToolsTest` — flat and recursive listings || `list_installed_apps` | `ROBOLECTRIC` | `AppsToolTest` — listing, system-app marking, counts, search filtering |+| `list_scheduled_tasks` | `ROBOLECTRIC` | `ScheduledTaskToolTest`, `ScheduleTaskLoopTest` — each task with its id, schedule and prompt; the one schedule tool Monitor is offered || `list_tasks` | `MANUAL_ONLY` | Routed to a live Microsoft Graph account; only the underlying GraphApi has JVM coverage today. || `list_timers` | `MANUAL_ONLY` | Needs an Android Context and a system service with real device state; no JVM-tier coverage yet — scheduled for the Robolectric tier. || `notion_delete_item` | `UNIT` | `NotionToolsMutationTest` — page trash patch vs block delete request shapes |