Skip to content

Open source Grok Bot alternative, Bring your own agent and subscription: message Claude Code, Codex, Gemini CLI, Cursor, Copilot and 40+ AI agents as bots on your own computer, from iPhone, Mac, Windows, Linux or terminal. Agent-agnostic and free. Also a Muse and Dots alternative. Built in Rust.

feat: pick routine schedules from presets and search time zones

leepokai383ea265035d
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
index 8f9bf9d2..8d9cfa8c 100644
--- a/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
+++ b/apps/android/app/src/main/kotlin/com/codync/android/RoutinesScreen.kt
@@ -50,6 +50,8 @@ import com.codync.android.core.RoutineDraft
import com.codync.android.core.RoutineScheduleDraft
import com.codync.android.core.RoutineSchedulePreview
import com.codync.android.core.RoutineWebhook
+import com.codync.android.core.canEdit
+import com.codync.android.core.routineRepeats
import com.codync.android.design.*
import com.kyant.shapes.RoundedRectangle
import java.text.DateFormat
@@ -97,8 +99,8 @@ import kotlinx.coroutines.launch
}
}
}
- // Item-based, so the editor always gets the routine it was opened on.
- CodyncSheet(editing, { editing = null }) { id ->
+ // Item-based, so the editor always gets the routine it was opened on; it opens once that routine is listed.
+ CodyncSheet(editing?.takeIf { listing.canEdit(it) }, { editing = null }) { id ->
RoutineEditor(bot.id, listing?.routines?.firstOrNull { it.id == id }, state, store) { saved ->
// A new webhook routine stays open: its URL and key exist only now.
editing = if (id.isEmpty() && saved?.hasWebhook == true) saved.id else null
@@ -120,6 +122,7 @@ import kotlinx.coroutines.launch
var error by remember { mutableStateOf<String?>(null) }
var advanced by remember { mutableStateOf(false) }
var confirmDelete by remember { mutableStateOf(false) }
+ var choosingZone by remember { mutableStateOf(false) }
var started by remember { mutableStateOf(false) }
val busy = "routines:$botId" in state.busy
val online = state.actualConnection is LinkState.Ready
@@ -164,15 +167,26 @@ import kotlinx.coroutines.launch
if (!loaded) IconLabel("Loading schedule…", "clock", Palette.secondary, style = Type.body)
else when (draft.schedule.kind) {
"cron" -> Column(verticalArrangement = Arrangement.spacedBy(8.dp)) {
- Field("Cron") {
- FieldBox(draft.schedule.expression, { draft = draft.copy(schedule = draft.schedule.copy(expression = it)) }, "0 9 * * 1-5",
- style = Type.body.monospaced, fill = Palette.bubbleUser, capitalize = false)
+ val schedule = draft.schedule
+ fun change(edit: RoutineScheduleDraft) { draft = draft.copy(schedule = edit) }
+ val current = preview.takeIf { checked == schedule }
+ Field("Repeat") {
+ ChoicePicker(schedule.calendarStyle, routineRepeats, { change(schedule.repeating(it, current?.cronExpression)) }, label = "Repeat")
}
- Field("Time zone") {
- FieldBox(draft.schedule.zone, { draft = draft.copy(schedule = draft.schedule.copy(zone = it)) }, "Asia/Taipei",
- fill = Palette.bubbleUser, capitalize = false)
+ when (schedule.calendarStyle) {
+ "hourly" -> Field("At minute") { ChoicePicker(schedule.minute, MINUTES, { change(schedule.copy(minute = it)) }, label = "At minute") }
+ "daily", "weekdays" -> TimeField(schedule) { change(it) }
+ "weekly" -> {
+ Field("On") { ChoicePicker(schedule.weekday, WEEKDAYS, { change(schedule.copy(weekday = it)) }, label = "On") }
+ TimeField(schedule) { change(it) }
+ }
+ else -> Field("Cron") {
+ FieldBox(schedule.expression, { change(schedule.copy(expression = it)) }, "0 9 * * 1-5",
+ style = Type.body.monospaced, fill = Palette.bubbleUser, capitalize = false)
+ }
}
- SchedulePreview(if (checked == draft.schedule) preview else null, previewError)
+ Field("Time zone") { ZoneButton(schedule.zone) { choosingZone = true } }
+ SchedulePreview(current, previewError, cronHint = schedule.calendarStyle == "custom")
}
"webhook" -> if (routine?.hasWebhook == true) RoutineWebhookPanel(botId, routine.id, online, store)
else Note("Runs each time something is posted to its URL. Save to get the URL and key.")
@@ -186,7 +200,7 @@ import kotlinx.coroutines.launch
Text("Run settings", style = Type.subheadline, color = Palette.secondary)
Symbol("chevron.down", Modifier.rotate(turn), size = 11.dp, tint = Palette.secondary)
Spacer(Modifier.weight(1f))
- if (!advanced) Text("Timeout ${draft.timeoutSeconds}s", style = Type.subheadline, color = Palette.tertiary)
+ if (!advanced) Text("Timeout ${draft.timeoutText}", style = Type.subheadline, color = Palette.tertiary)
}
AnimatedVisibility(advanced, enter = fadeIn(Motion.fade()) + expandVertically(Motion.layoutSize),
exit = fadeOut(Motion.fade()) + shrinkVertically(Motion.layoutSize)) {
@@ -225,10 +239,28 @@ import kotlinx.coroutines.launch
CodyncDialog("Delete routine?", confirmDelete, { confirmDelete = false }, "This deletes the routine and stops its future runs. This can't be undone.") {
listOf(DialogAction("Delete routine", destructive = true) { routine?.let { store.routineAction(botId, it.id, "deleteRoutine") { saved(null) } } })
}
+ CodyncSheet(choosingZone, { choosingZone = false }) {
+ ZonePicker(draft.schedule.zone) { draft = draft.copy(schedule = draft.schedule.copy(zone = it)); choosingZone = false }
+ }
+}
+
+private fun Int.twoDigits() = toString().padStart(2, '0')
+private val HOURS = (0..23).map { it to it.twoDigits() }
+private val MINUTES = (0..59).map { it to it.twoDigits() }
+// Monday first; the host counts 0 = Sunday … 6 = Saturday.
+private val WEEKDAYS = listOf(1 to "Monday", 2 to "Tuesday", 3 to "Wednesday", 4 to "Thursday", 5 to "Friday", 6 to "Saturday", 0 to "Sunday")
+
+/** "At": the hour and minute a daily, weekday or weekly schedule runs. */
+@Composable private fun TimeField(schedule: RoutineScheduleDraft, change: (RoutineScheduleDraft) -> Unit) = Field("At") {
+ Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(6.dp)) {
+ ChoicePicker(schedule.hour, HOURS, { change(schedule.copy(hour = it)) }, label = "Hour")
+ Text(":", style = Type.body, color = Palette.secondary)
+ ChoicePicker(schedule.minute, MINUTES, { change(schedule.copy(minute = it)) }, label = "Minute")
+ }
}
-/** One quiet line under the cron fields: what the host read, or why it can't. */
-@Composable private fun SchedulePreview(preview: RoutineSchedulePreview?, error: String?) {
+/** One quiet line under the schedule fields: what the host read, or why it can't (with the cron fields' order while it checks a Custom one). */
+@Composable private fun SchedulePreview(preview: RoutineSchedulePreview?, error: String?, cronHint: Boolean) {
Column(Modifier.padding(start = 4.dp), verticalArrangement = Arrangement.spacedBy(2.dp)) {
when {
error != null -> Text(error, style = Type.caption, color = Palette.danger)
@@ -237,7 +269,7 @@ import kotlinx.coroutines.launch
preview.nextRunAt?.let { Text("Next ${DateFormat.getDateTimeInstance(DateFormat.MEDIUM, DateFormat.SHORT).format(Date(it))}", style = Type.caption, color = Palette.secondary) }
preview.warning?.let { Text(it, style = Type.caption, color = Palette.secondary) }
}
- else -> Text("minute hour day month weekday", style = Type.caption.monospaced, color = Palette.tertiary)
+ cronHint -> Text("minute hour day month weekday", style = Type.caption.monospaced, color = Palette.tertiary)
}
}
}
diff --git a/apps/android/app/src/main/kotlin/com/codync/android/ZonePicker.kt b/apps/android/app/src/main/kotlin/com/codync/android/ZonePicker.kt
new file mode 100644
index 00000000..e767b736
--- /dev/null
+++ b/apps/android/app/src/main/kotlin/com/codync/android/ZonePicker.kt
@@ -0,0 +1,62 @@
+package com.codync.android
+
+import androidx.compose.foundation.background
+import androidx.compose.foundation.layout.Arrangement
+import androidx.compose.foundation.layout.Column
+import androidx.compose.foundation.layout.PaddingValues
+import androidx.compose.foundation.layout.Row
+import androidx.compose.foundation.layout.fillMaxSize
+import androidx.compose.foundation.layout.fillMaxWidth
+import androidx.compose.foundation.layout.padding
+import androidx.compose.foundation.lazy.LazyColumn
+import androidx.compose.foundation.lazy.items
+import androidx.compose.foundation.selection.selectable
+import androidx.compose.material3.Text
+import androidx.compose.runtime.Composable
+import androidx.compose.runtime.getValue
+import androidx.compose.runtime.mutableStateOf
+import androidx.compose.runtime.remember
+import androidx.compose.runtime.setValue
+import androidx.compose.ui.Alignment
+import androidx.compose.ui.Modifier
+import androidx.compose.ui.draw.clip
+import androidx.compose.ui.graphics.graphicsLayer
+import androidx.compose.ui.semantics.Role
+import androidx.compose.ui.semantics.contentDescription
+import androidx.compose.ui.semantics.semantics
+import androidx.compose.ui.unit.dp
+import com.codync.android.core.TimeZones
+import com.codync.android.design.*
+import com.kyant.shapes.RoundedRectangle
+
+/** The routine's time zone as a field: the zone and its offset; tapping opens `ZonePicker`. */
+@Composable internal fun ZoneButton(zone: String, open: () -> Unit) {
+ Row(Modifier.fillMaxWidth().clip(RoundedRectangle(12.dp)).background(Palette.bubbleUser).plainButton(action = open)
+ .semantics(mergeDescendants = true) { contentDescription = "Time zone: $zone" }.padding(horizontal = 14.dp, vertical = 11.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(8.dp)) {
+ Text(zone.ifEmpty { "Choose" }, Modifier.weight(1f), style = Type.body, color = Palette.text, maxLines = 1)
+ Text(TimeZones.offset(zone), style = Type.body, color = Palette.secondary)
+ Symbol("chevron.right", size = 13.dp, tint = Palette.tertiary)
+ }
+}
+
+/** Every IANA zone with its offset, searched as you type; the chosen one is checked. */
+@Composable internal fun ZonePicker(selection: String, pick: (String) -> Unit) {
+ var query by remember { mutableStateOf("") }
+ val zones = remember(query) { TimeZones.search(query) }
+ Column(Modifier.fillMaxSize().background(Palette.background)) {
+ ModalHeader("Time zone")
+ SearchField(query, { query = it }, Modifier.padding(horizontal = 20.dp), "Search time zones")
+ if (zones.isEmpty()) Text("No time zones match “${query.trim()}”.", Modifier.padding(24.dp), style = Type.body, color = Palette.secondary)
+ LazyColumn(Modifier.fillMaxSize(), contentPadding = PaddingValues(start = 24.dp, end = 24.dp, top = 12.dp, bottom = 36.dp)) {
+ items(zones, key = { it }) { zone ->
+ Row(Modifier.fillMaxWidth().selectable(zone == selection, role = Role.RadioButton) { pick(zone) }.padding(vertical = 11.dp),
+ verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(10.dp)) {
+ Text(zone, Modifier.weight(1f), style = Type.body, color = Palette.text)
+ Text(TimeZones.offset(zone), style = Type.subheadline, color = Palette.secondary)
+ Symbol("checkmark", size = 15.dp, tint = Palette.text, modifier = Modifier.graphicsLayer { alpha = if (zone == selection) 1f else 0f })
+ }
+ }
+ }
+ }
+}
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
index 4acfaedd..27c8358f 100644
--- a/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/Routine.kt
@@ -37,24 +37,61 @@ import kotlinx.serialization.json.*
}
}
+/**
+ * Whether the editor for `id` ("" sets up a new routine) can open: a routine's waits until it's listed,
+ * since a chat link can name one before the first load (or the next poll) and an empty form would save
+ * defaults over it.
+ */
+fun RoutineListing?.canEdit(id: String): Boolean = id.isEmpty() || this?.routines.orEmpty().any { it.id == id }
+
@Serializable data class RoutineScheduleDraft(
val kind: String = "cron", val amount: String = "1", val unit: Long = 3600,
val calendarStyle: String = "daily", val weekday: Int = 1, val selectedDays: List<Int> = emptyList(),
val monthDay: Int = 1, val minuteStep: Int = 15, val hour: Int = 9, val minute: Int = 0,
val at: Long = 0, val expression: String = "", val zone: String = "", val original: List<JsonObject> = emptyList(),
) {
- fun forMobileEditor(): RoutineScheduleDraft = copy(calendarStyle = "custom", kind = if (kind in listOf("cron", "webhook")) kind else "keep")
+ /** The phone edits the `routineRepeats` styles; the host's others open as Custom (the expression already holds their cron). */
+ fun forMobileEditor(): RoutineScheduleDraft = copy(calendarStyle = calendarStyle.takeIf { style -> routineRepeats.any { it.first == style } } ?: "custom",
+ kind = if (kind in listOf("cron", "webhook")) kind else "keep")
+
+ /**
+ * Switches the repeat style; Custom starts from `compiled`, the cron the host made of the current choice,
+ * empty while that check is still out (never the cron the routine opened with).
+ */
+ fun repeating(style: String, compiled: String?): RoutineScheduleDraft = when {
+ style == calendarStyle -> this
+ style == "custom" -> copy(calendarStyle = style, expression = compiled.orEmpty())
+ else -> copy(calendarStyle = style)
+ }
}
+/** The repeat styles the phone offers for a schedule, in menu order. */
+val routineRepeats = listOf("hourly" to "Hourly", "daily" to "Daily", "weekdays" to "Weekdays", "weekly" to "Weekly", "custom" to "Custom")
+
@Serializable data class RoutineSchedulePreview(
val draft: RoutineScheduleDraft, val triggers: List<JsonObject>, val summary: String,
val nextRunAt: Long? = null, val warning: String? = null,
-)
+) {
+ /** The cron the host compiled, when the schedule is one. */
+ val cronExpression: String? get() = triggers.firstOrNull()?.takeIf { it["type"]?.jsonPrimitive?.content == "cron" }
+ ?.get("expression")?.jsonPrimitive?.content
+}
@Serializable data class RoutineWebhook(val url: String? = null, val localUrl: String, val key: String, val connected: Boolean)
data class RoutineDraft(val id: String? = null, val name: String = "", val instruction: String = "",
val schedule: RoutineScheduleDraft = RoutineScheduleDraft(), val timeoutSeconds: String = "3600") {
+ /** The timeout in words: whole hours, else whole minutes, else seconds; anything else as typed. */
+ val timeoutText: String get() {
+ val seconds = timeoutSeconds.toLongOrNull() ?: return "${timeoutSeconds}s"
+ val (amount, unit) = when {
+ seconds > 0 && seconds % 3600 == 0L -> seconds / 3600 to "hour"
+ seconds > 0 && seconds % 60 == 0L -> seconds / 60 to "minute"
+ else -> seconds to "second"
+ }
+ return "$amount $unit${if (amount == 1L) "" else "s"}"
+ }
+
fun body(botId: String): JsonObject = buildJsonObject {
put("botId", botId); id?.let { put("id", it) }; put("name", name); put("instruction", instruction)
put("schedule", WireJson.encodeToJsonElement(schedule)); put("timeoutSeconds", timeoutSeconds)
diff --git a/apps/android/core/src/main/kotlin/com/codync/android/core/TimeZones.kt b/apps/android/core/src/main/kotlin/com/codync/android/core/TimeZones.kt
new file mode 100644
index 00000000..10caf39e
--- /dev/null
+++ b/apps/android/core/src/main/kotlin/com/codync/android/core/TimeZones.kt
@@ -0,0 +1,57 @@
+package com.codync.android.core
+
+import java.time.Instant
+import java.time.ZoneId
+import kotlin.math.abs
+
+/** The IANA zones a routine can run in, and the search over them. */
+object TimeZones {
+ /** Every zone id, sorted. */
+ val ids: List<String> by lazy { iana(ZoneId.getAvailableZoneIds()) }
+
+ /**
+ * Only ids the host's IANA database knows: Android's list adds Java's three-letter aliases
+ * (ACT, AET…) and the retired SystemV zones. EST, MST and HST are IANA zones and stay.
+ */
+ internal fun iana(ids: Collection<String>): List<String> =
+ ids.filter { id -> '/' !in ZoneId.SHORT_IDS[id].orEmpty() && !id.startsWith("SystemV/") }.sorted()
+
+ /** The zone's offset at `now`: "GMT+8", "GMT-3:30", or "GMT"; empty for an unknown zone. */
+ fun offset(id: String, now: Instant = Instant.now()): String {
+ val seconds = runCatching { ZoneId.of(id).rules.getOffset(now).totalSeconds }.getOrElse { return "" }
+ if (seconds == 0) return "GMT"
+ val minutes = abs(seconds) / 60
+ val rest = if (minutes % 60 == 0) "" else ":" + (minutes % 60).toString().padStart(2, '0')
+ return "GMT${if (seconds < 0) "-" else "+"}${minutes / 60}$rest"
+ }
+
+ /**
+ * The zones matching `query`, best first: the id starts with it, then every word starts a word
+ * of the id, then every word is inside it, then its letters appear in order. Case is ignored and
+ * "/", "_" and "-" count as spaces, so "new york" and "asia tai" match.
+ */
+ fun search(query: String, zones: List<String> = ids): List<String> {
+ val words = words(query)
+ if (words.isEmpty()) return zones
+ return zones.mapNotNull { zone -> rank(words(zone), words)?.let { zone to it } }.sortedBy { it.second }.map { it.first }
+ }
+
+ private fun words(text: String) = text.lowercase().split('/', '_', '-', ' ').filter(String::isNotEmpty)
+
+ private fun rank(name: List<String>, words: List<String>): Int? {
+ val joined = name.joinToString(" ")
+ return when {
+ joined.startsWith(words.joinToString(" ")) -> 0
+ words.all { word -> name.any { it.startsWith(word) } } -> 1
+ words.all { it in joined } -> 2
+ inOrder(words.joinToString(""), name.joinToString("")) -> 3
+ else -> null
+ }
+ }
+
+ private fun inOrder(letters: String, text: String): Boolean {
+ var at = 0
+ for (letter in letters) at = text.indexOf(letter, at).takeIf { it >= 0 }?.plus(1) ?: return false
+ return true
+ }
+}
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/RoutineTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/RoutineTest.kt
index 77335fe5..296649f7 100644
--- a/apps/android/core/src/test/kotlin/com/codync/android/core/RoutineTest.kt
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/RoutineTest.kt
@@ -23,6 +23,39 @@ class RoutineTest {
assertEquals(draft.zone, draft.forMobileEditor().zone)
}
+ @Test fun `the phone keeps its five repeat styles and opens the rest as custom`() {
+ for ((style) in routineRepeats) assertEquals(style, RoutineScheduleDraft(calendarStyle = style).forMobileEditor().calendarStyle)
+ for (style in listOf("minutes", "days", "monthly")) assertEquals("custom", RoutineScheduleDraft(calendarStyle = style).forMobileEditor().calendarStyle)
+ }
+
+ @Test fun `switching to custom starts from the cron the host compiled`() {
+ val weekdays = RoutineScheduleDraft(calendarStyle = "weekdays", expression = "0 9 * * *")
+ assertEquals("0 9 * * 1-5", weekdays.repeating("custom", "0 9 * * 1-5").expression)
+ // While the host is still checking the last change, Custom starts empty, not from the cron the routine opened with.
+ assertEquals("", weekdays.repeating("custom", null).expression)
+ assertEquals("0 9 * * *", weekdays.repeating("hourly", "0 9 * * 1-5").expression)
+ val custom = RoutineScheduleDraft(calendarStyle = "custom", expression = "7 9 * * 5")
+ assertEquals(custom, custom.repeating("custom", null))
+ val cron = WireJson.parseToJsonElement("""{"type":"cron","expression":"0 9 * * 1-5","timeZone":"Asia/Taipei"}""").jsonObject
+ assertEquals("0 9 * * 1-5", RoutineSchedulePreview(weekdays, listOf(cron), "").cronExpression)
+ assertNull(RoutineSchedulePreview(weekdays, listOf(buildJsonObject { put("type", "webhook") }), "").cronExpression)
+ }
+
+ @Test fun `a routine's editor waits for the routine to be listed`() {
+ val listing = RoutineListing(listOf(Routine("r", "bot", "Check CI", "Check", emptyList(), false)), emptyList())
+ assertFalse(null.canEdit("r"))
+ assertTrue(listing.canEdit("r"))
+ assertFalse(listing.canEdit("other"))
+ assertTrue(null.canEdit(""))
+ }
+
+ @Test fun `timeout reads as a human duration`() {
+ for ((seconds, text) in listOf("3600" to "1 hour", "7200" to "2 hours", "1800" to "30 minutes", "60" to "1 minute",
+ "90" to "90 seconds", "1" to "1 second", "0" to "0 seconds", "abc" to "abcs")) {
+ assertEquals(text, RoutineDraft(timeoutSeconds = seconds).timeoutText)
+ }
+ }
+
@Test fun `routine status reflects active recovery and failed runs before the schedule`() {
val routine = Routine("r", "b", "Morning", "Report", emptyList(), true, triggerDescriptions = listOf("Every day"))
val failed = RoutineRun("old", "r", "b", "failed")
diff --git a/apps/android/core/src/test/kotlin/com/codync/android/core/TimeZonesTest.kt b/apps/android/core/src/test/kotlin/com/codync/android/core/TimeZonesTest.kt
new file mode 100644
index 00000000..285f1160
--- /dev/null
+++ b/apps/android/core/src/test/kotlin/com/codync/android/core/TimeZonesTest.kt
@@ -0,0 +1,36 @@
+package com.codync.android.core
+
+import java.time.Instant
+import org.junit.Assert.*
+import org.junit.Test
+
+class TimeZonesTest {
+ @Test fun `search ignores case and separators`() {
+ assertEquals("Asia/Taipei", TimeZones.search("TAIPEI").first())
+ assertEquals("Asia/Taipei", TimeZones.search("asia tai").first())
+ assertEquals("America/New_York", TimeZones.search("new york").first())
+ assertEquals("America/Port-au-Prince", TimeZones.search("port au").first())
+ assertTrue("Asia/Taipei" in TimeZones.search("tpe"))
+ assertEquals(TimeZones.ids, TimeZones.search(" "))
+ assertTrue(TimeZones.search("zzzz").isEmpty())
+ }
+
+ @Test fun `prefix matches come before word starts, then anywhere, then letters in order`() {
+ val zones = listOf("Asia/Hind", "America/Indiana", "Indian/Chagos", "Iran/Nod")
+ assertEquals(listOf("Indian/Chagos", "America/Indiana", "Asia/Hind", "Iran/Nod"), TimeZones.search("ind", zones))
+ }
+
+ @Test fun `the list keeps IANA zones and drops Java and SystemV aliases`() {
+ assertEquals(listOf("Asia/Taipei", "EST", "UTC"), TimeZones.iana(listOf("UTC", "ACT", "SystemV/AST4", "EST", "Asia/Taipei", "CTT")))
+ }
+
+ @Test fun `offsets read as GMT hours and minutes`() {
+ val winter = Instant.parse("2026-01-15T00:00:00Z")
+ assertEquals("GMT+8", TimeZones.offset("Asia/Taipei", winter))
+ assertEquals("GMT+5:30", TimeZones.offset("Asia/Kolkata", winter))
+ assertEquals("GMT-3:30", TimeZones.offset("America/St_Johns", winter))
+ assertEquals("GMT-5", TimeZones.offset("America/New_York", winter))
+ assertEquals("GMT", TimeZones.offset("UTC", winter))
+ assertEquals("", TimeZones.offset("Not/AZone", winter))
+ }
+}
diff --git a/apps/desktop/package.json b/apps/desktop/package.json
index 49a65f03..759609a9 100644
--- a/apps/desktop/package.json
+++ b/apps/desktop/package.json
@@ -16,7 +16,7 @@
"build": "electron-vite build",
"build:demo": "vite build --config vite.demo.config.ts && mv ../../web/public/demo/desktop/index.html ../../web/public/demo/desktop.html",
"typecheck": "tsc --noEmit -p tsconfig.json",
- "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/lib/*.test.ts src/renderer/views/thread/*.test.ts",
+ "test": "node --test --experimental-strip-types src/shared/*.test.ts src/renderer/lib/*.test.ts src/renderer/views/thread/*.test.ts src/renderer/views/routines/*.test.ts",
"icons": "swift tools/export-symbols.swift",
"dist:mac:dev": "node tools/account-config.mjs dev && node tools/native-host.mjs dev && node tools/native-screen.mjs dev && electron-vite build && CSC_NAME=\"Pokai Lee (6KFK5J2LB4)\" electron-builder --mac --config tools/dev-builder.cjs",
"dist:mac:main": "node tools/account-config.mjs main && node tools/native-host.mjs main && node tools/native-screen.mjs main && electron-vite build && electron-builder --mac",
diff --git a/apps/desktop/src/renderer/views/routines/RoutineEditorView.tsx b/apps/desktop/src/renderer/views/routines/RoutineEditorView.tsx
index f2599b1f..f1898eca 100644
--- a/apps/desktop/src/renderer/views/routines/RoutineEditorView.tsx
+++ b/apps/desktop/src/renderer/views/routines/RoutineEditorView.tsx
@@ -1,15 +1,19 @@
import { useEffect, useRef, useState } from 'react'
-import { Button, ChoicePicker, IconButton, Spinner } from '../../components/Controls'
+import { Button, CardSection, IconButton, SegmentedChoice, Spinner } from '../../components/Controls'
import { Icon } from '../../components/Icon'
import { Dialog, ModalHeader } from '../../components/Overlay'
import { HStack, Spacer, VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useStore } from '../../store/context'
-import { emptyDraft, errorText, sameDraft, type Routine, type RoutineScheduleDraft, type RoutineSchedulePreview } from './routine'
+import { durationText, emptyDraft, errorText, repeatChoice, sameDraft, type Routine, type RoutineScheduleDraft, type RoutineSchedulePreview } from './routine'
import { Field } from '../bots/parts'
+import { LabeledRow, RoutineScheduleFields } from './RoutineScheduleFields'
import { RoutineWebhookPanel } from './RoutineWebhookPanel'
+import { currentZone } from './time-zones'
import './routines.css'
+const saveShortcut = window.codync.platform === 'darwin' ? '⌘S' : 'Ctrl+S'
+
export function RoutineEditorView({ botId, routine, saved }: {
botId: string
routine: Routine | null
@@ -36,7 +40,7 @@ export function RoutineEditorView({ botId, routine, saved }: {
// Anything the bot set up (a one-off time, an interval, events, several triggers) stays as it is until replaced.
const keepsOriginal = routine ? (routine.triggers.length === 1 ? !['cron', 'webhook'].includes(routine.triggers[0]!.type) : routine.triggers.length > 0) : false
const options = [
- ...(routine && keepsOriginal ? [{ id: 'keep', label: routine.triggerDescriptions.join(' · ') }] : []),
+ ...(keepsOriginal ? [{ id: 'keep', label: 'Set by bot' }] : []),
{ id: 'cron', label: 'Schedule' },
{ id: 'webhook', label: 'Webhook' },
]
@@ -47,9 +51,9 @@ export function RoutineEditorView({ botId, routine, saved }: {
const client = await store.ready()
const result = await client.call<RoutineSchedulePreview>('routineSchedule', {
triggers: routine?.triggers ?? [],
- timeZone: Intl.DateTimeFormat().resolvedOptions().timeZone,
+ timeZone: currentZone(Intl.DateTimeFormat().resolvedOptions().timeZone),
})
- const draft = { ...result.draft, calendarStyle: 'custom' }
+ const draft = { ...result.draft, calendarStyle: repeatChoice(result.draft.calendarStyle) }
if (!['cron', 'webhook'].includes(draft.kind)) draft.kind = 'keep'
setSchedule(draft)
setPreview(result)
@@ -132,60 +136,25 @@ export function RoutineEditorView({ botId, routine, saved }: {
const triggerFields = () => {
switch (schedule.kind) {
case 'cron':
- return (
- <VStack gap={8} className="routine-cron">
- <div className="routine-cron-fields">
- <Field label="Cron">
- <input
- className="routine-input routine-cron-input"
- value={schedule.expression}
- placeholder="0 9 * * 1-5"
- spellCheck={false}
- autoCorrect="off"
- onChange={(e) => update({ expression: e.target.value })}
- />
- </Field>
- <Field label="Time zone">
- <input className="routine-input" value={schedule.zone} placeholder="Asia/Taipei" spellCheck={false} autoCorrect="off" onChange={(e) => update({ zone: e.target.value })} />
- </Field>
- </div>
- <div className="routine-cron-preview">
- {previewError ? (
- <Text size="caption" tone="danger" className="routine-cron-error">{previewError}</Text>
- ) : shownPreview ? (
- <VStack gap={2}>
- <Text size="caption" weight="medium">{shownPreview.summary}</Text>
- {shownPreview.nextRunAt ? (
- <Text size="caption" tone="secondary">
- Next {new Date(shownPreview.nextRunAt).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}
- </Text>
- ) : null}
- {shownPreview.warning ? <Text size="caption" tone="secondary">{shownPreview.warning}</Text> : null}
- </VStack>
- ) : (
- <Text size="caption" mono tone="tertiary" className="routine-cron-hint">minute hour day month weekday</Text>
- )}
- </div>
- </VStack>
- )
+ return <RoutineScheduleFields schedule={schedule} update={update} preview={shownPreview} error={previewError} />
case 'webhook':
return routine && routine.triggers.some((t) => t.type === 'webhook' || t.type === 'event') ? (
<RoutineWebhookPanel botId={botId} routineId={routine.id} />
) : (
- <Text size="caption" tone="secondary" className="routine-caption">Runs each time something is posted to its URL. Save to get the URL and key.</Text>
+ <Note icon="link" title="Runs each time something is posted to its URL." detail="Save to get the URL and key." />
)
default:
- return <Text size="caption" tone="secondary" className="routine-caption">Set up by the bot. Pick Schedule or Webhook to replace it.</Text>
+ return <Note icon="sparkles" title={routine?.triggerDescriptions.join(' · ') ?? ''} detail="Set up by the bot. Pick Schedule or Webhook to replace it." />
}
}
return (
<VStack className="routine-editor">
- <ModalHeader title={routine ? 'Edit routine' : 'Set up a routine'} />
+ <ModalHeader icon={schedule.kind === 'webhook' ? 'link' : 'clock'} title={routine ? 'Edit routine' : 'Set up a routine'} />
{/* The card fits the form; it scrolls only when taller than the window allows. */}
<fieldset className="routine-form" disabled={busy || !loaded}>
<VStack gap={24} className="routine-form-body">
- <VStack gap={14}>
+ <VStack gap={16}>
<Field label="Name">
<input className="routine-input" value={name} placeholder="e.g. Morning summary" onChange={(e) => setName(e.target.value)} />
</Field>
@@ -193,10 +162,11 @@ export function RoutineEditorView({ botId, routine, saved }: {
<textarea className="routine-input" value={instruction} placeholder="Describe what this bot should do each time it runs." onChange={(e) => setInstruction(e.target.value)} />
</Field>
</VStack>
- <VStack gap={14}>
- <Field label="When to run">
- <ChoicePicker selection={schedule.kind} options={options} onChange={(kind) => update({ kind })} fits />
- </Field>
+ <VStack gap={10}>
+ <HStack gap={12}>
+ <Text tone="text" grow>When to run</Text>
+ <SegmentedChoice selection={schedule.kind} options={options} onChange={(kind) => update({ kind })} />
+ </HStack>
{loaded ? (
triggerFields()
) : (
@@ -206,22 +176,24 @@ export function RoutineEditorView({ botId, routine, saved }: {
</HStack>
)}
</VStack>
- <VStack gap={12}>
+ <VStack gap={10}>
<button className="press routine-advanced" aria-expanded={advanced} onClick={() => setAdvanced((a) => !a)}>
Run settings
<span className={`routine-chevron ${advanced ? 'open' : ''}`}>
<Icon name="chevron.down" size={10} weight="semibold" />
</span>
<Spacer />
- {!advanced ? <Text tone="tertiary">Timeout {timeout}s</Text> : null}
+ {!advanced ? <Text tone="tertiary">Timeout {durationText(timeout)}</Text> : null}
</button>
{advanced ? (
- <VStack gap={12} className="routine-fade">
- <Field label="Timeout (seconds)">
- <input className="routine-input" value={timeout} placeholder="3600" onChange={(e) => setTimeoutText(e.target.value)} />
- </Field>
- <Text size="caption" tone="secondary" className="routine-caption">A run is stopped after this long. 1 second to 24 hours.</Text>
- </VStack>
+ <div className="routine-fade">
+ <CardSection footer="A run is stopped after this long. 1 second to 24 hours.">
+ <LabeledRow label="Timeout">
+ <input className="schedule-input routine-timeout" aria-label="Timeout in seconds" value={timeout} placeholder="3600" onChange={(e) => setTimeoutText(e.target.value)} />
+ <Text size="callout" tone="secondary">seconds</Text>
+ </LabeledRow>
+ </CardSection>
+ </div>
) : null}
</VStack>
</VStack>
@@ -251,7 +223,7 @@ export function RoutineEditorView({ botId, routine, saved }: {
Connect to this computer to save your routine.
</HStack>
) : null}
- <HStack gap={16}>
+ <HStack gap={4}>
{routine ? (
<>
<IconButton title="Delete routine" icon="trash" onClick={() => setConfirmDelete(true)} />
@@ -271,9 +243,10 @@ export function RoutineEditorView({ botId, routine, saved }: {
</>
) : null}
<Spacer />
- <Button disabled={!canSave} onClick={() => void save()} title="Save (⌘S)">
+ <Button disabled={!canSave} onClick={() => void save()} title={`Save (${saveShortcut})`}>
{busy ? <Spinner size={12} /> : null}
{busy ? 'Saving…' : routine ? 'Save changes' : 'Create routine'}
+ {busy ? null : <span className="button-shortcut">{saveShortcut}</span>}
</Button>
</HStack>
</VStack>
@@ -302,3 +275,18 @@ export function RoutineEditorView({ botId, routine, saved }: {
</VStack>
)
}
+
+/** A trigger that has no fields here: what it does, and what to do about it. */
+function Note({ icon, title, detail }: { icon: string; title: string; detail: string }) {
+ return (
+ <CardSection>
+ <HStack gap={12} align="flex-start" className="routine-note">
+ <Icon name={icon} size={13} color="var(--secondary)" className="routine-note-icon" />
+ <VStack gap={3}>
+ <Text size="callout" weight="medium" tone="text">{title}</Text>
+ <Text size="callout" tone="secondary">{detail}</Text>
+ </VStack>
+ </HStack>
+ </CardSection>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/routines/RoutineScheduleFields.tsx b/apps/desktop/src/renderer/views/routines/RoutineScheduleFields.tsx
new file mode 100644
index 00000000..1a00f5a4
--- /dev/null
+++ b/apps/desktop/src/renderer/views/routines/RoutineScheduleFields.tsx
@@ -0,0 +1,119 @@
+import type { ReactNode } from 'react'
+import { CardSection, ChipChoice, ChoicePicker } from '../../components/Controls'
+import { HStack, VStack } from '../../components/Stack'
+import { Text } from '../../components/Text'
+import { TimeZonePicker } from './TimeZonePicker'
+import { compiledCron, repeatChoice, repeatChoices, type RepeatChoice, type RoutineScheduleDraft, type RoutineSchedulePreview } from './routine'
+import './routines.css'
+
+const weekdays = [
+ { id: 1, label: 'Mon', title: 'Monday' },
+ { id: 2, label: 'Tue', title: 'Tuesday' },
+ { id: 3, label: 'Wed', title: 'Wednesday' },
+ { id: 4, label: 'Thu', title: 'Thursday' },
+ { id: 5, label: 'Fri', title: 'Friday' },
+ { id: 6, label: 'Sat', title: 'Saturday' },
+ { id: 0, label: 'Sun', title: 'Sunday' },
+]
+const pad = (n: number) => String(n).padStart(2, '0')
+const minutes = Array.from({ length: 60 }, (_, m) => ({ id: m, label: `:${pad(m)}` }))
+
+/**
+ * A schedule's fields in one group (how often, the day and time, the time zone), then what the
+ * host read from them. The host compiles the cron; Custom edits it directly.
+ */
+export function RoutineScheduleFields({ schedule, update, preview, error }: {
+ schedule: RoutineScheduleDraft
+ update: (change: Partial<RoutineScheduleDraft>) => void
+ /** The host's reading of exactly these fields, once it has checked them. */
+ preview: RoutineSchedulePreview | null
+ error: string | null
+}) {
+ const repeat = repeatChoice(schedule.calendarStyle)
+ // Custom starts from the host's cron for the choice it replaces; empty while that check is
+ // still out, never the cron the routine opened with.
+ const choose = (id: RepeatChoice) => {
+ if (id !== repeat) update(id === 'custom' ? { calendarStyle: id, expression: compiledCron(preview) ?? '' } : { calendarStyle: id })
+ }
+
+ return (
+ <CardSection footer={<SchedulePreview preview={preview} error={error} />}>
+ <LabeledRow key="Repeat" label="Repeat">
+ <ChipChoice label="Repeat" selection={repeat} options={repeatChoices} onChange={choose} />
+ </LabeledRow>
+ {repeat === 'weekly' ? (
+ <LabeledRow key="On" label="On">
+ <ChipChoice label="Day" selection={schedule.weekday} options={weekdays} onChange={(weekday) => update({ weekday })} />
+ </LabeledRow>
+ ) : null}
+ {repeat === 'hourly' ? (
+ <LabeledRow key="At minute" label="At minute">
+ <ChoicePicker selection={schedule.minute} options={minutes} onChange={(minute) => update({ minute })} fill="var(--field)" />
+ </LabeledRow>
+ ) : repeat === 'custom' ? (
+ <LabeledRow key="Cron" label="Cron" top>
+ <VStack gap={6} grow>
+ <input
+ className="schedule-input routine-cron-input"
+ aria-label="Cron"
+ value={schedule.expression}
+ placeholder="0 9 * * 1-5"
+ spellCheck={false}
+ autoCorrect="off"
+ onChange={(e) => update({ expression: e.target.value })}
+ />
+ <Text size="caption" mono tone="tertiary" className="routine-cron-hint">minute hour day month weekday</Text>
+ </VStack>
+ </LabeledRow>
+ ) : (
+ <LabeledRow key="At" label="At">
+ <input
+ type="time"
+ className="schedule-input schedule-time"
+ aria-label="Time"
+ value={`${pad(schedule.hour)}:${pad(schedule.minute)}`}
+ onChange={(e) => {
+ const [hour, minute] = e.target.value.split(':').map(Number)
+ if (hour !== undefined && minute !== undefined && !Number.isNaN(hour) && !Number.isNaN(minute)) update({ hour, minute })
+ }}
+ />
+ </LabeledRow>
+ )}
+ <LabeledRow key="Time zone" label="Time zone">
+ <TimeZonePicker zone={schedule.zone} onChange={(zone) => update({ zone })} />
+ </LabeledRow>
+ </CardSection>
+ )
+}
+
+/** A row of the routine editor's groups (`CardSection`): its label in a fixed column, then the field; `top` for a tall one. */
+export function LabeledRow({ label, top = false, className, children }: { label: string; top?: boolean; className?: string; children: ReactNode }) {
+ return (
+ <HStack align={top ? 'flex-start' : 'center'} className={`labeled-row${top ? ' top' : ''}${className ? ` ${className}` : ''}`}>
+ <Text size="callout" weight="medium" tone="secondary" className="labeled-row-label">{label}</Text>
+ {children}
+ </HStack>
+ )
+}
+
+/** One quiet line under the group: what the host read, or why it can't. */
+function SchedulePreview({ preview, error }: { preview: RoutineSchedulePreview | null; error: string | null }) {
+ if (error) return <Text size="callout" tone="danger" className="schedule-preview">{error}</Text>
+ return (
+ <VStack gap={2} className="schedule-preview" aria-live="polite">
+ {preview ? (
+ <>
+ <HStack gap={8} wrap>
+ <Text size="callout" weight="medium" tone="text">{preview.summary}</Text>
+ {preview.nextRunAt ? (
+ <Text size="callout" tone="secondary">
+ Next {new Date(preview.nextRunAt).toLocaleString(undefined, { dateStyle: 'medium', timeStyle: 'short' })}
+ </Text>
+ ) : null}
+ </HStack>
+ {preview.warning ? <Text size="callout" tone="secondary">{preview.warning}</Text> : null}
+ </>
+ ) : null}
+ </VStack>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx b/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx
index 2dd3d55c..c1c10ceb 100644
--- a/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx
+++ b/apps/desktop/src/renderer/views/routines/RoutineWebhookPanel.tsx
@@ -1,11 +1,11 @@
import { useEffect, useState, type ReactNode } from 'react'
-import { IconButton } from '../../components/Controls'
+import { CardSection, IconButton } from '../../components/Controls'
import { Dialog } from '../../components/Overlay'
-import { HStack, VStack } from '../../components/Stack'
+import { VStack } from '../../components/Stack'
import { Text } from '../../components/Text'
import { useStore } from '../../store/context'
-import { Field } from '../bots/parts'
import { errorText, type RoutineWebhook } from './routine'
+import { LabeledRow } from './RoutineScheduleFields'
import './routines.css'
/** A saved webhook routine's address and key: copy either, reveal or replace the key. */
@@ -39,8 +39,8 @@ export function RoutineWebhookPanel({ botId, routineId }: { botId: string; routi
void load(false)
}, [routineId])
- const value = (text: string, copy: 'url' | 'key', extra?: ReactNode) => (
- <HStack gap={8} className="routine-webhook-value">
+ const row = (label: string, text: string, copy: 'url' | 'key', extra?: ReactNode) => (
+ <LabeledRow label={label} className="webhook-row">
<Text size="callout" mono lines={2} grow className="routine-webhook-text">
{text}
</Text>
@@ -54,31 +54,31 @@ export function RoutineWebhookPanel({ botId, routineId }: { botId: string; routi
setCopied(copy)
}}
/>
- </HStack>
+ </LabeledRow>
)
return (
- <VStack gap={14}>
+ <VStack gap={10}>
{webhook ? (
- <>
- <Field label={webhook.url ? 'URL' : 'Local URL'}>{value(webhook.url ?? webhook.localUrl, 'url')}</Field>
- <Field label="Key">
- {value(
- showKey ? webhook.key : '•'.repeat(16),
- 'key',
- <>
- <IconButton title={showKey ? 'Hide key' : 'Show key'} icon={showKey ? 'eye.slash' : 'eye'} onClick={() => setShowKey((s) => !s)} />
- <IconButton title="Replace key" icon="arrow.triangle.2.circlepath" disabled={rotating || store.isOffline} onClick={() => setConfirmRotate(true)} />
- </>,
- )}
- </Field>
- <Text size="caption" tone="secondary" className="routine-caption">
- {webhook.url
+ <CardSection
+ footer={
+ webhook.url
? 'POST with Authorization: Bearer <key>. For GitHub, use content type application/json and the key as the secret. ' +
'Deliveries wait up to 72 hours while this computer is off. They pass through the Codync cloud, which can read them.'
- : 'The Codync cloud is off, so only this computer can send to it.'}
- </Text>
- </>
+ : 'The Codync cloud is off, so only this computer can send to it.'
+ }
+ >
+ {row(webhook.url ? 'URL' : 'Local URL', webhook.url ?? webhook.localUrl, 'url')}
+ {row(
+ 'Key',
+ showKey ? webhook.key : '•'.repeat(16),
+ 'key',
+ <>
+ <IconButton title={showKey ? 'Hide key' : 'Show key'} icon={showKey ? 'eye.slash' : 'eye'} onClick={() => setShowKey((s) => !s)} />
+ <IconButton title="Replace key" icon="arrow.triangle.2.circlepath" disabled={rotating || store.isOffline} onClick={() => setConfirmRotate(true)} />
+ </>,
+ )}
+ </CardSection>
) : error ? (
<Text size="caption" tone="danger" className="routine-caption">{error}</Text>
) : (
diff --git a/apps/desktop/src/renderer/views/routines/TimeZonePicker.tsx b/apps/desktop/src/renderer/views/routines/TimeZonePicker.tsx
new file mode 100644
index 00000000..76c20737
--- /dev/null
+++ b/apps/desktop/src/renderer/views/routines/TimeZonePicker.tsx
@@ -0,0 +1,99 @@
+import { useEffect, useMemo, useRef, useState } from 'react'
+import { SearchField } from '../../components/Controls'
+import { Icon } from '../../components/Icon'
+import { Text } from '../../components/Text'
+import { AnchoredPanel } from '../bots/parts'
+import { currentZone, matchZones, timeZoneOptions, zoneLabel, zoneOffset } from './time-zones'
+import './routines.css'
+
+/** The routine's time zone: a button that opens every zone, filtered as you type. */
+export function TimeZonePicker({ zone: saved, onChange }: { zone: string; onChange: (zone: string) => void }) {
+ const zone = currentZone(saved)
+ const anchor = useRef<HTMLButtonElement>(null)
+ const [open, setOpen] = useState(false)
+ return (
+ <>
+ <button
+ ref={anchor}
+ className="schedule-input zone-button"
+ aria-label={`Time zone, ${zone}`}
+ aria-haspopup="listbox"
+ aria-expanded={open}
+ onClick={() => setOpen(true)}
+ >
+ <Text truncate grow>{zoneLabel(zone)}</Text>
+ <Text tone="secondary">{zoneOffset(zone)}</Text>
+ <Icon name="chevron.up.chevron.down" size={10} weight="semibold" color="var(--secondary)" />
+ </button>
+ <AnchoredPanel open={open} onClose={() => setOpen(false)} anchor={anchor}>
+ <ZoneList
+ zone={zone}
+ pick={(picked) => {
+ setOpen(false)
+ onChange(picked)
+ }}
+ />
+ </AnchoredPanel>
+ </>
+ )
+}
+
+/** The search box over the matching zones; ↑/↓ move, Return picks. */
+function ZoneList({ zone, pick }: { zone: string; pick: (zone: string) => void }) {
+ const zones = useMemo(() => timeZoneOptions(), [])
+ const [query, setQuery] = useState('')
+ const matches = useMemo(() => matchZones(zones, query), [zones, query])
+ const [highlight, setHighlight] = useState(() => Math.max(0, zones.findIndex((z) => z.id === zone)))
+ const input = useRef<HTMLInputElement>(null)
+ const list = useRef<HTMLDivElement>(null)
+
+ useEffect(() => input.current?.focus(), [])
+ useEffect(() => {
+ list.current?.querySelector(`[data-index="${highlight}"]`)?.scrollIntoView({ block: 'nearest' })
+ }, [highlight, matches])
+
+ return (
+ <div
+ className="zone-picker"
+ onKeyDown={(e) => {
+ if (e.key === 'ArrowDown' || e.key === 'ArrowUp') {
+ e.preventDefault()
+ setHighlight((h) => Math.min(Math.max(h + (e.key === 'ArrowDown' ? 1 : -1), 0), matches.length - 1))
+ } else if (e.key === 'Enter' && matches[highlight]) {
+ e.preventDefault()
+ pick(matches[highlight].id)
+ }
+ }}
+ >
+ <SearchField
+ value={query}
+ prompt="Search time zones"
+ inputRef={input}
+ onChange={(q) => {
+ setQuery(q)
+ setHighlight(0)
+ }}
+ />
+ <div ref={list} className="zone-list" role="listbox" aria-label="Time zones">
+ {matches.map((z, i) => (
+ <button
+ key={z.id}
+ data-index={i}
+ role="option"
+ aria-selected={z.id === zone}
+ className={`menu-row${i === highlight ? ' highlight' : ''}`}
+ onMouseEnter={() => setHighlight(i)}
+ onClick={() => pick(z.id)}
+ >
+ <Text truncate grow>{zoneLabel(z.id)}</Text>
+ <Text size="caption" tone="secondary">{z.offset}</Text>
+ <span className={`check-slot${z.id === zone ? ' on' : ''}`}>
+ <Icon name="checkmark" size={10} weight="semibold" />
+ </span>
+ </button>
+ ))}
+ {matches.length === 0 ? <Text size="callout" tone="secondary" className="zone-empty">No time zone matches “{query}”.</Text> : null}
+ </div>
+ </div>
+ )
+}
diff --git a/apps/desktop/src/renderer/views/routines/routine.test.ts b/apps/desktop/src/renderer/views/routines/routine.test.ts
new file mode 100644
index 00000000..c4285399
--- /dev/null
+++ b/apps/desktop/src/renderer/views/routines/routine.test.ts
@@ -0,0 +1,56 @@
+import assert from 'node:assert/strict'
+import { test } from 'node:test'
+import { compiledCron, durationText, repeatChoice, type RoutineSchedulePreview } from './routine.ts'
+import { matchZones, timeZoneOptions, zoneOffset } from './time-zones.ts'
+
+test('time zones match like the phones: name start, word starts, inside, letters in order', () => {
+ const zones = timeZoneOptions(new Date('2026-01-15T00:00:00Z'))
+ const ids = (query: string) => matchZones(zones, query).map((z) => z.id)
+ assert.equal(ids('taipei')[0], 'Asia/Taipei')
+ assert.equal(ids('new york')[0], 'America/New_York')
+ assert.equal(ids('asia tai')[0], 'Asia/Taipei')
+ assert.ok(ids('aipe').includes('Asia/Taipei'))
+ assert.ok(ids('tpe').includes('Asia/Taipei'))
+ // Name start, then word starts, then inside a word, then letters in order; ties keep list order.
+ const few = [{ id: 'America/New_York', offset: '' }, { id: 'Asia/Taipei', offset: '' }, { id: 'Asia/Tokyo', offset: '' }, { id: 'America/Argentina/Buenos_Aires', offset: '' }]
+ assert.deepEqual(matchZones(few, 'a').map((z) => z.id), ['America/New_York', 'Asia/Taipei', 'Asia/Tokyo', 'America/Argentina/Buenos_Aires'])
+ assert.deepEqual(matchZones(few, 'ai').map((z) => z.id), ['America/Argentina/Buenos_Aires', 'Asia/Taipei', 'America/New_York', 'Asia/Tokyo'])
+ assert.deepEqual(matchZones(few, 'nyk').map((z) => z.id), ['America/New_York'])
+ assert.ok(ids('utc').includes('UTC'))
+ assert.deepEqual(ids('nowhere-at-all'), [])
+ // ICU's retired names are listed by their current ones.
+ assert.equal(ids('kolkata')[0], 'Asia/Kolkata')
+ assert.equal(ids('kyiv')[0], 'Europe/Kyiv')
+ assert.ok(!zones.some((z) => z.id === 'Asia/Calcutta'))
+ assert.equal(ids('').length, zones.length)
+})
+
+test('a zone shows its offset right now', () => {
+ assert.equal(zoneOffset('Asia/Taipei', new Date('2026-01-15T00:00:00Z')), 'GMT+8')
+ assert.equal(zoneOffset('America/New_York', new Date('2026-07-15T00:00:00Z')), 'GMT-4')
+ assert.equal(zoneOffset('Not/A_Zone'), '')
+})
+
+test('a timeout reads in the largest whole unit', () => {
+ assert.equal(durationText('3600'), '1 hour')
+ assert.equal(durationText('7200'), '2 hours')
+ assert.equal(durationText('1800'), '30 minutes')
+ assert.equal(durationText('60'), '1 minute')
+ assert.equal(durationText('90'), '90 seconds')
+ assert.equal(durationText('1'), '1 second')
+ assert.equal(durationText('abc'), 'abcs')
+ assert.equal(durationText('0'), '0s')
+})
+
+test('styles the editor has no choice for open as Custom', () => {
+ assert.equal(repeatChoice('weekdays'), 'weekdays')
+ assert.equal(repeatChoice('hourly'), 'hourly')
+ for (const style of ['minutes', 'days', 'monthly', 'custom']) assert.equal(repeatChoice(style), 'custom')
+})
+
+test('Custom starts from the cron the host compiled', () => {
+ const preview = (triggers: RoutineSchedulePreview['triggers']) => ({ triggers }) as RoutineSchedulePreview
+ assert.equal(compiledCron(preview([{ type: 'cron', expression: '0 9 * * 1-5', timeZone: 'Asia/Taipei' }])), '0 9 * * 1-5')
+ assert.equal(compiledCron(preview([{ type: 'webhook' }])), null)
+ assert.equal(compiledCron(null), null)
+})
diff --git a/apps/desktop/src/renderer/views/routines/routine.ts b/apps/desktop/src/renderer/views/routines/routine.ts
index a7a81c5a..fa899242 100644
--- a/apps/desktop/src/renderer/views/routines/routine.ts
+++ b/apps/desktop/src/renderer/views/routines/routine.ts
@@ -98,4 +98,37 @@ export interface RoutineSchedulePreview {
warning?: string | null
}
+/**
+ * The Repeat choices: the host's calendar styles the editor offers. A schedule in any other
+ * style (every few minutes, several days, monthly) opens as Custom, its cron as written.
+ */
+export const repeatChoices = [
+ { id: 'hourly', label: 'Hourly' },
+ { id: 'daily', label: 'Daily' },
+ { id: 'weekdays', label: 'Weekdays' },
+ { id: 'weekly', label: 'Weekly' },
+ { id: 'custom', label: 'Custom' },
+] as const
+
+export type RepeatChoice = (typeof repeatChoices)[number]['id']
+
+export const repeatChoice = (style: string): RepeatChoice => repeatChoices.find((c) => c.id === style)?.id ?? 'custom'
+
+/** The cron the host compiled for a checked schedule, to start Custom from the same times. */
+export const compiledCron = (preview: RoutineSchedulePreview | null) => {
+ const [trigger] = preview?.triggers ?? []
+ return trigger?.type === 'cron' ? (trigger.expression ?? null) : null
+}
+
+/** A timeout in seconds as people say it ("1 hour", "30 minutes", "90 seconds"); other text as typed. */
+export function durationText(text: string) {
+ const value = text.trim()
+ if (!/^\d+$/.test(value) || Number(value) === 0) return `${value}s`
+ const seconds = Number(value)
+ const count = (amount: number, unit: string) => `${amount} ${unit}${amount === 1 ? '' : 's'}`
+ if (seconds % 3600 === 0) return count(seconds / 3600, 'hour')
+ if (seconds % 60 === 0) return count(seconds / 60, 'minute')
+ return count(seconds, 'second')
+}
+
export const errorText = (e: unknown) => (e instanceof Error ? e.message : String(e))
diff --git a/apps/desktop/src/renderer/views/routines/routines.css b/apps/desktop/src/renderer/views/routines/routines.css
index 2a2d5850..a095c894 100644
--- a/apps/desktop/src/renderer/views/routines/routines.css
+++ b/apps/desktop/src/renderer/views/routines/routines.css
@@ -1,31 +1,44 @@
-/* A routine form's text field: plain, filled, rounded (kit `routineInput`). */
-.routine-input {
- width: 100%;
- padding: 12px;
+/* A routine form's text fields: plain, filled, rounded (kit `routineInput`); the schedule's
+ fields are the same, smaller, inside their rows. */
+.routine-input,
+.schedule-input {
+ padding: 9px 12px;
border: none;
outline: none;
- border-radius: var(--radius-m);
+ border-radius: var(--radius-s);
background: var(--bubble-user);
color: var(--text);
font: inherit;
user-select: text;
resize: none;
}
-.routine-input:focus {
- outline: 2px solid var(--secondary);
+.routine-input {
+ width: 100%;
+}
+.schedule-input {
+ padding: 5px 10px;
+ border-radius: var(--radius-xs);
+}
+.routine-input:focus,
+.schedule-input:focus {
+ outline: 2px solid rgba(var(--text-rgb), 0.3);
}
-.routine-input::placeholder {
+.routine-input::placeholder,
+.schedule-input::placeholder {
color: var(--secondary);
}
textarea.routine-input {
field-sizing: content;
- min-height: calc(3lh + 24px);
- max-height: calc(8lh + 24px);
+ line-height: 1.4;
+ min-height: calc(3lh + 18px);
+ max-height: calc(8lh + 18px);
}
.routine-cron-input {
+ width: 100%;
font-size: var(--text-body);
font-weight: 400;
font-family: var(--mono);
+ word-spacing: 0.3em;
}
/* A routine's editor (RoutineEditorView): the card fits the form. */
@@ -46,12 +59,12 @@ textarea.routine-input {
padding: 0;
min-width: 0;
}
-.routine-form-body,
-.routine-editor-footer {
- padding: 20px;
+.routine-form-body {
+ padding: 12px 20px 8px;
}
.routine-editor-footer {
flex: none;
+ padding: 16px 20px 20px;
}
.routine-caption {
padding-left: 4px;
@@ -66,9 +79,13 @@ textarea.routine-input {
gap: 6px;
width: 100%;
padding-left: 4px;
- font-size: var(--text-caption);
- font-weight: 400;
+ font-size: var(--text-callout);
+ font-weight: 500;
color: var(--secondary);
+ transition: color var(--hover);
+}
+.routine-advanced:hover {
+ color: var(--text);
}
.routine-chevron {
display: flex;
@@ -98,51 +115,97 @@ textarea.routine-input {
opacity: 0.6;
}
-/* Cron and time zone side by side, stacked when the card is narrow. */
-.routine-cron {
- container-type: inline-size;
+/* The editor's groups (CardSection, LabeledRow): denser rows, labels in one column. */
+.routine-form .card-row {
+ min-height: 48px;
+ padding: 6px 16px;
}
-.routine-cron-fields {
- display: flex;
- align-items: flex-start;
- gap: 10px;
+.labeled-row {
+ gap: 12px;
}
-.routine-cron-fields > :first-child {
- flex: 1;
- min-width: 220px;
+.labeled-row.top {
+ padding: 4px 0;
+}
+.labeled-row.top > .labeled-row-label {
+ padding-top: 5px;
}
-.routine-cron-fields > :last-child {
- width: 170px;
+.labeled-row-label {
+ width: 76px;
flex: none;
}
-/* The schedule check under the fields. */
-.routine-cron-preview {
- padding-left: 4px;
+.schedule-time {
+ font-variant-numeric: tabular-nums;
}
-.routine-cron-error {
- line-height: 1.4;
+.schedule-time::-webkit-calendar-picker-indicator {
+ display: none;
+}
+/* The time zone: a button with the zone and its offset, opening a searchable list. */
+.zone-button {
+ display: flex;
+ align-items: center;
+ gap: 8px;
+ width: 240px;
+ max-width: 100%;
+ text-align: left;
+ transition: background-color var(--hover);
+}
+.zone-button:hover {
+ background: rgba(var(--text-rgb), 0.11);
+}
+.zone-picker {
+ width: 300px;
+ padding: 8px;
+ display: flex;
+ flex-direction: column;
+ gap: 6px;
+ font-size: var(--text-callout);
+}
+.zone-list {
+ max-height: 280px;
+ overflow-y: auto;
+ display: flex;
+ flex-direction: column;
+ gap: 2px;
+}
+.zone-empty {
+ padding: 10px;
+}
+/* A menu's panel shares the search box's fill, so the box takes the field's. */
+.zone-picker .search-field {
+ background: var(--field);
+}
+.zone-picker .search-field:focus-within {
+ outline: none;
+}
+.routine-timeout {
+ width: 80px;
+ text-align: right;
+ font-variant-numeric: tabular-nums;
}
.routine-cron-hint {
white-space: pre;
+ padding-left: 10px;
}
-@container (max-width: 400px) {
- .routine-cron-fields {
- flex-direction: column;
- align-items: stretch;
- gap: 14px;
- }
- .routine-cron-fields > :first-child,
- .routine-cron-fields > :last-child {
- width: auto;
- min-width: 0;
- }
+/* What the host read from the schedule, under the group. */
+.schedule-preview {
+ min-height: 1.3em;
+}
+/* A trigger with no fields here (a new webhook, one the bot set up). */
+.routine-note {
+ padding: 8px 0;
+ line-height: 1.4;
+}
+.routine-note-icon {
+ margin-top: 2px;
}
-/* A webhook's URL or key with its actions (RoutineWebhookPanel). */
-.routine-webhook-value {
- padding: 8px 6px 8px 12px;
- background: var(--bubble-user);
- border-radius: var(--radius-m);
+/* A webhook's URL or key with its actions (RoutineWebhookPanel): the buttons sit closer to the edge. */
+.webhook-row {
+ gap: 6px;
+ margin-right: -8px;
+}
+.webhook-row > .labeled-row-label {
+ width: 70px;
}
.routine-webhook-text {
user-select: text;
diff --git a/apps/desktop/src/renderer/views/routines/time-zones.ts b/apps/desktop/src/renderer/views/routines/time-zones.ts
new file mode 100644
index 00000000..93d02625
--- /dev/null
+++ b/apps/desktop/src/renderer/views/routines/time-zones.ts
@@ -0,0 +1,83 @@
+// Time zones for the routine editor's picker: every IANA zone the runtime knows, each with its
+// offset right now, and a forgiving match on what's typed.
+
+export interface TimeZoneOption {
+ id: string
+ /** "GMT+8", "GMT-4:30", "GMT" */
+ offset: string
+}
+
+/** A zone's offset from UTC right now, as the runtime names it ("GMT+8"); empty for an unknown zone. */
+export function zoneOffset(zone: string, now = new Date()) {
+ try {
+ const parts = new Intl.DateTimeFormat('en-US', { timeZone: zone, timeZoneName: 'shortOffset' }).formatToParts(now)
+ return parts.find((p) => p.type === 'timeZoneName')?.value ?? ''
+ } catch {
+ return ''
+ }
+}
+
+// ICU (Chromium, Node) still lists these zones by retired names; IANA, the host and the phones
+// use the current ones.
+const renamed: Record<string, string> = {
+ 'Africa/Asmera': 'Africa/Asmara',
+ 'America/Buenos_Aires': 'America/Argentina/Buenos_Aires',
+ 'America/Catamarca': 'America/Argentina/Catamarca',
+ 'America/Coral_Harbour': 'America/Atikokan',
+ 'America/Cordoba': 'America/Argentina/Cordoba',
+ 'America/Godthab': 'America/Nuuk',
+ 'America/Indianapolis': 'America/Indiana/Indianapolis',
+ 'America/Jujuy': 'America/Argentina/Jujuy',
+ 'America/Louisville': 'America/Kentucky/Louisville',
+ 'America/Mendoza': 'America/Argentina/Mendoza',
+ 'Asia/Calcutta': 'Asia/Kolkata',
+ 'Asia/Katmandu': 'Asia/Kathmandu',
+ 'Asia/Rangoon': 'Asia/Yangon',
+ 'Asia/Saigon': 'Asia/Ho_Chi_Minh',
+ 'Atlantic/Faeroe': 'Atlantic/Faroe',
+ 'Europe/Kiev': 'Europe/Kyiv',
+ 'Pacific/Enderbury': 'Pacific/Kanton',
+ 'Pacific/Ponape': 'Pacific/Pohnpei',
+ 'Pacific/Truk': 'Pacific/Chuuk',
+}
+
+/** A zone by its current IANA name ("Asia/Calcutta" → "Asia/Kolkata"). */
+export const currentZone = (id: string) => renamed[id] ?? id
+
+export const timeZoneOptions = (now = new Date()): TimeZoneOption[] =>
+ ['UTC', ...[...new Set(Intl.supportedValuesOf('timeZone').map(currentZone))].sort()].map((id) => ({ id, offset: zoneOffset(id, now) }))
+
+/** "America/Argentina/Buenos_Aires" → "America/Argentina/Buenos Aires" */
+export const zoneLabel = (id: string) => id.replaceAll('_', ' ')
+
+const words = (text: string) => text.toLowerCase().split(/[\s/_-]+/).filter(Boolean)
+
+/** How well a zone's words match the typed ones (lower is better), or null when they don't. */
+function rank(name: string[], typed: string[]): number | null {
+ const joined = name.join(' ')
+ if (joined.startsWith(typed.join(' '))) return 0
+ if (typed.every((word) => name.some((part) => part.startsWith(word)))) return 1
+ if (typed.every((word) => joined.includes(word))) return 2
+ let at = 0
+ const letters = name.join('')
+ for (const letter of typed.join('')) {
+ at = letters.indexOf(letter, at) + 1
+ if (at === 0) return null
+ }
+ return 3
+}
+
+/**
+ * The zones matching what's typed, best first (as on the phones): the name starts with it, then
+ * every typed word starts a word ("new york", "asia tai"), then every word is inside it ("aipe"),
+ * then its letters appear in order ("tpe"). Ties keep their order.
+ */
+export function matchZones(zones: TimeZoneOption[], query: string) {
+ const typed = words(query)
+ if (!typed.length) return zones
+ return zones
+ .map((zone) => [zone, rank(words(zone.id), typed)] as const)
+ .filter((match): match is readonly [TimeZoneOption, number] => match[1] !== null)
+ .sort((a, b) => a[1] - b[1])
+ .map(([zone]) => zone)
+}
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift b/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift
index e067544a..0314af86 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/Routine.swift
@@ -13,6 +13,20 @@ public struct Routine: Codable, Identifiable, Hashable, Sendable {
public var nextRunAt: Int64?
public var timeoutSeconds: Int?
public var lastError: String?
+
+ /// A timeout as typed, in words: whole hours, else whole minutes, else seconds; anything else as typed.
+ public static func timeoutText(_ text: String) -> String {
+ guard let seconds = Int(text), seconds >= 0 else { return "\(text)s" }
+ let unit: Duration.UnitsFormatStyle.Unit
+ if seconds > 0, seconds % 3600 == 0 {
+ unit = .hours
+ } else if seconds > 0, seconds % 60 == 0 {
+ unit = .minutes
+ } else {
+ unit = .seconds
+ }
+ return Duration.seconds(seconds).formatted(.units(allowed: [unit], width: .wide))
+ }
}
public struct RoutineTrigger: Codable, Hashable, Sendable {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift b/apps/ios/Kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift
index 331bcf05..b09c4c0d 100644
--- a/apps/ios/Kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/RoutineScheduleDraft.swift
@@ -24,6 +24,41 @@ public struct RoutineScheduleDraft: Codable, Hashable, Sendable {
get { Date(timeIntervalSince1970: Double(at) / 1000) }
set { at = Int64((newValue.timeIntervalSince1970 * 1000).rounded()) }
}
+
+ /// `hour` and `minute` as a time-of-day Date for a DatePicker shown in GMT
+ /// (`.environment(\.timeZone, .gmt)`), so no offset or daylight saving shifts them.
+ public var timeOfDay: Date {
+ get { Date(timeIntervalSinceReferenceDate: TimeInterval(hour * 3600 + minute * 60)) }
+ set {
+ let seconds = Int(newValue.timeIntervalSinceReferenceDate.rounded(.down)) % 86_400
+ let day = seconds < 0 ? seconds + 86_400 : seconds
+ hour = day / 3600
+ minute = day % 3600 / 60
+ }
+ }
+
+ /// The Repeat choices the phone offers for a schedule, in menu order.
+ public static let repeatChoices = [("hourly", "Hourly"), ("daily", "Daily"), ("weekdays", "Weekdays"),
+ ("weekly", "Weekly"), ("custom", "Custom")].map { (id: $0.0, label: $0.1) }
+
+ /// The phone edits the `repeatChoices` styles; the host's others (every N minutes, some days, monthly)
+ /// open as Custom, whose expression already holds their cron. A trigger it has no fields for is kept.
+ public func forMobileEditor() -> Self {
+ var draft = self
+ if !Self.repeatChoices.contains(where: { $0.id == calendarStyle }) { draft.calendarStyle = "custom" }
+ if !["cron", "webhook"].contains(kind) { draft.kind = "keep" }
+ return draft
+ }
+
+ /// Switches the repeat style; Custom starts from `compiled`, the cron the host made of the current
+ /// choice, empty while that check is still out (never the cron the routine opened with).
+ public func repeating(_ style: String, compiled: String?) -> Self {
+ guard style != calendarStyle else { return self }
+ var draft = self
+ draft.calendarStyle = style
+ if style == "custom" { draft.expression = compiled ?? "" }
+ return draft
+ }
}
public struct RoutineSchedulePreview: Codable, Sendable {
@@ -32,6 +67,11 @@ public struct RoutineSchedulePreview: Codable, Sendable {
public var summary: String
public var nextRunAt: Int64?
public var warning: String?
+
+ /// The cron the host compiled, when the schedule is one.
+ public var cronExpression: String? {
+ triggers.first.flatMap { $0.type == "cron" ? $0.expression : nil }
+ }
}
extension HostClient {
diff --git a/apps/ios/Kit/Sources/CodyncKit/Models/TimeZones.swift b/apps/ios/Kit/Sources/CodyncKit/Models/TimeZones.swift
new file mode 100644
index 00000000..553a715f
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncKit/Models/TimeZones.swift
@@ -0,0 +1,37 @@
+import Foundation
+
+/// The IANA zones a routine can run in, and the search over them.
+public enum TimeZones {
+ /// "GMT+8", "GMT-4", "GMT+5:30" right now; empty for an unknown zone.
+ public static func offset(_ zone: String) -> String {
+ guard let timeZone = TimeZone(identifier: zone) else { return "" }
+ return Date.now.formatted(Date.FormatStyle(timeZone: timeZone).timeZone(.localizedGMT(.short)))
+ }
+
+ /// Zones matching the query, best first: the name starts with it, then each word starts a word,
+ /// then each word appears somewhere, then its letters appear in order. "/", "_" and "-" count as spaces.
+ public static func search(_ query: String, in zones: [String] = TimeZone.knownTimeZoneIdentifiers) -> [String] {
+ let wanted = words(query)
+ guard !wanted.isEmpty else { return zones }
+ return zones.compactMap { zone in rank(words(zone), wanted).map { (rank: $0, zone: zone) } }
+ .sorted { ($0.rank, $0.zone) < ($1.rank, $1.zone) }
+ .map(\.zone)
+ }
+
+ private static func words(_ text: String) -> [String] {
+ text.lowercased().split { " /_-".contains($0) }.map(String.init)
+ }
+
+ private static func rank(_ name: [String], _ query: [String]) -> Int? {
+ let spaced = name.joined(separator: " ")
+ if spaced.hasPrefix(query.joined(separator: " ")) { return 0 }
+ if query.allSatisfy({ word in name.contains { $0.hasPrefix(word) } }) { return 1 }
+ if query.allSatisfy({ spaced.contains($0) }) { return 2 }
+ var rest = Substring(name.joined())
+ for letter in query.joined() {
+ guard let found = rest.firstIndex(of: letter) else { return nil }
+ rest = rest[rest.index(after: found)...]
+ }
+ return 3
+ }
+}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineEditorView.swift b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineEditorView.swift
index 24efcdfb..e81b2dd9 100644
--- a/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineEditorView.swift
+++ b/apps/ios/Kit/Sources/CodyncUI/Routines/RoutineEditorView.swift
@@ -21,6 +21,7 @@ struct RoutineEditorView: View {
@State private var checkedSchedule: RoutineScheduleDraft?
@State private var confirmDelete = false
@State private var started = false
+ @State private var pickingZone = false
/// Any text field is being edited; cleared on save so nothing sits under the keyboard.
@FocusState private var typing: Bool
@@ -68,6 +69,12 @@ struct RoutineEditorView: View {
}
}]
}
+ .codyncSheet(isPresented: $pickingZone) {
+ TimeZonePicker(selection: schedule.zone) {
+ schedule.zone = $0
+ pickingZone = false
+ }
+ }
.task {
if let routine {
name = routine.name
@@ -111,7 +118,7 @@ struct RoutineEditorView: View {
Image(systemName: "chevron.down").font(.caption2.weight(.semibold))
.rotationEffect(.degrees(advanced ? 180 : 0))
Spacer()
- if !advanced { Text("Timeout \(timeout)s").foregroundStyle(Palette.tertiary) }
+ if !advanced { Text("Timeout \(Routine.timeoutText(timeout))").foregroundStyle(Palette.tertiary) }
}
.font(.subheadline)
.foregroundStyle(Palette.secondary)
@@ -153,9 +160,7 @@ struct RoutineEditorView: View {
guard let client = model.client else { error = "Connect to this computer to load the schedule."; return }
do {
let result = try await client.routineSchedule(triggers: routine?.triggers ?? [], timeZone: TimeZone.current.identifier)
- schedule = result.draft
- schedule.calendarStyle = "custom"
- if !["cron", "webhook"].contains(schedule.kind) { schedule.kind = "keep" }
+ schedule = result.draft.forMobileEditor()
preview = result
checkedSchedule = result.draft
loaded = true
@@ -181,17 +186,64 @@ struct RoutineEditorView: View {
}
}
- /// Cron is written directly; the host checks it and describes when it runs.
+ /// A frequency with its time, or cron written directly; the host compiles, checks and describes it.
private var cronFields: some View {
- VStack(alignment: .leading, spacing: 8) {
+ VStack(alignment: .leading, spacing: 14) {
ViewThatFits(in: .horizontal) {
- HStack(alignment: .top, spacing: 10) { expressionField; zoneField.frame(width: 170) }
- VStack(alignment: .leading, spacing: 14) { expressionField; zoneField }
+ HStack(alignment: .top, spacing: 10) { frequencyFields }
+ VStack(alignment: .leading, spacing: 14) { frequencyFields }
+ }
+ VStack(alignment: .leading, spacing: 8) {
+ if schedule.calendarStyle == "custom" {
+ ViewThatFits(in: .horizontal) {
+ HStack(alignment: .top, spacing: 10) { expressionField; zoneField }
+ VStack(alignment: .leading, spacing: 14) { expressionField; zoneField }
+ }
+ } else {
+ zoneField
+ }
+ schedulePreview.padding(.leading, 4)
}
- schedulePreview.padding(.leading, 4)
}
}
+ @ViewBuilder private var frequencyFields: some View {
+ Field("Repeat") {
+ ChoicePicker(selection: Binding(get: { schedule.calendarStyle }, set: selectFrequency), options: RoutineScheduleDraft.repeatChoices)
+ }
+ switch schedule.calendarStyle {
+ case "hourly":
+ Field("At minute") {
+ ChoicePicker(selection: $schedule.minute, options: (0..<60).map { (id: $0, label: String(format: ":%02d", $0)) })
+ }
+ case "daily", "weekdays":
+ timeField
+ case "weekly":
+ Field("On") {
+ // Monday first; the host counts 0 = Sunday … 6 = Saturday, like cron.
+ ChoicePicker(selection: $schedule.weekday,
+ options: [1, 2, 3, 4, 5, 6, 0].map { (id: $0, label: Calendar.current.standaloneWeekdaySymbols[$0]) })
+ }
+ timeField
+ default:
+ EmptyView()
+ }
+ }
+
+ private var timeField: some View {
+ Field("At") {
+ DatePicker("At", selection: $schedule.timeOfDay, displayedComponents: .hourAndMinute)
+ .labelsHidden()
+ .environment(\.timeZone, .gmt)
+ }
+ }
+
+ /// Custom starts from the cron the host compiled for the checked choice it replaces.
+ private func selectFrequency(_ style: String) {
+ let compiled = checkedSchedule == schedule ? preview?.cronExpression : nil
+ withAnimation(Motion.reduced(Motion.layout, reduceMotion)) { schedule = schedule.repeating(style, compiled: compiled) }
+ }
+
private var expressionField: some View {
Field("Cron") {
TextField("Cron", text: $schedule.expression, prompt: Text("0 9 * * 1-5").foregroundStyle(Palette.secondary))
@@ -202,8 +254,16 @@ struct RoutineEditorView: View {
private var zoneField: some View {
Field("Time zone") {
- TextField("Time zone", text: $schedule.zone, prompt: Text("Asia/Taipei").foregroundStyle(Palette.secondary))
- .autocorrectionDisabled().routineInput().focused($typing)
+ Button { pickingZone = true } label: {
+ HStack(spacing: 6) {
+ Text(schedule.zone).lineLimit(1)
+ Text(TimeZones.offset(schedule.zone)).foregroundStyle(Palette.secondary)
+ Image(systemName: "chevron.down").font(.caption2.weight(.semibold)).foregroundStyle(Palette.secondary)
+ }
+ .foregroundStyle(Palette.text)
+ .outlinedPill()
+ }
+ .buttonStyle(.plain)
}
}
@@ -224,7 +284,7 @@ struct RoutineEditorView: View {
Text(warning).font(.caption).foregroundStyle(Palette.secondary)
}
}
- } else {
+ } else if schedule.calendarStyle == "custom" {
Text("minute hour day month weekday").font(.caption.monospaced()).foregroundStyle(Palette.tertiary)
}
}
diff --git a/apps/ios/Kit/Sources/CodyncUI/Routines/TimeZonePicker.swift b/apps/ios/Kit/Sources/CodyncUI/Routines/TimeZonePicker.swift
new file mode 100644
index 00000000..6bd0e6f7
--- /dev/null
+++ b/apps/ios/Kit/Sources/CodyncUI/Routines/TimeZonePicker.swift
@@ -0,0 +1,62 @@
+import CodyncKit
+import SwiftUI
+
+/// Every IANA time zone with its current GMT offset, narrowed as you type; picking one closes it.
+struct TimeZonePicker: View {
+ let selection: String
+ let onPick: (String) -> Void
+ @State private var query = ""
+ private static let top = "top"
+
+ var body: some View {
+ VStack(spacing: 0) {
+ ModalHeader("Time zone")
+ SearchField("Search time zones", text: $query)
+ .padding(.horizontal, 20)
+ .padding(.bottom, 12)
+ ScrollViewReader { proxy in
+ ScrollView {
+ let zones = TimeZones.search(query)
+ VStack(spacing: 0) {
+ Color.clear.frame(height: 0).id(Self.top)
+ if zones.isEmpty {
+ Text("No matching time zones").foregroundStyle(Palette.secondary).padding(.top, 8)
+ }
+ LazyVStack(alignment: .leading, spacing: 0) {
+ ForEach(zones, id: \.self) { zone in
+ row(zone)
+ if zone != zones.last { Hairline().padding(.horizontal, 16) }
+ }
+ }
+ .background(Palette.surface, in: RoundedRectangle(cornerRadius: 16, style: .continuous))
+ }
+ .padding(.horizontal, 20)
+ .padding(.bottom, 20)
+ }
+ .scrollDismissesKeyboard(.interactively)
+ .onAppear { proxy.scrollTo(selection, anchor: .center) }
+ // A shorter list from a deep scroll position would otherwise show blank.
+ .onChange(of: query) { proxy.scrollTo(Self.top, anchor: .top) }
+ }
+ }
+ .font(.body)
+ .background(Palette.background)
+ }
+
+ private func row(_ zone: String) -> some View {
+ Button { onPick(zone) } label: {
+ HStack(spacing: 10) {
+ Text(zone).foregroundStyle(Palette.text).lineLimit(1)
+ Spacer(minLength: 8)
+ Text(TimeZones.offset(zone)).foregroundStyle(Palette.secondary)
+ Image(systemName: "checkmark").font(.callout.weight(.semibold)).foregroundStyle(Palette.accent)
+ .opacity(zone == selection ? 1 : 0)
+ }
+ .padding(.horizontal, 16)
+ .padding(.vertical, 14)
+ .contentShape(Rectangle())
+ }
+ .buttonStyle(PressScale())
+ .accessibilityAddTraits(zone == selection ? .isSelected : [])
+ }
+}
diff --git a/apps/ios/Kit/Tests/CodyncKitTests/RoutineTests.swift b/apps/ios/Kit/Tests/CodyncKitTests/RoutineTests.swift
index f29828fb..c65c4871 100644
--- a/apps/ios/Kit/Tests/CodyncKitTests/RoutineTests.swift
+++ b/apps/ios/Kit/Tests/CodyncKitTests/RoutineTests.swift
@@ -37,6 +37,18 @@ import Testing
#expect(draft.at == 1_779_000_000_001)
}
+@Test func routineTimeOfDayRoundTripsHourAndMinute() throws {
+ var draft = RoutineScheduleDraft()
+ draft.hour = 23
+ draft.minute = 47
+ var calendar = Calendar(identifier: .gregorian)
+ calendar.timeZone = .gmt
+ #expect(calendar.dateComponents([.hour, .minute], from: draft.timeOfDay) == DateComponents(hour: 23, minute: 47))
+ draft.timeOfDay = try #require(calendar.date(from: DateComponents(year: 2030, month: 3, day: 9, hour: 6, minute: 5)))
+ #expect(draft.hour == 6)
+ #expect(draft.minute == 5)
+}
+
@Test func routineWebhookDecodesWithAndWithoutTheCloud() throws {
let cloud = Data(#"{"url":"https://api.codync.dev/v1/hooks/c/r","localUrl":"http://127.0.0.1:19222/hooks/routines/r","key":"k","connected":true}"#.utf8)
let local = Data(#"{"url":null,"localUrl":"http://127.0.0.1:19222/hooks/routines/r","key":"k","connected":false}"#.utf8)
@@ -45,3 +57,61 @@ import Testing
#expect(off.url == nil)
#expect(off.localUrl.hasSuffix("/hooks/routines/r"))
}
+
+@Test func routineTimeoutReadsAsADuration() {
+ #expect(Routine.timeoutText("3600") == "1 hour")
+ #expect(Routine.timeoutText("7200") == "2 hours")
+ #expect(Routine.timeoutText("1800") == "30 minutes")
+ #expect(Routine.timeoutText("60") == "1 minute")
+ #expect(Routine.timeoutText("90") == "90 seconds")
+ #expect(Routine.timeoutText("1") == "1 second")
+ #expect(Routine.timeoutText("1.5") == "1.5s")
+ #expect(Routine.timeoutText("") == "s")
+}
+
+@Test func timeZoneSearchIsFuzzyAndRanksWordStartsFirst() {
+ let zones = ["America/New_York", "Asia/Taipei", "Asia/Tokyo", "Europe/Berlin", "America/Argentina/Buenos_Aires"]
+ #expect(TimeZones.search("taipei", in: zones) == ["Asia/Taipei"])
+ #expect(TimeZones.search("TAIPEI", in: zones) == ["Asia/Taipei"])
+ #expect(TimeZones.search("new york", in: zones) == ["America/New_York"])
+ #expect(TimeZones.search("new_york", in: zones) == ["America/New_York"])
+ #expect(TimeZones.search("asia tai", in: zones) == ["Asia/Taipei"])
+ #expect(TimeZones.search("buenos-aires", in: zones) == ["America/Argentina/Buenos_Aires"])
+ // A name that starts with the query, then word starts, then text inside a word, then letters in order.
+ #expect(TimeZones.search("a", in: zones) == ["America/Argentina/Buenos_Aires", "America/New_York", "Asia/Taipei", "Asia/Tokyo"])
+ #expect(TimeZones.search("ai", in: zones) == ["America/Argentina/Buenos_Aires", "Asia/Taipei", "America/New_York", "Asia/Tokyo"])
+ #expect(TimeZones.search("nyk", in: zones) == ["America/New_York"])
+ #expect(TimeZones.search(" ", in: zones) == zones)
+ #expect(TimeZones.search("xyz", in: zones).isEmpty)
+ #expect(TimeZones.offset("Asia/Taipei") == "GMT+8")
+}
+
+@Test func routineRepeatKeepsTheFiveChoicesAndOpensTheRestAsCustom() {
+ #expect(RoutineScheduleDraft.repeatChoices.map(\.id) == ["hourly", "daily", "weekdays", "weekly", "custom"])
+ var draft = RoutineScheduleDraft()
+ for style in ["hourly", "daily", "weekdays", "weekly", "custom"] {
+ draft.calendarStyle = style
+ #expect(draft.forMobileEditor().calendarStyle == style)
+ }
+ for style in ["minutes", "days", "monthly"] {
+ draft.calendarStyle = style
+ #expect(draft.forMobileEditor().calendarStyle == "custom")
+ }
+ for (kind, shown) in [("cron", "cron"), ("webhook", "webhook"), ("interval", "keep"), ("once", "keep")] {
+ draft.kind = kind
+ #expect(draft.forMobileEditor().kind == shown)
+ }
+}
+
+@Test func customStartsFromTheCronTheHostCompiled() {
+ var draft = RoutineScheduleDraft()
+ draft.calendarStyle = "weekdays"
+ draft.expression = "0 8 * * *"
+ #expect(draft.repeating("custom", compiled: "0 9 * * 1-5").expression == "0 9 * * 1-5")
+ #expect(draft.repeating("custom", compiled: nil).expression == "")
+ #expect(draft.repeating("daily", compiled: "0 9 * * 1-5").expression == "0 8 * * *")
+ #expect(draft.repeating("weekdays", compiled: "x") == draft)
+ let cron = RoutineTrigger(type: "cron", expression: "0 9 * * 1-5", timeZone: "UTC")
+ #expect(RoutineSchedulePreview(draft: draft, triggers: [cron], summary: "").cronExpression == "0 9 * * 1-5")
+ #expect(RoutineSchedulePreview(draft: draft, triggers: [RoutineTrigger(type: "webhook")], summary: "").cronExpression == nil)
+}
diff --git a/docs/design/ui-conventions.md b/docs/design/ui-conventions.md
index 2f7ab0b9..d7460ccb 100644
--- a/docs/design/ui-conventions.md
+++ b/docs/design/ui-conventions.md
@@ -58,7 +58,7 @@ The iPhone and the desktop no longer share UI code. `CodyncUI` (`apps/ios/Kit/`)
## Shared application controls
-Other custom iPhone screens use `Chrome.swift` and `Controls.swift`. The desktop equivalents are in `Overlay.tsx` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`) and `Controls.tsx` (`IconButton`, `DropdownMenu`, `ChoicePicker`, `Switch`, `CardForm`, `CardSection`, `ValueRow`).
+Other custom iPhone screens use `Chrome.swift` and `Controls.swift`. The desktop equivalents are in `Overlay.tsx` (`Sheet`, `Dialog`, `AnchoredMenu`, `ModalHeader`) and `Controls.tsx` (`IconButton`, `DropdownMenu`, `ChoicePicker`, `ChipChoice`, `Switch`, `CardForm`, `CardSection`, `ValueRow`).
| Need | Component |
|---|---|
@@ -96,7 +96,7 @@ Preserve the original character avatar design: dotted shading, highlight-only co
The details inspector (`apps/desktop/src/renderer/views/thread/DetailsPanel.tsx`) copies Grok Bot's: share (Create template) and close (X) as round buttons in the corner, in the page color with a soft ring, over a 54-point band that drags the window; the bot's 60-point avatar, name and runtime centered on top; then page tabs (`TabChoice`: plain labels, the chosen one on a light capsule) for **Details**, **Memory** and **Settings**, all in one scroll. The chat's `<<` button (in the same ringed style) and the title pill open it; hovering the pill shows a `>` after the name. Details holds what changes often: Instructions, Agent (the agent with its logo, its model and fast mode), the Use the computer switch and Routines (one card per routine); Settings holds the rest: Profile (avatar row, name), Workspace (computer, workspace, permissions), Activity, Connectors and Skills. Both are parts of `BotSettingsForm` (`part`), saved as you edit; the New bot and editor sheets show all of it. Memory is the memory card, its sections in the same tabs and the add/more actions beside each layer's note. Every group in the panel is Grok Bot's outlined card (an outline on the page, no fill, inputs filled instead), a row with a note puts its control under the note, and long notes (skill descriptions, explanations, a note's description) stop at two lines with an ellipsis. A group shows its avatar, name, bot count and members instead of tabs. Use 16-point horizontal insets and 28-point section gaps; sections use the `CardSection` look: filled 16-point groups without borders, hairline-split rows, a note under each option. The iPhone's Details sheet (`BotDetailsView`, from the title menu's Details, Settings and Routines) has the same corner buttons, header, tabs, pages, outlined cards (`cardStyle`) and two-line notes (`noteLines`), and saves as you edit too.
-Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens the same form as +, filled in, with delete and test run beside Save. On the desktop the form card fits its content. The header's chat button asks the bot (puts "I want a routine that " in the composer); + opens the form, where When to run is a type choice and cron is typed directly. The empty state is one line of text. A saved webhook routine's form shows the public URL and key as filled monospaced rows with copy, show/hide and replace-key (confirmed) icon buttons, and one caption on how to send and that deliveries pass through the Codync cloud. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.
+Routines are a compact grouped list: name, a one-line schedule (or the live run state), and an on/off switch per row; tapping a row opens the same form as +, filled in, with delete and test run beside Save. On the desktop the form card fits its content. The header's chat button asks the bot (puts "I want a routine that " in the composer); + opens the form, where When to run is a type choice (a segmented control on the desktop, the system menu on iPhone) and a schedule is a Repeat choice (Hourly, Daily, Weekdays, Weekly, Custom) with only the fields that choice needs (minute, time, weekday, or a typed cron for Custom) and a time zone picked from a searchable list. On the desktop these sit in one `CardSection` of labeled rows, Repeat and the weekday as `ChipChoice` chips with the chosen one on a light capsule. The empty state is one line of text. A saved webhook routine's form shows the public URL and key as monospaced rows (in the same group on the desktop) with copy, show/hide and replace-key (confirmed) icon buttons, and one caption on how to send and that deliveries pass through the Codync cloud. Agent metadata uses Runtime and Workspace labels for personal bots, or Project folder for explicitly configured projects; project paths remain selectable and wrap. Personal workspace paths stay out of the default details UI. Keep status and section headings readable in both appearances through `Palette`.
On iPhone, the routine editor keeps the full-width save action in a fixed footer on the sheet background. When required fields are empty, the footer explains why saving is unavailable.
@@ -233,6 +233,14 @@ explicit exception to the filled-surface border rule. iOS keeps the system sheet
and system menu's own edge treatment; terminal dialogs retain their existing
character borders. Neither receives an extra desktop-style outline.
+Desktop sheets and dialogs sit a step above the page (`--sheet`, raised in dark
+mode, over a deeper scrim); inside them grouped rows and fields are quiet tints of
+the text color, and a sheet's `ModalHeader` leads with an icon tile (a symbol, or
+the item's logo for an agent) beside the title and its line. Forms fit their content
+instead of a fixed height. A confirmation dialog is left-aligned with its answers in
+a row on the right, Cancel first. These are desktop treatments: iOS keeps the system
+sheet and `.codyncDialog`, and the terminal keeps its character dialogs.
+
The desktop sidebar computer filter shares the toolbar's subtle outline and 32px
height, with a capsule enclosing both the computer glyph and its chevron. This
applies in expanded and compact sidebars. iOS retains native toolbar treatment;
diff --git a/docs/features/routines.md b/docs/features/routines.md
index d55163cf..584fc40f 100644
--- a/docs/features/routines.md
+++ b/docs/features/routines.md
@@ -7,11 +7,15 @@ conversation details panel and the iPhone's **More → Routines** show a compact
that " in the composer; **+** opens the form for doing it by hand. A row opens
the same form filled in, with delete and test run beside Save; the row's switch
pauses and resumes. Run results appear in the chat. The form is name, instruction, a **When to run** type (Schedule or Webhook, the two
-Claude Code routines also offer besides GitHub events) and a run timeout; cron is
-written directly as five fields plus an IANA time zone, and the host checks it and
-shows the summary and next run. One-off times, intervals, events and multiple
+Claude Code routines also offer besides GitHub events) and a run timeout. A schedule
+picks how often it repeats (Hourly, Daily, Weekdays, Weekly, or Custom for a cron
+written as five fields), the time and day, and an IANA time zone chosen from a list
+filtered as you type (the device's own zone by default); the host compiles the
+cron, checks it and shows the summary and next run. One-off times, intervals, events and multiple
triggers are left to the bot: editing such a routine shows its current triggers as
-the selected type and keeps them until Schedule or Webhook replaces them. The TUI (`n` form with a typed When, `c` asks the bot) match.
+the selected type and keeps them until Schedule or Webhook replaces them. The TUI (`n` form with a typed When: `daily 09:00`, `weekdays 09:00`,
+`weekly mon 09:00`, `hourly :30`, `every 2h`, a cron or `webhook`, optionally ending
+in a time zone that Tab completes; `c` asks the bot) match.
A saved webhook routine's form shows its public URL and key (copy, reveal, replace
with confirmation; TUI `w` copies a curl command and `W` replaces the
key). Creation/update notices open the routine.
@@ -20,8 +24,8 @@ key). Creation/update notices open the routine.
The editor keeps task fields first, then a When to run type menu and its settings.
Inputs use the shared palette with a visible filled surface. New recurring schedules
-default to a typed cron expression and an explicit IANA time zone; the host
-describes it and shows the next run. Run timeout is under an animated Run settings
+default to Daily at 09:00 in the device's time zone; Custom takes a typed cron. The
+host describes the schedule and shows the next run. Run timeout is under an animated Run settings
expansion. A fixed footer keeps Create routine / Save changes and inline errors
visible while the form scrolls.
The layout uses the same light/dark tokens, type family and custom controls as the
@@ -215,8 +219,8 @@ the routine by name. No reference routine was run, paused or deleted during this
comparison.
Codync retains that compact sidebar and the chat-based setup path, while providing
-a direct editor where cron is typed as written (the earlier frequency/clock pickers
-were removed as too heavy). Existing duration intervals keep their cadence until
+a direct editor: a light Repeat choice with the time and day for the common
+schedules, and Custom for a cron typed as written. Existing duration intervals keep their cadence until
explicitly replaced. Editing hydrates the original expression, timezone and interval
exactly; compound and provider-event triggers retain a lossless Keep existing
triggers fallback. Expired one-shot timestamps are preserved when editing other fields.
@@ -227,9 +231,14 @@ Edit with bot includes the routine ID in a draft without sending it.
## Cron scheduling contract
-All newly configured recurring schedules in the editors use `cron` (sent as
-`calendarStyle: custom` with the typed expression) and run through the host's
-existing Croner scheduler. The host keeps preset compilation for its API. Cron generation, parsing, validation, timezone checks, descriptions and next-run
+All newly configured recurring schedules in the editors use `cron` and run through
+the host's existing Croner scheduler. The editors send the Repeat choice as
+`calendarStyle` (`hourly`, `daily`, `weekdays`, `weekly`) with the hour, minute and
+weekday, or `custom` with the typed expression, and the host compiles it. A loaded
+schedule in a style the editors don't offer (every few minutes, several days,
+monthly) opens as Custom with its cron unchanged; switching to Custom starts from
+the cron the host compiled (empty while the host is still checking the last change).
+Cron generation, parsing, validation, timezone checks, descriptions and next-run
calculation all live in `host/src/routines/editor.rs` and `schedule.rs`. The Swift
draft is only a Codable form DTO. The editor debounces preview requests, discards
stale responses, shows host errors and disables Save until the current draft is
diff --git a/host/src/routines/editor.rs b/host/src/routines/editor.rs
index db89424d..197a6722 100644
--- a/host/src/routines/editor.rs
+++ b/host/src/routines/editor.rs
@@ -76,7 +76,8 @@ impl ScheduleDraft {
draft
}
- fn read_cron(&mut self) {
+ /// The style (and its fields) a Custom `expression` is, when the editor has one for it.
+ pub(crate) fn read_cron(&mut self) {
let fields: Vec<_> = self.expression.split_whitespace().collect();
let [minute, hour, day, month, weekday] = fields.as_slice() else { return };
if [hour, day, month, weekday].iter().all(|field| **field == "*")
@@ -145,7 +146,7 @@ impl ScheduleDraft {
})
}
- fn cron(&self) -> Result<String> {
+ pub(crate) fn cron(&self) -> Result<String> {
if self.hour > 23 || self.minute > 59 {
bail!("choose a valid hour and minute");
}
diff --git a/host/src/routines/mod.rs b/host/src/routines/mod.rs
index 6df7e6bf..430d6916 100644
--- a/host/src/routines/mod.rs
+++ b/host/src/routines/mod.rs
@@ -1,6 +1,6 @@
//! Durable bot routines, shared by API clients and the built-in MCP server.
mod editor;
-pub use editor::preview as schedule_preview;
+pub use editor::{ScheduleDraft, preview as schedule_preview};
pub mod hooks;
use hooks::Refused;
mod runner;
@@ -213,7 +213,7 @@ impl Routines {
bail!("routine name or instruction is empty or too long");
}
let triggers: Vec<Trigger> = if let Some(draft) = body.get("schedule") {
- serde_json::from_value::<editor::ScheduleDraft>(draft.clone()).context("invalid schedule")?.triggers()?
+ serde_json::from_value::<ScheduleDraft>(draft.clone()).context("invalid schedule")?.triggers()?
} else {
serde_json::from_value(body["triggers"].clone()).context("invalid triggers")?
};
diff --git a/host/src/tui/manage/mod.rs b/host/src/tui/manage/mod.rs
index aa840754..016e7aa5 100644
--- a/host/src/tui/manage/mod.rs
+++ b/host/src/tui/manage/mod.rs
@@ -15,13 +15,14 @@ mod pages;
mod replies;
mod routines;
mod skill;
+mod when;
pub use analytics::AnalyticsSheet;
pub use fields::{handoff_fields, memory_file_fields};
pub use memory::{MemoryMode, MemorySheet, Section};
pub use pages::Page;
-pub use routines::local_zone;
pub use skill::SkillSheet;
+pub use when::{complete_zone, local_zone};
use crossterm::event::{KeyCode, KeyEvent, KeyModifiers};
use serde_json::{Value, json};
diff --git a/host/src/tui/manage/routines.rs b/host/src/tui/manage/routines.rs
index 1e6b2771..1bf7823b 100644
--- a/host/src/tui/manage/routines.rs
+++ b/host/src/tui/manage/routines.rs
@@ -1,10 +1,10 @@
-//! A bot's routines: the list, the form, and the triggers typed into it.
+//! A bot's routines: the list and the form (what's typed for when: `when.rs`).
use crossterm::event::{KeyCode, KeyEvent};
use serde_json::{Value, json};
-use std::str::FromStr as _;
use super::super::app::{After, App, Confirm, ConfirmAct, Editor, FIELDS, Field, Focus, Overlay};
+use super::when::{complete_zone, local_zone, parse_when, when_text};
use super::{Page, Reply, RoutineField, RoutineForm, RoutineList, ctrl, newline, s};
impl App {
@@ -145,6 +145,14 @@ impl App {
pub(in crate::tui) fn routine_key(&mut self, mut f: Box<RoutineForm>, k: KeyEvent) -> Option<Overlay> {
use RoutineField::{Instruction, Name, When};
+ // Tab finishes a time zone being typed after the schedule before it moves on.
+ if k.code == KeyCode::Tab
+ && f.field == When
+ && let Some(done) = complete_zone(&f.when.text, crate::store::now_ms())
+ {
+ f.when = Editor::with(&done);
+ return Some(Overlay::Routine(f));
+ }
match k.code {
KeyCode::Esc => return None,
_ if newline(k) && f.field == Instruction => f.instruction.insert("\n"),
@@ -211,104 +219,3 @@ impl App {
fn has_webhook(r: &Value) -> bool {
r["triggers"].as_array().into_iter().flatten().any(|t| matches!(t["type"].as_str(), Some("webhook" | "event")))
}
-
-/// This computer's IANA time zone (routines run on the host's clock in it).
-pub fn local_zone() -> String {
- let valid = |z: &str| chrono_tz::Tz::from_str(z).is_ok();
- if let Ok(tz) = std::env::var("TZ")
- && valid(tz.trim_start_matches(':'))
- {
- return tz.trim_start_matches(':').to_owned();
- }
- std::fs::read_link("/etc/localtime")
- .ok()
- .and_then(|p| p.to_string_lossy().split_once("zoneinfo/").map(|(_, z)| z.to_owned()))
- .filter(|z| valid(z))
- .unwrap_or_else(|| "UTC".into())
-}
-
-/// One trigger from what's typed: `webhook`, `every 30m`, a date and time (once),
-/// or five cron fields in `zone`.
-pub fn parse_when(text: &str, zone: &str, now: i64) -> Result<Value, String> {
- let t = text.trim().to_lowercase();
- if t.is_empty() {
- return Err("Say when it runs.".into());
- }
- if t == "webhook" {
- return Ok(json!({"type": "webhook"}));
- }
- if let Some(rest) = t.strip_prefix("every") {
- let rest = rest.trim();
- let split = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
- let (n, unit) = rest.split_at(split);
- let n: i64 = if n.is_empty() { 1 } else { n.parse().map_err(|_| "Use a whole number, like every 30m.")? };
- let unit = match unit.trim().trim_end_matches('s') {
- "sec" | "second" => 1,
- "m" | "min" | "minute" => 60,
- "h" | "hr" | "hour" => 3600,
- "d" | "day" => 86400,
- "" if n > 0 && !rest.is_empty() => return Err("Add a unit: s, m, h or d.".into()),
- _ => return Err("Use s, m, h or d, like every 2h.".into()),
- };
- return Ok(json!({"type": "interval", "seconds": n * unit}));
- }
- if let Ok(at) = chrono::NaiveDateTime::parse_from_str(&t, "%Y-%m-%d %H:%M") {
- let tz = chrono_tz::Tz::from_str(zone).map_err(|_| "Unknown time zone")?;
- let at = at.and_local_timezone(tz).earliest().ok_or("That time doesn't exist here.")?.timestamp_millis();
- if at <= now {
- return Err("That time has passed.".into());
- }
- return Ok(json!({"type": "once", "at": at}));
- }
- if t.split_whitespace().count() == 5 {
- return Ok(
- json!({"type": "cron", "expression": t.split_whitespace().collect::<Vec<_>>().join(" "), "timeZone": zone}),
- );
- }
- Err("Try 0 9 * * 1-5, every 2h, 2026-10-01 09:00 or webhook.".into())
-}
-
-/// A routine's triggers as `parse_when` reads them, when they're one it can write.
-pub fn when_text(triggers: &Value, zone: &str) -> Option<String> {
- let [t] = triggers.as_array()?.as_slice() else { return None };
- match t["type"].as_str()? {
- "webhook" => Some("webhook".into()),
- "interval" => {
- let secs = t["seconds"].as_i64()?;
- let (n, u) = [(86400, "d"), (3600, "h"), (60, "m"), (1, "s")].into_iter().find(|(u, _)| secs % u == 0)?;
- Some(format!("every {}{u}", secs / n))
- }
- "cron" if t["timeZone"].as_str() == Some(zone) => t["expression"].as_str().map(str::to_owned),
- "once" => {
- let tz = chrono_tz::Tz::from_str(zone).ok()?;
- let at = chrono::DateTime::from_timestamp_millis(t["at"].as_i64()?)?.with_timezone(&tz);
- Some(at.format("%Y-%m-%d %H:%M").to_string())
- }
- _ => None,
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn when_reads_what_it_writes() {
- let now = 1_790_470_800_000;
- let zone = "Asia/Taipei";
- assert_eq!(parse_when("webhook", zone, now), Ok(json!({"type": "webhook"})));
- assert_eq!(parse_when("every 30m", zone, now), Ok(json!({"type": "interval", "seconds": 1800})));
- assert_eq!(parse_when("Every 2 hours", zone, now), Ok(json!({"type": "interval", "seconds": 7200})));
- assert!(parse_when("every 5", zone, now).is_err());
- assert!(parse_when("2020-01-01 09:00", zone, now).is_err());
- assert!(parse_when("tomorrow", zone, now).is_err());
- for text in ["0 9 * * 1-5", "every 90m", "every 1d", "webhook", "2030-10-01 09:00"] {
- let t = parse_when(text, zone, now).expect(text);
- let back = when_text(&json!([t]), zone).expect(text);
- assert_eq!(parse_when(&back, zone, now), Ok(t), "{text}");
- }
- // Another zone's cron, or several triggers, stay as they were.
- assert_eq!(when_text(&json!([{"type": "cron", "expression": "0 9 * * *", "timeZone": "UTC"}]), zone), None);
- assert_eq!(when_text(&json!([{"type": "webhook"}, {"type": "webhook"}]), zone), None);
- }
-}
diff --git a/host/src/tui/manage/when.rs b/host/src/tui/manage/when.rs
new file mode 100644
index 00000000..c8f30f32
--- /dev/null
+++ b/host/src/tui/manage/when.rs
@@ -0,0 +1,330 @@
+//! When a routine runs, as typed in the terminal: `webhook`, `every 30m`, a Repeat preset
+//! (`daily 09:00`), a date and time, or cron, each optionally followed by a time zone.
+
+use crate::routines::ScheduleDraft;
+use serde_json::{Value, json};
+use std::str::FromStr as _;
+
+/// This computer's IANA time zone (routines run on the host's clock in it).
+pub fn local_zone() -> String {
+ let valid = |z: &str| chrono_tz::Tz::from_str(z).is_ok();
+ if let Ok(tz) = std::env::var("TZ")
+ && valid(tz.trim_start_matches(':'))
+ {
+ return tz.trim_start_matches(':').to_owned();
+ }
+ std::fs::read_link("/etc/localtime")
+ .ok()
+ .and_then(|p| p.to_string_lossy().split_once("zoneinfo/").map(|(_, z)| z.to_owned()))
+ .filter(|z| valid(z))
+ .unwrap_or_else(|| "UTC".into())
+}
+
+/// One trigger from what's typed. A trailing time zone (`daily 09:00 Europe/Paris`, any case)
+/// replaces `zone` for clock times; one still being typed gets a hint at what Tab picks.
+pub fn parse_when(text: &str, zone: &str, now: i64) -> Result<Value, String> {
+ let (rest, last) = split_last(text);
+ if let Some(z) = exact_zone(last) {
+ return parse_in(rest, z, now);
+ }
+ parse_in(text, zone, now).map_err(|e| match zone_attempt(text, now) {
+ Some((_, word)) => match best_zone(word) {
+ Some(z) => format!("Unknown time zone; tab picks {z}."),
+ None => "Unknown time zone.".into(),
+ },
+ None => e,
+ })
+}
+
+/// `text` with its last word completed to the closest time zone, when it's a clock schedule
+/// followed by part of one (`daily 09:00 taipei` → `daily 09:00 Asia/Taipei`).
+pub fn complete_zone(text: &str, now: i64) -> Option<String> {
+ let (rest, word) = zone_attempt(text, now)?;
+ Some(format!("{} {}", rest.trim(), best_zone(word)?))
+}
+
+/// A routine's triggers as `parse_when` reads them, when they're one it can write; a cron
+/// in another zone than `zone` ends with that zone.
+pub fn when_text(triggers: &Value, zone: &str) -> Option<String> {
+ let [t] = triggers.as_array()?.as_slice() else { return None };
+ match t["type"].as_str()? {
+ "webhook" => Some("webhook".into()),
+ "interval" => {
+ let secs = t["seconds"].as_i64()?;
+ let (n, u) = [(86400, "d"), (3600, "h"), (60, "m"), (1, "s")].into_iter().find(|(u, _)| secs % u == 0)?;
+ Some(format!("every {}{u}", secs / n))
+ }
+ "cron" => {
+ let cron = t["expression"].as_str()?;
+ let at = exact_zone(t["timeZone"].as_str()?)?;
+ let text = preset_text(cron).unwrap_or_else(|| cron.to_owned());
+ Some(if at == zone { text } else { format!("{text} {at}") })
+ }
+ "once" => {
+ let tz = chrono_tz::Tz::from_str(zone).ok()?;
+ let at = chrono::DateTime::from_timestamp_millis(t["at"].as_i64()?)?.with_timezone(&tz);
+ Some(at.format("%Y-%m-%d %H:%M").to_string())
+ }
+ _ => None,
+ }
+}
+
+/// `parse_when` without a trailing zone: everything in `zone`.
+fn parse_in(text: &str, zone: &str, now: i64) -> Result<Value, String> {
+ let t = text.trim().to_lowercase();
+ if t.is_empty() {
+ return Err("Say when it runs.".into());
+ }
+ if t == "webhook" {
+ return Ok(json!({"type": "webhook"}));
+ }
+ let words: Vec<&str> = t.split_whitespace().collect();
+ if let Some(cron) = preset_cron(&words) {
+ return Ok(json!({"type": "cron", "expression": cron?, "timeZone": zone}));
+ }
+ if let Some(rest) = t.strip_prefix("every") {
+ let rest = rest.trim();
+ let split = rest.find(|c: char| !c.is_ascii_digit()).unwrap_or(rest.len());
+ let (n, unit) = rest.split_at(split);
+ let n: i64 = if n.is_empty() { 1 } else { n.parse().map_err(|_| "Use a whole number, like every 30m.")? };
+ let unit = match unit.trim().trim_end_matches('s') {
+ "sec" | "second" => 1,
+ "m" | "min" | "minute" => 60,
+ "h" | "hr" | "hour" => 3600,
+ "d" | "day" => 86400,
+ "" if n > 0 && !rest.is_empty() => return Err("Add a unit: s, m, h or d.".into()),
+ _ => return Err("Use s, m, h or d, like every 2h.".into()),
+ };
+ return Ok(json!({"type": "interval", "seconds": n * unit}));
+ }
+ if let Ok(at) = chrono::NaiveDateTime::parse_from_str(&t, "%Y-%m-%d %H:%M") {
+ let tz = chrono_tz::Tz::from_str(zone).map_err(|_| "Unknown time zone")?;
+ let at = at.and_local_timezone(tz).earliest().ok_or("That time doesn't exist here.")?.timestamp_millis();
+ if at <= now {
+ return Err("That time has passed.".into());
+ }
+ return Ok(json!({"type": "once", "at": at}));
+ }
+ if words.len() == 5 {
+ return Ok(json!({"type": "cron", "expression": words.join(" "), "timeZone": zone}));
+ }
+ Err("Try daily 09:00, weekdays 09:00, every 2h, 0 9 * * 1-5 or webhook.".into())
+}
+
+/// Weekdays in cron order (0 = Sunday); the first three letters are the short name.
+const DAYS: [&str; 7] = ["sunday", "monday", "tuesday", "wednesday", "thursday", "friday", "saturday"];
+
+/// The cron the host's routine editor compiles for a Repeat preset (`hourly`, `hourly :30`,
+/// `daily 09:00`, `weekdays 09:00`, `weekly mon 09:00`), or `None` when the words aren't one.
+fn preset_cron(words: &[&str]) -> Option<Result<String, String>> {
+ let (&style, rest) = words.split_first()?;
+ let time = |example: &str| match rest {
+ [at] => clock(at).ok_or_else(|| format!("Use a 24-hour time, like {example}.")),
+ _ => Err(format!("Use a 24-hour time, like {example}.")),
+ };
+ let draft = |(hour, minute): (u8, u8), weekday: u8| ScheduleDraft {
+ calendar_style: style.into(),
+ hour,
+ minute,
+ weekday,
+ ..ScheduleDraft::default()
+ };
+ let draft = match style {
+ "hourly" => match rest {
+ [] => Ok(draft((0, 0), 1)),
+ [m] => m
+ .strip_prefix(':')
+ .and_then(|m| small(m, 59))
+ .map(|m| draft((0, m), 1))
+ .ok_or_else(|| "Use a minute, like hourly :30.".into()),
+ _ => Err("Use a minute, like hourly :30.".into()),
+ },
+ "daily" | "weekdays" => time(&format!("{style} 09:00")).map(|at| draft(at, 1)),
+ "weekly" => {
+ let [day, at] = rest else { return Some(Err("Use a day and time, like weekly mon 09:00.".into())) };
+ let Some(d) = (0..).zip(DAYS).find_map(|(d, full)| (day.len() >= 3 && full.starts_with(day)).then_some(d))
+ else {
+ return Some(Err("Use a day from sun to sat, like weekly mon 09:00.".into()));
+ };
+ clock(at).map(|at| draft(at, d)).ok_or_else(|| "Use a 24-hour time, like weekly mon 09:00.".into())
+ }
+ _ => return None,
+ };
+ Some(draft.and_then(|d| d.cron().map_err(|e| format!("{e:#}"))))
+}
+
+/// A cron the host's routine editor reads as a Repeat preset, in its words; other crons get `None`.
+fn preset_text(expression: &str) -> Option<String> {
+ let mut draft =
+ ScheduleDraft { calendar_style: "custom".into(), expression: expression.into(), ..ScheduleDraft::default() };
+ draft.read_cron();
+ let (minute, at) = (draft.minute, format!("{:02}:{:02}", draft.hour, draft.minute));
+ Some(match draft.calendar_style.as_str() {
+ "hourly" if minute == 0 => "hourly".into(),
+ "hourly" => format!("hourly :{minute:02}"),
+ "daily" | "weekdays" => format!("{} {at}", draft.calendar_style),
+ "weekly" => format!("weekly {} {at}", DAYS.get(usize::from(draft.weekday))?.get(..3)?),
+ _ => return None,
+ })
+}
+
+/// `H:MM` or `HH:MM` on a 24-hour clock.
+fn clock(at: &str) -> Option<(u8, u8)> {
+ let (h, m) = at.split_once(':')?;
+ Some((small(h, 23)?, small(m, 59)?))
+}
+
+/// One or two digits, at most `max`.
+fn small(digits: &str, max: u8) -> Option<u8> {
+ let plain = (1..=2).contains(&digits.len()) && digits.bytes().all(|b| b.is_ascii_digit());
+ plain.then(|| digits.parse().ok()).flatten().filter(|n| *n <= max)
+}
+
+/// The text before its last word, and that word.
+fn split_last(text: &str) -> (&str, &str) {
+ let text = text.trim_end();
+ text.rsplit_once(char::is_whitespace).unwrap_or(("", text))
+}
+
+/// The IANA name `word` spells, in any case.
+fn exact_zone(word: &str) -> Option<&'static str> {
+ chrono_tz::TZ_VARIANTS.iter().map(|z| z.name()).find(|name| name.eq_ignore_ascii_case(word))
+}
+
+/// A clock schedule followed by a word that may be part of a time zone name: the two parts.
+fn zone_attempt(text: &str, now: i64) -> Option<(&str, &str)> {
+ let (rest, word) = split_last(text);
+ let clock_time = |t: Value| matches!(t["type"].as_str(), Some("cron" | "once"));
+ (word.chars().any(char::is_alphabetic)
+ && exact_zone(word).is_none()
+ && parse_in(rest, "UTC", now).is_ok_and(clock_time))
+ .then_some((rest, word))
+}
+
+/// The time zone whose name holds every part of `word` ("/", "_" and "-" read as spaces):
+/// cities starting with it first, then the shortest name.
+fn best_zone(word: &str) -> Option<&'static str> {
+ let norm = |s: &str| s.to_lowercase().replace(['/', '_', '-'], " ");
+ let query = norm(word);
+ let parts: Vec<&str> = query.split_whitespace().collect();
+ let first = parts.first()?;
+ chrono_tz::TZ_VARIANTS
+ .iter()
+ .map(|z| z.name())
+ .filter(|name| parts.iter().all(|p| norm(name).contains(p)))
+ .min_by_key(|name| (!norm(name.rsplit('/').next().unwrap_or(name)).starts_with(first), name.len(), *name))
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const NOW: i64 = 1_790_470_800_000;
+ const ZONE: &str = "Asia/Taipei";
+
+ #[test]
+ fn when_reads_what_it_writes() {
+ let (now, zone) = (NOW, ZONE);
+ assert_eq!(parse_when("webhook", zone, now), Ok(json!({"type": "webhook"})));
+ assert_eq!(parse_when("every 30m", zone, now), Ok(json!({"type": "interval", "seconds": 1800})));
+ assert_eq!(parse_when("Every 2 hours", zone, now), Ok(json!({"type": "interval", "seconds": 7200})));
+ assert!(parse_when("every 5", zone, now).is_err());
+ assert!(parse_when("2020-01-01 09:00", zone, now).is_err());
+ assert!(parse_when("tomorrow", zone, now).is_err());
+ for text in ["0 9 * * 1-5", "every 90m", "every 1d", "webhook", "2030-10-01 09:00", "0 9 * * * Europe/Paris"] {
+ let t = parse_when(text, zone, now).expect(text);
+ let back = when_text(&json!([t]), zone).expect(text);
+ assert_eq!(parse_when(&back, zone, now), Ok(t), "{text}");
+ }
+ // Several triggers, or a zone chrono-tz doesn't know, stay as they were.
+ assert_eq!(when_text(&json!([{"type": "webhook"}, {"type": "webhook"}]), zone), None);
+ assert_eq!(
+ when_text(&json!([{"type": "cron", "expression": "0 9 * * *", "timeZone": "Mars/Base"}]), zone),
+ None
+ );
+ }
+
+ #[test]
+ fn presets_write_the_editors_cron_and_read_back() {
+ let (now, zone) = (NOW, ZONE);
+ // Typed, the cron the host's editor writes for that Repeat style, and how editing shows it.
+ for (typed, cron, shown) in [
+ ("hourly", "0 * * * *", "hourly"),
+ ("hourly :30", "30 * * * *", "hourly :30"),
+ ("Hourly :05", "5 * * * *", "hourly :05"),
+ ("daily 08:30", "30 8 * * *", "daily 08:30"),
+ (" DAILY 9:00 ", "0 9 * * *", "daily 09:00"),
+ ("weekdays 09:00", "0 9 * * 1-5", "weekdays 09:00"),
+ ("weekdays 23:59", "59 23 * * 1-5", "weekdays 23:59"),
+ ("weekly sun 00:00", "0 0 * * 0", "weekly sun 00:00"),
+ ("weekly mon 09:00", "0 9 * * 1", "weekly mon 09:00"),
+ ("weekly Friday 17:45", "45 17 * * 5", "weekly fri 17:45"),
+ ("weekly sat 12:00", "0 12 * * 6", "weekly sat 12:00"),
+ ] {
+ let t = json!({"type": "cron", "expression": cron, "timeZone": zone});
+ assert_eq!(parse_when(typed, zone, now), Ok(t.clone()), "{typed}");
+ assert_eq!(when_text(&json!([t]), zone).as_deref(), Some(shown), "{typed}");
+ assert_eq!(parse_when(shown, zone, now), Ok(t), "{shown}");
+ }
+ // A cron the host's editor reads as a preset shows as one, and saves as the cron it compiles.
+ let padded = json!([{"type": "cron", "expression": "0 09 * * *", "timeZone": zone}]);
+ assert_eq!(when_text(&padded, zone).as_deref(), Some("daily 09:00"));
+ // Crons no preset writes stay raw, and save back unchanged.
+ for cron in ["0 9 * * 1,3,5", "*/15 * * * *", "0 9 1 * *", "0 9 * * 7", "0 * * * 1-5"] {
+ let t = json!({"type": "cron", "expression": cron, "timeZone": zone});
+ assert_eq!(when_text(&json!([t]), zone).as_deref(), Some(cron));
+ assert_eq!(parse_when(cron, zone, now), Ok(t), "{cron}");
+ }
+ for (typed, error) in [
+ ("hourly 30", "Use a minute, like hourly :30."),
+ ("hourly :60", "Use a minute, like hourly :30."),
+ ("daily", "Use a 24-hour time, like daily 09:00."),
+ ("daily 24:00", "Use a 24-hour time, like daily 09:00."),
+ ("daily 9am", "Use a 24-hour time, like daily 09:00."),
+ ("weekdays 09:60", "Use a 24-hour time, like weekdays 09:00."),
+ ("weekdays 9:00 10:00", "Use a 24-hour time, like weekdays 09:00."),
+ ("weekly 09:00", "Use a day and time, like weekly mon 09:00."),
+ ("weekly mo 09:00", "Use a day from sun to sat, like weekly mon 09:00."),
+ ("weekly funday 09:00", "Use a day from sun to sat, like weekly mon 09:00."),
+ ("weekly tue 7:5x", "Use a 24-hour time, like weekly mon 09:00."),
+ ] {
+ assert_eq!(parse_when(typed, zone, now), Err(error.into()), "{typed}");
+ }
+ }
+
+ #[test]
+ fn a_trailing_zone_replaces_the_local_one() {
+ let cron = |expression: &str, zone: &str| json!({"type": "cron", "expression": expression, "timeZone": zone});
+ // Any case; the stored name is the canonical one, and editing shows it only when it isn't local.
+ for (typed, t, shown) in [
+ ("daily 09:00 europe/london", cron("0 9 * * *", "Europe/London"), "daily 09:00 Europe/London"),
+ ("weekdays 9:00 UTC", cron("0 9 * * 1-5", "UTC"), "weekdays 09:00 UTC"),
+ ("0 9 * * 1,3 America/New_York", cron("0 9 * * 1,3", "America/New_York"), "0 9 * * 1,3 America/New_York"),
+ ("hourly :15 Asia/Taipei", cron("15 * * * *", ZONE), "hourly :15"),
+ ] {
+ assert_eq!(parse_when(typed, ZONE, NOW), Ok(t.clone()), "{typed}");
+ assert_eq!(when_text(&json!([t]), ZONE).as_deref(), Some(shown), "{typed}");
+ }
+ // A date and time in another zone is that zone's moment.
+ let paris = parse_when("2030-10-01 09:00 Europe/Paris", ZONE, NOW).expect("once in Paris");
+ assert_eq!(paris["at"], 1_917_068_400_000_i64);
+ // Tab completes a partly typed zone after a clock schedule, fuzzily and in any case.
+ for (typed, done) in [
+ ("daily 09:00 taipei", "daily 09:00 Asia/Taipei"),
+ ("weekdays 08:30 new-york", "weekdays 08:30 America/New_York"),
+ ("0 9 * * 1 LOND", "0 9 * * 1 Europe/London"),
+ ("2030-10-01 09:00 tokyo", "2030-10-01 09:00 Asia/Tokyo"),
+ ] {
+ assert_eq!(complete_zone(typed, NOW).as_deref(), Some(done), "{typed}");
+ }
+ // Nothing to complete: no schedule before the word, a whole zone, a number, or no clock time.
+ for typed in ["daily", "daily 09:00", "daily 09:00 UTC", "weekdays 9:00 10:00", "every 2h paris", "webhook x"] {
+ assert_eq!(complete_zone(typed, NOW), None, "{typed}");
+ }
+ assert_eq!(
+ parse_when("daily 09:00 taipei", ZONE, NOW),
+ Err("Unknown time zone; tab picks Asia/Taipei.".into())
+ );
+ assert_eq!(parse_when("daily 09:00 qqq", ZONE, NOW), Err("Unknown time zone.".into()));
+ }
+}
diff --git a/host/src/tui/sheets.rs b/host/src/tui/sheets.rs
index 25cc1dfc..4cc57ff8 100644
--- a/host/src/tui/sheets.rs
+++ b/host/src/tui/sheets.rs
@@ -149,7 +149,7 @@ pub fn routines(buf: &mut Buffer, area: Rect, app: &App, l: &RoutineList) {
pub fn routine(buf: &mut Buffer, area: Rect, f: &RoutineForm) {
let t = theme();
- let r = centered(area, 84, 14);
+ let r = centered(area, 84, 15);
let title = if f.id.is_some() { "Edit routine" } else { "New routine" };
let inner = frame_box(buf, r, t.text, t.panel, Some((title, t.text)));
let label = |on: bool| if on { t.bold } else { t.secondary }.patch(t.panel);
@@ -168,19 +168,18 @@ pub fn routine(buf: &mut Buffer, area: Rect, f: &RoutineForm) {
);
put(buf, inner.x, inner.y + 7, 9, "When", label(f.field == RoutineField::When));
let placeholder = if f.original_text.is_empty() {
- "0 9 * * 1-5 · every 2h · 2026-10-01 09:00 · webhook"
+ "daily 09:00 · weekdays 09:00 · every 2h · 0 9 * * 1-5 · webhook"
} else {
&f.original_text
};
input_line(buf, at(inner.y + 7), inner.y + 7, &f.when, placeholder, f.field == RoutineField::When, false);
- put(
- buf,
- vx,
- inner.y + 8,
- vw,
- &format!("cron runs in {}; every = from now on; webhook = when called", super::manage::local_zone()),
- t.dim.patch(t.panel),
- );
+ put(buf, vx, inner.y + 8, vw, "or hourly :30 · weekly mon 09:00 · 2026-10-01 09:00 (once)", t.dim.patch(t.panel));
+ put(buf, vx, inner.y + 9, vw, "every = from now on · webhook = when called", t.dim.patch(t.panel));
+ let (zone_hint, zone_style) = match super::manage::complete_zone(&f.when.text, crate::store::now_ms()) {
+ Some(done) => (format!("tab → {done}"), t.secondary),
+ None => (format!("times in {}; end with a zone to change it", super::manage::local_zone()), t.dim),
+ };
+ put(buf, vx, inner.y + 10, vw, &zone_hint, zone_style.patch(t.panel));
let by = inner.bottom() - 1;
if let Some(e) = &f.error {
put(buf, inner.x, by - 1, inner.width, e, t.red.patch(t.panel));