From c7fbf4edf638e1983350fbbb2a498be09e052f65 Mon Sep 17 00:00:00 2001 From: pponce Date: Mon, 26 Oct 2026 13:53:44 -0700 Subject: [PATCH 1/4] Integrate verified server jobs with native schedule rework --- .../localrock/shared/device/ScheduleApi.kt | 33 +- .../localrock/shared/schedule/ScheduleApi.kt | 3 + .../shared/schedule/ScheduleEnablement.kt | 155 ++++++++++ .../shared/schedule/ServerJobCreation.kt | 41 +++ .../shared/schedule/ServerJobDeletion.kt | 69 +++++ .../shared/schedule/ServerSchedule.kt | 112 +++++++ .../localrock/shared/vacuum/CleanTimer.kt | 11 +- .../localrock/shared/vacuum/ScheduleMirror.kt | 3 + .../shared/vacuum/ServerJobEditing.kt | 60 ++++ .../localrock/shared/vacuum/ServerTimer.kt | 10 +- .../shared/vacuum/VacuumRepository.kt | 185 +++++++++--- .../localrock/ui/vacuum/ScheduleScreen.kt | 117 +++++-- .../shared/device/ScheduleJobsApiTest.kt | 33 ++ .../shared/schedule/ScheduleEnablementTest.kt | 285 ++++++++++++++++++ .../shared/schedule/ServerJobCreationTest.kt | 55 ++++ .../shared/schedule/ServerJobDeletionTest.kt | 53 ++++ .../shared/schedule/ServerScheduleTest.kt | 62 ++++ .../shared/vacuum/ServerJobEditingTest.kt | 50 +++ docs/schedules.md | 21 ++ 19 files changed, 1272 insertions(+), 86 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleApi.kt create mode 100644 composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt create mode 100644 composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt create mode 100644 composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt create mode 100644 composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt create mode 100644 composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt create mode 100644 composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt create mode 100644 composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt create mode 100644 composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt create mode 100644 composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt create mode 100644 composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt create mode 100644 composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt create mode 100644 docs/schedules.md diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt index b94ff5de..b3c6a3e0 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt @@ -2,6 +2,8 @@ package com.kodraliu.localrock.shared.device import com.kodraliu.localrock.shared.vacuum.ScheduleMirror import io.ktor.client.HttpClient +import com.kodraliu.localrock.shared.schedule.ServerSchedule +import io.ktor.client.request.get import io.ktor.client.request.delete import io.ktor.client.request.post import io.ktor.client.request.put @@ -11,6 +13,8 @@ import io.ktor.client.statement.bodyAsText import io.ktor.http.ContentType import io.ktor.http.content.TextContent import io.ktor.http.isSuccess +import io.ktor.http.encodeURLPathPart +import kotlinx.serialization.json.* import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive @@ -23,19 +27,36 @@ import kotlinx.serialization.json.jsonPrimitive * The JSON is serialised here, not by the client, so the Hawk signature covers the very bytes sent. */ class ScheduleApi(private val client: HttpClient) : ScheduleMirror { + private fun collection(duid: String) = "/user/devices/${duid.encodeURLPathPart()}/jobs" + private fun item(duid: String, id: String) = "${collection(duid)}/${id.encodeURLPathPart()}" + + override suspend fun list(duid: String): List { + val body = checked(client.get(collection(duid))) + val data = body["result"]?.takeUnless { it is JsonNull } ?: body["data"] + val rows = data as? JsonArray ?: throw DeviceApiException(0, "Unsupported schedule list") + val jobs = rows.map { + val raw = it as? JsonObject ?: throw DeviceApiException(0, "Invalid schedule record") + val id = (raw["id"] as? JsonPrimitive)?.contentOrNull + if (id.isNullOrBlank()) throw DeviceApiException(0, "Schedule has no ID") + ServerSchedule(raw) + } + if (jobs.map { it.id }.distinct().size != jobs.size) throw DeviceApiException(0, "Duplicate schedule IDs") + return jobs + } + override suspend fun create(duid: String, job: JsonObject): String { - val body = checked(client.post("/user/devices/$duid/jobs") { setBody(json(job)) }) - return body["data"]?.jsonObject?.get("id")?.jsonPrimitive?.contentOrNull + val body = checked(client.post(collection(duid)) { setBody(json(job)) }) + return ((body["result"] ?: body["data"]) as? JsonObject)?.get("id")?.jsonPrimitive?.contentOrNull ?: throw DeviceApiException(0, "The server saved the schedule but did not return its id") } override suspend fun update(duid: String, jobId: String, job: JsonObject) { - checked(client.put("/user/devices/$duid/jobs/$jobId") { setBody(json(job)) }) + checked(client.put(item(duid, jobId)) { setBody(json(job)) }) } override suspend fun delete(duid: String, jobId: String) { - checked(client.delete("/user/devices/$duid/jobs/$jobId")) + checked(client.delete(item(duid, jobId))) } private fun json(job: JsonObject) = TextContent(job.toString(), ContentType.Application.Json) @@ -45,10 +66,12 @@ class ScheduleApi(private val client: HttpClient) : ScheduleMirror { val text = response.bodyAsText() val body = runCatching { Json.parseToJsonElement(text).jsonObject }.getOrNull() val success = (body?.get("success") as? JsonPrimitive)?.contentOrNull != "false" - if (!response.status.isSuccess() || body == null || !success) { + val code = (body?.get("code") as? JsonPrimitive)?.intOrNull + if (!response.status.isSuccess() || body == null || !success || (code != null && code != 200)) { val reason = body?.get("msg")?.jsonPrimitive?.contentOrNull ?: "HTTP ${response.status.value}" throw DeviceApiException(response.status.value, "The server refused the schedule: $reason") } return body } } + diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleApi.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleApi.kt new file mode 100644 index 00000000..b176de28 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleApi.kt @@ -0,0 +1,3 @@ +package com.kodraliu.localrock.shared.schedule + +class ScheduleException(message: String) : RuntimeException(message) diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt new file mode 100644 index 00000000..95935a1d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt @@ -0,0 +1,155 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.coroutines.sync.Mutex +import kotlinx.serialization.json.* + +/** No retries or rollback: every write is preceded and followed by fresh reads. */ +class ScheduleEnablement( + private val readJobs: suspend () -> List, + private val writeJob: suspend (ServerSchedule, JsonObject) -> Unit, + private val readTimers: suspend () -> JsonElement?, + private val writeTimer: suspend (String, Boolean) -> Unit, +) { + private val mutex = Mutex() + + suspend fun save(expected: ServerSchedule, patch: JsonObject, synchronizeEnabled: Boolean): ServerSchedule { + if (!mutex.tryLock()) throw ScheduleException("A schedule save is already in progress. No additional write was sent.") + var verifiedEnabled: Boolean? = null + var robotProgress = "Robot enablement was not changed." + try { + if (!synchronizeEnabled && "enabled" in patch) { + throw ScheduleException("Enablement must use synchronization. No writes were sent.") + } + var current = readCurrent(expected.id, synchronizeEnabled) + if (current == null || snapshot(current) != snapshot(expected)) { + throw ScheduleException("This schedule changed or was deleted. Refresh before editing it again. No writes were sent.") + } + if (synchronizeEnabled) { + val enabled = (patch["enabled"] as? JsonPrimitive)?.booleanOrNull + ?: throw ScheduleException("Choose an enabled state. No writes were sent.") + val settings = current.settings + // The method is not evidence of a native timer. Only an explicit valid name is. + if (settings?.containsKey("name") == true) { + val rawName = settings["name"] as? JsonPrimitive + val name = rawName?.takeIf { it.isString }?.content?.takeIf { it.isNotBlank() } + ?: throw ScheduleException("The native timer reference is invalid. No writes were sent.") + val desired = if (enabled) "On" else "Off" + val initial = nativeTimerState(request { readTimers() }, name) + if (initial !in listOf("On", "Off")) { + throw ScheduleException("Native timer is ${initial.lowercase()}. Nothing was changed; refresh and check More details. Timers are not recreated automatically.") + } + if (initial != desired) { + // A concurrent server edit must stop us before changing the robot. + current = readCurrent(expected.id, synchronizeEnabled) + if (current == null || !matchesExpected(current, expected, initial == "On")) { + throw ScheduleException("Schedule conflict before robot update. No writes were sent; refresh.") + } + robotProgress = "A robot update was attempted; its current state is unconfirmed." + // A lost MQTT reply isn't proof of failure. Read back once, never resend. + try { request { writeTimer(name, enabled) } } + catch (e: CancellationException) { throw e } + catch (_: Exception) { /* Read-back determines whether the state was applied. */ } + val verified = try { nativeTimerState(request { readTimers() }, name) } + catch (e: CancellationException) { throw e } + catch (_: Exception) { + throw ScheduleException("$robotProgress Server job was not saved. Refresh before retrying; no rollback was attempted.") + } + if (verified != desired) { + throw ScheduleException("Robot did not confirm the requested state. Server job was not saved. Refresh before retrying; no rollback was attempted.") + } + } + verifiedEnabled = enabled + robotProgress = "Robot timer was verified ${desired.lowercase()}." + } + } + + // Recheck even when no native write was needed. Never overwrite a concurrent edit. + current = readCurrent(expected.id, synchronizeEnabled) + if (current == null || !matchesExpected(current, expected, verifiedEnabled)) { + throw ScheduleException("$robotProgress Server job changed or was deleted; it was not overwritten. Refresh. No rollback was attempted.") + } + val baseline = current + val target = ServerSchedule(JsonObject(baseline.raw + patch)) + if (snapshot(target) == snapshot(baseline)) return baseline + var writeFailed = false + try { request { writeJob(baseline, patch) } } + catch (e: CancellationException) { throw e } + catch (_: Exception) { writeFailed = true } + // HTTP success alone isn't confirmation; a failed response can also hide a saved write. + val confirmed = try { readCurrent(expected.id, synchronizeEnabled) } + catch (e: CancellationException) { throw e } + catch (_: Exception) { + throw ScheduleException("$robotProgress Server save is unconfirmed because read-back failed. Refresh before retrying; no writes were repeated or rolled back.") + } + if (confirmed != null && snapshot(confirmed) == snapshot(target)) return confirmed + val reason = when { + confirmed == null -> "The server job is missing." + snapshot(confirmed) == snapshot(baseline) -> if (writeFailed) "Server save failed; the job is unchanged." else "Server did not retain the requested changes." + else -> "Server read-back conflicts with the requested changes." + } + throw ScheduleException("$robotProgress $reason The combined save is incomplete. Refresh before retrying; no rollback was attempted.") + } catch (e: CancellationException) { + throw e + } catch (e: ScheduleException) { + if (robotProgress != "Robot enablement was not changed." && !e.message.orEmpty().startsWith(robotProgress)) { + throw ScheduleException("$robotProgress ${e.message} No rollback was attempted.") + } + throw e + } catch (_: Exception) { + throw ScheduleException("$robotProgress Could not read the current schedule or timer state. Server job was not saved. Refresh before retrying.") + } finally { + mutex.unlock() + } + } + + private suspend fun readCurrent(id: String, validateReference: Boolean): ServerSchedule? { + val jobs = request { readJobs() } + val matches = jobs.filter { it.id == id } + if (matches.size > 1) throw ScheduleException("Ambiguous server job ID. Refresh; no further writes were sent.") + val job = matches.singleOrNull() ?: return null + if (validateReference) { + val entries = job.param?.get("params") as? JsonArray + val references = entries.orEmpty().filterIsInstance().filter { "name" in it } + if (references.isNotEmpty() && job.settings == null) { + throw ScheduleException("Ambiguous native timer references in the schedule. No further writes were sent.") + } + val name = job.nativeName + if (name != null && jobs.count { other -> + val params = other.param?.get("params") as? JsonArray + params.orEmpty().filterIsInstance().any { (it["name"] as? JsonPrimitive)?.contentOrNull == name } + } > 1) { + throw ScheduleException("Multiple server jobs share this native timer. No further writes were sent; resolve the conflicting references first.") + } + } + return job + } + + /** Session timeouts cancel an inner await, not this save. Preserve actual caller cancellation. */ + private suspend fun request(block: suspend () -> T): T = try { + block() + } catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + throw ScheduleException("Connection closed or request timed out.") + } + + // #213 may reconcile enabled during native read-back. Accept only that exact, verified + // transition; edits to any other job field remain conflicts. + private fun matchesExpected(current: ServerSchedule, expected: ServerSchedule, reconciled: Boolean?): Boolean { + if (snapshot(current) == snapshot(expected)) return true + return reconciled != null && current.enabled == reconciled && + snapshot(current).filterKeys { it != "enabled" } == snapshot(expected).filterKeys { it != "enabled" } + } + + private fun snapshot(job: ServerSchedule): JsonObject = JsonObject(job.snapshot().toMutableMap().apply { + // The server can serialize param as either an object or a JSON string. + job.param?.let { put("param", it) } + }) +} + +/** Captured native RPC shape; timer name and HTTP job ID must never be interchanged. */ +fun nativeTimerUpdateParams(name: String, enabled: Boolean): List = + listOf(JsonArray(listOf(JsonPrimitive(name), JsonPrimitive(if (enabled) "on" else "off")))) + diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt new file mode 100644 index 00000000..73ca4257 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt @@ -0,0 +1,41 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.serialization.json.* + +/** Complete a native creation with one HTTP POST, then read back even if its response was lost. */ +class ServerJobCreation( + private val readTimers: suspend () -> JsonElement?, + private val createJob: suspend (JsonObject) -> String, + private val readJobs: suspend () -> List, +) { + suspend fun confirm(name: String, body: JsonObject): ServerSchedule { + try { + if (nativeTimerState(request { readTimers() }, name) != "On") { + throw ScheduleException("Native timer creation could not be verified. Server job was not created.") + } + var returnedId: String? = null + try { returnedId = request { createJob(body) } } + catch (e: CancellationException) { throw e } + catch (_: Exception) { /* Lost response is not proof of failure. Do not repeat POST. */ } + val matches = request { readJobs() }.filter { it.nativeName == name } + val saved = matches.singleOrNull() + if (saved != null && (returnedId == null || returnedId == saved.id) && + body.filterKeys { it != "id" }.all { (key, value) -> + (if (key == "param") saved.param else saved.raw[key]) == value + }) return saved + throw ScheduleException("Matching server job is missing, ambiguous or different.") + } catch (e: CancellationException) { throw e } + catch (e: Exception) { + throw ScheduleException("Native creation was attempted; combined save is unconfirmed. ${e.message.orEmpty()} No timer was deleted and no write was repeated. Refresh before retrying.") + } + } + + private suspend fun request(block: suspend () -> T): T = try { block() } + catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + throw ScheduleException("Connection closed or request timed out.") + } +} diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt new file mode 100644 index 00000000..81b6be46 --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt @@ -0,0 +1,69 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive +import kotlinx.serialization.json.* + +/** Verify each side of a deletion; uncertain writes are read back, never repeated or rolled back. */ +class ServerJobDeletion( + private val readJobs: suspend () -> List, + private val readTimers: suspend () -> JsonElement?, + private val deleteTimer: suspend (String) -> Unit, + private val deleteJob: suspend (String) -> Unit, +) { + suspend fun delete(expected: ServerSchedule) { + var progress = "Nothing was deleted." + try { + val jobs = request { readJobs() } + val current = jobs.filter { it.id == expected.id }.singleOrNull() + if (current == null || normalized(current) != normalized(expected)) { + throw ScheduleException("Schedule changed or was deleted. Refresh before deleting it.") + } + val entries = current.param?.get("params") as? JsonArray + val references = entries.orEmpty().filterIsInstance().filter { "name" in it } + if (references.isNotEmpty()) { + val rawName = current.settings?.get("name") as? JsonPrimitive + val name = rawName?.takeIf { it.isString }?.content?.takeIf { it.isNotBlank() } + ?: throw ScheduleException("Missing or ambiguous native timer reference.") + if (jobs.count { job -> + (job.param?.get("params") as? JsonArray).orEmpty().filterIsInstance() + .any { (it["name"] as? JsonPrimitive)?.contentOrNull == name } + } != 1) throw ScheduleException("Multiple jobs share this native timer; resolve the references first.") + val state = nativeTimerState(request { readTimers() }, name) + if (state !in listOf("On", "Off")) throw ScheduleException("Native timer is ${state.lowercase()}; deletion stopped.") + val fresh = request { readJobs() }.filter { it.id == expected.id }.singleOrNull() + if (fresh == null || normalized(fresh) != normalized(expected)) throw ScheduleException("Schedule changed before native deletion.") + progress = "Native deletion was attempted; its state is unconfirmed." + try { request { deleteTimer(name) } } + catch (e: CancellationException) { throw e } + catch (_: Exception) { /* Inspect the result, without retrying the write. */ } + if (nativeTimerState(request { readTimers() }, name) != "Missing") { + throw ScheduleException("Native timer deletion was not confirmed; the server job was retained.") + } + progress = "Native timer deletion was confirmed." + } + val fresh = request { readJobs() }.filter { it.id == expected.id }.singleOrNull() + if (fresh == null || normalized(fresh) != normalized(expected)) { + throw ScheduleException("Server job changed or disappeared; no server delete was sent.") + } + progress += " Server deletion was attempted." + try { request { deleteJob(expected.id) } } + catch (e: CancellationException) { throw e } + catch (_: Exception) { /* A lost acknowledgement may still mean success. */ } + if (request { readJobs() }.any { it.id == expected.id }) { + throw ScheduleException("Server job deletion was not confirmed.") + } + } catch (e: CancellationException) { throw e } + catch (e: Exception) { + throw ScheduleException("$progress ${e.message ?: "Could not verify the current state."} Refresh before retrying; no rollback was attempted.") + } + } + + private fun normalized(job: ServerSchedule) = JsonObject(job.snapshot() + listOfNotNull(job.param?.let { "param" to it }).toMap()) + private suspend fun request(block: suspend () -> T): T = try { block() } + catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + throw ScheduleException("Connection closed or request timed out.") + } +} diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt new file mode 100644 index 00000000..5eb17d6a --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt @@ -0,0 +1,112 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.serialization.json.* + +/** Keep the original payload: firmware-specific fields must survive edits. */ +data class ServerSchedule(val raw: JsonObject) { + val id: String get() = requireNotNull((raw["id"] as? JsonPrimitive)?.contentOrNull) + val cron: String get() = (raw["cron"] as? JsonPrimitive)?.contentOrNull.orEmpty() + val timezone: String get() = (raw["timeZoneId"] as? JsonPrimitive)?.contentOrNull.orEmpty() + val enabled: Boolean get() = (raw["enabled"] as? JsonPrimitive)?.booleanOrNull ?: false + val repeated: Boolean get() = (raw["repeated"] as? JsonPrimitive)?.booleanOrNull ?: true + val nextFire: String? get() = (raw["nextFireTime"] as? JsonPrimitive)?.contentOrNull + val param: JsonObject? get() = when (val value = raw["param"]) { + is JsonObject -> value + is JsonPrimitive -> runCatching { Json.parseToJsonElement(value.content) as? JsonObject }.getOrNull() + else -> null + } + val settings: JsonObject? get() = (param?.get("params") as? JsonArray)?.singleOrNull() as? JsonObject + val nativeName: String? get() = (settings?.get("name") as? JsonPrimitive)?.contentOrNull + val mapIndex: String? get() = (settings?.get("map_index") as? JsonPrimitive)?.contentOrNull + val weekly: WeeklyTime? get() = WeeklyTime.parse(cron) + val editable: Boolean get() = weekly != null && timezone.isNotBlank() && settings != null && + (param?.get("method") as? JsonPrimitive)?.content == "server_scheduled_start" + + fun settingsText(key: String): String = (settings?.get(key) as? JsonPrimitive)?.contentOrNull.orEmpty() + + /** Only changed settings are supplied; omitted model fields and native timer identity survive. */ + fun update(time: WeeklyTime, zone: String, enabled: Boolean, changes: Map = emptyMap(), repeated: Boolean = this.repeated): JsonObject { + require(editable) { "This schedule format is read-only" } + require(zone.isNotBlank()) { "Enter an IANA timezone" } + require(changes.keys.all { it in EDITABLE_SETTINGS }) { "Unsupported setting" } + return buildJsonObject { + put("cron", time.cron()) + put("timeZoneId", zone.trim()) + put("enabled", enabled) + put("repeated", repeated) + if (changes.isNotEmpty()) { + put("param", JsonObject(param!!.toMutableMap().apply { + put("params", JsonArray(listOf(JsonObject(settings!!.toMutableMap().apply { putAll(changes) })))) + })) + } + } + } + + // nextFireTime changes with time and is not part of a user's editable snapshot. + fun snapshot(): JsonObject = JsonObject(raw.filterKeys { it != "nextFireTime" }) + + companion object { + val EDITABLE_SETTINGS = setOf("segments", "repeat", "fan_power", "water_box_mode", "mop_mode") + fun create(time: WeeklyTime, zone: String, settings: Map, repeated: Boolean = true): JsonObject { + require(zone.isNotBlank()) { "Enter an IANA timezone" } + require(settings.keys.all { it in EDITABLE_SETTINGS }) + return buildJsonObject { + put("cron", time.cron()); put("timeZoneId", zone.trim()) + // New jobs are explicitly enabled after review, not while editing. + put("enabled", false); put("repeated", repeated); put("type", "clean") + put("param", buildJsonObject { + put("id", 1); put("method", "server_scheduled_start") + put("params", JsonArray(listOf(buildJsonObject { + put("repeat", 1); put("segments", "0") + settings.forEach { (key, value) -> put(key, value) } + }))) + }) + } + } + } +} + +data class WeeklyTime(val hour: Int, val minute: Int, val days: Set) { + fun cron(): String { + require(hour in 0..23 && minute in 0..59 && days.isNotEmpty() && days.all { it in 0..6 }) { + "Choose a valid time and at least one weekday" + } + return "$minute $hour ? * ${days.sorted().joinToString(",")}" + } + companion object { + /** Only losslessly editable weekly patterns; never turn dated/complex cron into daily. */ + fun parse(cron: String): WeeklyTime? { + val parts = cron.trim().split(Regex("\\s+")) + if (parts.size != 5 || parts[2] !in listOf("*", "?") || parts[3] != "*") return null + val minute = parts[0].toIntOrNull()?.takeIf { it in 0..59 } ?: return null + val hour = parts[1].toIntOrNull()?.takeIf { it in 0..23 } ?: return null + val days = mutableSetOf() + if (parts[4] in listOf("*", "?")) days.addAll(0..6) else { + for (item in parts[4].split(',')) { + val range = item.split('-') + if (range.size !in 1..2) return null + val start = range[0].toIntOrNull()?.takeIf { it in 0..7 } ?: return null + val end = range.last().toIntOrNull()?.takeIf { it in start..7 } ?: return null + (start..end).forEach { days.add(it % 7) } + } + } + return WeeklyTime(hour, minute, days).takeIf { days.isNotEmpty() } + } + } +} + +/** Native timer state is independent of the server job's enabled flag. */ +fun nativeTimerState(result: JsonElement?, name: String): String { + val entries = result as? JsonArray ?: return "Unknown" + val matches = entries.filterIsInstance().filter { + (it.getOrNull(0) as? JsonPrimitive)?.let { id -> id.isString && id.content == name } == true + } + if (matches.isEmpty()) return "Missing" + if (matches.size != 1) return "Ambiguous" + return when ((matches.single().getOrNull(1) as? JsonPrimitive)?.contentOrNull) { + "on" -> "On" + "off" -> "Off" + else -> "Unknown" + } +} + diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt index 7f7ad174..cc5e514e 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt @@ -1,5 +1,6 @@ package com.kodraliu.localrock.shared.vacuum +import com.kodraliu.localrock.shared.schedule.ServerSchedule import kotlinx.serialization.json.JsonElement import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive @@ -14,6 +15,8 @@ data class CleanTimer( val weekdays: Set, // 0=Sun, 1=Mon … 6=Sat; empty means every day, unless [date] is set val settings: TimerSettings = TimerSettings(), val date: TimerDate? = null, // set for a one-time schedule, which runs on that day only + val serverJob: ServerSchedule? = null, + val editable: Boolean = true, ) /** @@ -30,7 +33,7 @@ data class TimerSettings( val waterBoxMode: Int? = null, val mopMode: Int? = null, val repeat: Int? = null, - // Carried by server_timer schedules, never set by this app's own UI yet: which rooms to + // Carried by server_timer schedules: which rooms to // clean ("0" for the whole home), whether mopping is on, and which saved map to use. val segments: String? = null, val cleanMop: Int? = null, @@ -38,9 +41,8 @@ data class TimerSettings( // The official app maintains a second, independent copy of a server_timer schedule over // HTTP (POST/PUT /user/devices/{duid}/jobs), its own cloud-sync record with its own id, not // the robot's. That copy's settings carry this "name" field, the real server_timer id it - // mirrors, confirmed live. get_timer answers from that HTTP-side store, so a schedule read - // from it is this mirror, not the robot's real entry: editing or deleting it must use this - // id, not the timer's own [CleanTimer.id], or the write lands on nothing the robot has. + // mirrors. HTTP jobs carry this native reference separately from the job ID. Native + // commands must use this name, not [CleanTimer.id]. A job without it is server-only. // Never sent back out in [toActionObject]; the robot's own entries never carry it. val serverTimerId: String? = null, ) @@ -161,3 +163,4 @@ fun TimerSettings.summary(): String? { repeat?.takeIf { it > 1 }?.let { parts += "$it passes" } return parts.takeIf { it.isNotEmpty() }?.joinToString(" · ") } + diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt index 7fb1493f..ec29c1e4 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt @@ -1,5 +1,6 @@ package com.kodraliu.localrock.shared.vacuum +import com.kodraliu.localrock.shared.schedule.ServerSchedule import kotlinx.serialization.json.JsonArray import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive @@ -13,6 +14,7 @@ import kotlinx.serialization.json.JsonPrimitive * from, so a schedule without one never shows in this app's own list either. Both confirmed live. */ interface ScheduleMirror { + suspend fun list(duid: String): List /** Adds the record and returns the id the cloud gave it. */ suspend fun create(duid: String, job: JsonObject): String suspend fun update(duid: String, jobId: String, job: JsonObject) @@ -59,3 +61,4 @@ internal fun mirrorJobBody( fields["param"] = param return JsonObject(fields) } + diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt new file mode 100644 index 00000000..94f1b71d --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt @@ -0,0 +1,60 @@ +package com.kodraliu.localrock.shared.vacuum + +import com.kodraliu.localrock.shared.schedule.ScheduleException +import com.kodraliu.localrock.shared.schedule.ServerSchedule +import kotlinx.serialization.json.* +import kotlinx.datetime.LocalDate + +/** Unsupported jobs stay visible rather than becoming a misleading empty schedule list. */ +internal fun ServerSchedule.toCleanTimer(): CleanTimer { + val weekly = weekly + val parts = cron.trim().split(Regex("\\s+")) + val dated = if (parts.size == 5 && parts[4] in listOf("?", "*")) { + val day = parts[2].toIntOrNull() + val month = parts[3].toIntOrNull() + if (day != null && month != null && runCatching { LocalDate(2000, month, day) }.isSuccess) TimerDate(month, day) else null + } else null + val h = parts.getOrNull(1)?.toIntOrNull()?.takeIf { it in 0..23 } + val m = parts.getOrNull(0)?.toIntOrNull()?.takeIf { it in 0..59 } + val supported = (weekly != null || dated != null) && h != null && m != null && settings != null && + (param?.get("method") as? JsonPrimitive)?.contentOrNull == "server_scheduled_start" + return CleanTimer(id, enabled, h ?: 0, m ?: 0, weekly?.days ?: emptySet(), + parseTimerSettings(settings), dated, this, supported) +} + +/** Patch only user edits. Native identity, room order and unknown firmware fields survive. */ +internal fun serverJobEditPatch( + timer: CleanTimer, + hour: Int, + minute: Int, + weekdays: Set, + settings: TimerSettings, + once: Boolean, + date: TimerDate?, + settingsChanged: Boolean, + timingChanged: Boolean, +): JsonObject { + val job = timer.serverJob ?: throw ScheduleException("This is not a server job") + if (!timer.editable) throw ScheduleException("This schedule format is read-only") + return buildJsonObject { + if (timingChanged) { + put("cron", mirrorCron(minute, hour, if (once) emptySet() else weekdays, date)) + put("repeated", !once) + } + if (settingsChanged) { + val before = timer.settings.toActionObject() + val after = settings.toActionObject() + val edited = job.settings!!.toMutableMap() + // Only the dialog's cleaning controls can change these fields. Rooms/map/name stay intact. + for (key in listOf("fan_power", "water_box_mode", "mop_mode", "repeat")) { + if (before[key] != after[key]) { + val value = after[key] + if (value == null) edited.remove(key) else edited[key] = value + } + } + if (JsonObject(edited) != job.settings) { + put("param", JsonObject(job.param!! + ("params" to JsonArray(listOf(JsonObject(edited)))))) + } + } + } +} diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt index bd966b4f..9b9c3ef8 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt @@ -10,11 +10,9 @@ import kotlinx.serialization.json.jsonPrimitive /** * A newer, separate scheduling protocol some firmware speaks instead of (or alongside) - * get/set/upd/del_timer. Confirmed live against a Roborock Qrevo: the robot stores this kind - * of schedule itself and fires it autonomously from its own clock, no app, cloud, or server - * involvement needed once it is saved. Firmware that only understands this shape rejects the - * legacy set_timer with `-10005 "timer type error"` (see LocalRock #28), not because the - * settings are wrong, but because the envelope itself is unrecognised. + * get/set/upd/del_timer. Native entries retain identity and settings; their presence alone does + * not establish autonomous execution. Server-linked jobs require the server scheduler to dispatch + * the due clean. Firmware may reject the legacy envelope with -10005 "timer type error". * * Which protocol a robot wants is not guesswork: the official app decides it from * `app_get_init_status`'s `result[0].local_info.featureset`, bit 0. See [usesServerTimer]. @@ -31,6 +29,7 @@ internal fun parseServerTimerEntry(row: JsonElement): ServerTimerEntry? { if (fields.size < 3) return null val id = fields[0].jsonPrimitive.contentOrNull ?: return null val status = fields[1].jsonPrimitive.contentOrNull + if (status != "on" && status != "off") return null val mapIndex = fields[2].jsonPrimitive.contentOrNull?.toIntOrNull() ?: -1 return ServerTimerEntry(id = id, enabled = status == "on", mapIndex = mapIndex) } @@ -103,3 +102,4 @@ internal fun usesServerTimer(initStatusResult: JsonElement?): Boolean? { val featureSet = localInfo["featureset"]?.jsonPrimitive?.contentOrNull?.toIntOrNull() ?: return null return (featureSet and 1) != 0 } + diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt index f8b6a7f4..4cc656be 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt @@ -1,6 +1,9 @@ package com.kodraliu.localrock.shared.vacuum import com.kodraliu.localrock.shared.device.DeviceApiException +import com.kodraliu.localrock.shared.schedule.* +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive import com.kodraliu.localrock.shared.model.Room import com.kodraliu.localrock.shared.mqtt.MqttClient import com.kodraliu.localrock.shared.mqtt.MqttTopics @@ -845,7 +848,7 @@ class VacuumRepository( /** A server_timer id is a millisecond timestamp, confirmed live; legacy ones are second-based. */ private fun newTimerId(useServerTimer: Boolean): String = - if (useServerTimer) (nowEpochSeconds().toLong() * 1000).toString() else nowEpochSeconds().toString() + if (useServerTimer) (nowEpochSeconds().toLong() * 1000 + kotlin.random.Random.nextInt(1000)).toString() else nowEpochSeconds().toString() private suspend fun saveTimerEntry( useServerTimer: Boolean, @@ -855,6 +858,8 @@ class VacuumRepository( settings: TimerSettings, ) { if (useServerTimer) { + val existing = session.getServerTimer().also { it.requireOk("get_server_timer") }.result + if (nativeTimerState(existing, id) != "Missing") throw ScheduleException("Native timer ID already exists or could not be checked. No timer was overwritten.") // The robot refuses a server_timer entry that leaves any field out ("Param error"); the // official app always sends every one, so what the schedule leaves open is filled in. session.setServerTimer(id, cron, settings.completedForServerTimer()).requireOk("set_server_timer") @@ -863,20 +868,53 @@ class VacuumRepository( } } - // get_server_timer's own answer has no cron or settings to show (just id, on/off, and a map - // index), so the list always reads from legacy get_timer instead. For a server_timer robot - // that answer is not the robot's own state either: it is the official app's separate HTTP-side - // mirror (POST/PUT /user/devices/{duid}/jobs), confirmed live, which is why its settings carry - // the "name" field [parseTimerSettings] reads into [TimerSettings.serverTimerId], the real - // robot-side id to use when writing back. A robot that never mirrors there just won't show its - // server_timer schedules here, a known gap, not a silently wrong answer. + private val scheduleWrites = Mutex() + private suspend fun scheduleWrite(action: suspend () -> T): T { + if (!scheduleWrites.tryLock()) throw ScheduleException("A schedule save is already in progress. No additional write was sent.") + try { return action() } + catch (e: CancellationException) { + currentCoroutineContext().ensureActive() + throw ScheduleException("Schedule request timed out. Its final state is unconfirmed; refresh before retrying. No automatic retry was sent.") + } finally { scheduleWrites.unlock() } + } + + private val scheduleEnablement by lazy { + ScheduleEnablement( + readJobs = { requireNotNull(scheduleMirror).list(duid) }, + writeJob = { job, patch -> requireNotNull(scheduleMirror).update(duid, job.id, patch) }, + readTimers = { session.getServerTimer().also { it.requireOk("get_server_timer") }.result }, + writeTimer = { name, enabled -> session.updServerTimer(name, enabled).requireOk("upd_server_timer") }, + ) + } + + /** Only an unavailable collection permits legacy fallback; an empty jobs list does not. */ suspend fun fetchTimers() { + if (scheduleMirror != null && !demo) { + try { + _timers.value = scheduleMirror.list(duid).map { it.toCleanTimer() } + .sortedWith(compareBy { it.hour }.thenBy { it.minute }.thenBy { it.id }) + return + } catch (e: DeviceApiException) { + if (e.responseCode != 404 && e.responseCode != 405) throw e + } + } val resp = session.getTimer() - val result = resp.result as? JsonArray ?: return - _timers.value = parseTimerList(result) + resp.requireOk("get_timer") + _timers.value = parseTimerList(resp.result) + } + + suspend fun nativeScheduleState(timer: CleanTimer): String { + val job = timer.serverJob ?: return "Not checked" + val name = job.nativeName ?: return "No native timer reference" + val reply = session.getServerTimer() + reply.requireOk("get_server_timer") + return nativeTimerState(reply.result, name) } - suspend fun createTimer( + suspend fun createTimer(hour: Int, minute: Int, weekdays: Set, settings: TimerSettings = TimerSettings(), once: Boolean = false): CleanTimer = + scheduleWrite { createTimerInternal(hour, minute, weekdays, settings, once) } + + private suspend fun createTimerInternal( hour: Int, minute: Int, weekdays: Set, @@ -885,12 +923,19 @@ class VacuumRepository( ): CleanTimer { val date = if (once) nextOccurrence(hour, minute) else null val cron = buildCron(minute, hour, if (once) emptySet() else weekdays, date) - var useServerTimer = prefersServerTimer() + val jobsSupported = if (scheduleMirror == null || demo) false else try { + scheduleMirror.list(duid) + true + } catch (e: DeviceApiException) { + if (e.responseCode != 404 && e.responseCode != 405) throw e + false + } + var useServerTimer = prefersServerTimer() && jobsSupported var id = newTimerId(useServerTimer) try { saveTimerEntry(useServerTimer, id, cron, enabled = true, settings = settings) } catch (e: RobotCommandException) { - if (!e.isTimerTypeMismatch()) throw e + if (!e.isTimerTypeMismatch() || !jobsSupported) throw e useServerTimer = !useServerTimer serverTimerPreferred = useServerTimer id = newTimerId(useServerTimer) @@ -901,24 +946,21 @@ class VacuumRepository( var timerId = id if (useServerTimer) { timerSettings = settings.completedForServerTimer().copy(serverTimerId = id) - try { - timerId = createCloudRecord(id, minute, hour, newWeekdays, date, timerSettings) - } catch (e: DeviceApiException) { - // A server without the jobs endpoint (not yet on a release with it) answers 404 or - // 405. The robot's own schedule was already removed, so save it the legacy way, - // which robots that carry the server_timer flag still accept on such a server. - if (e.responseCode != 404 && e.responseCode != 405) throw e - serverTimerPreferred = false - id = newTimerId(false) - saveTimerEntry(false, id, cron, enabled = true, settings = settings) - timerSettings = settings - timerId = id - } + timerId = createCloudRecord(id, minute, hour, newWeekdays, date, timerSettings) + val confirmed = requireNotNull(scheduleMirror).list(duid).singleOrNull { it.id == timerId } + ?: throw ScheduleException("Native timer was created but the server job could not be confirmed. Refresh; do not repeat creation.") + fetchTimers() + return confirmed.toCleanTimer() } + val timer = CleanTimer( id = timerId, enabled = true, hour = hour, minute = minute, weekdays = newWeekdays, settings = timerSettings, date = date, ) + if (jobsSupported) { + fetchTimers() + return _timers.value.singleOrNull { it.id == timer.id } ?: timer + } _timers.value = _timers.value + timer return timer } @@ -927,7 +969,7 @@ class VacuumRepository( * Adds the cloud's record of the server_timer schedule [robotId] just saved on the robot, and * returns the record's own id. Without it the official app deletes the robot's schedule as a * stray, and this app's list, which reads the records, would not show it. If the record cannot - * be written the robot's schedule is removed again, so nothing is left half saved. + * be confirmed, preserve the native entry and report the partial save for explicit recovery. */ private suspend fun createCloudRecord( robotId: String, @@ -946,12 +988,11 @@ class VacuumRepository( robotId = robotId, forCreate = true, ) - try { - return mirror.create(duid, body) - } catch (e: Exception) { - runCatching { session.delServerTimer(robotId) } - throw e - } + return ServerJobCreation( + readTimers = { session.getServerTimer().also { it.requireOk("get_server_timer") }.result }, + createJob = { mirror.create(duid, it) }, + readJobs = { mirror.list(duid) }, + ).confirm(robotId, body).id } /** Rewrites the cloud record [jobId] of a server_timer schedule to match what the robot now holds. */ @@ -989,11 +1030,31 @@ class VacuumRepository( if (useServerTimer) timer.settings.serverTimerId ?: timer.id else timer.id /** - * Rewrites [timer]'s time, days and options; its id and on/off state are kept. The old schedule - * is deleted and added again rather than overwritten, so an option that was dropped is simply - * absent and no firmware has to accept a null. If the new one is refused the old one is put back. + * Server jobs are patched without recreating native entries or changing enablement unless + * explicitly requested. Legacy-only records retain their protocol-specific edit path. */ suspend fun updateTimer( + timer: CleanTimer, hour: Int, minute: Int, weekdays: Set, settings: TimerSettings, + once: Boolean = false, settingsChanged: Boolean = true, timingChanged: Boolean = true, + enabled: Boolean = timer.enabled, + ): CleanTimer = scheduleWrite { + val job = timer.serverJob + if (job != null) { + val date = if (once) { + if (timer.date != null && hour == timer.hour && minute == timer.minute) timer.date + else nextTimerDate(nowEpochSeconds().toLong(), + if (job.timezone.isBlank()) TimeZone.currentSystemDefault() else TimeZone.of(job.timezone), hour, minute) + } else null + val patch = serverJobEditPatch(timer, hour, minute, weekdays, settings, once, date, settingsChanged, timingChanged) + val sync = enabled != timer.enabled + val combined = if (sync) JsonObject(patch + ("enabled" to JsonPrimitive(enabled))) else patch + val saved = scheduleEnablement.save(job, combined, sync).toCleanTimer() + _timers.value = _timers.value.map { if (it.id == saved.id) saved else it } + saved + } else updateTimerInternal(timer, hour, minute, weekdays, settings, once) + } + + private suspend fun updateTimerInternal( timer: CleanTimer, hour: Int, minute: Int, @@ -1004,22 +1065,23 @@ class VacuumRepository( val date = if (once) nextOccurrence(hour, minute) else null val newWeekdays = if (once) emptySet() else weekdays val cron = buildCron(minute, hour, newWeekdays, date) - val useServerTimer = prefersServerTimer() + // A legacy-view record without a native name must use its legacy ID, even on a + // model whose feature flag advertises server_timer (the old-server fallback case). + val useServerTimer = timer.settings.serverTimerId != null val id = robotId(timer, useServerTimer) // The new settings come from the edit dialog's own choices, which know nothing of the // mirror link; carry it forward so a second edit can still find the real robot-side id. - val newSettings = settings.copy(serverTimerId = timer.settings.serverTimerId) + val newSettings = settings.copy(serverTimerId = timer.settings.serverTimerId, segments = timer.settings.segments, mapIndex = timer.settings.mapIndex, cleanMop = timer.settings.cleanMop) if (useServerTimer) session.delServerTimer(id).requireOk("del_server_timer") else session.delTimer(id).requireOk("del_timer") try { saveTimerEntry(useServerTimer, id, cron, enabled = timer.enabled, settings = newSettings) - } catch (e: Exception) { - runCatching { - val oldCron = buildCron(timer.minute, timer.hour, timer.weekdays, timer.date) - saveTimerEntry(useServerTimer, id, oldCron, enabled = timer.enabled, settings = timer.settings) - } - throw e + if (useServerTimer && !timer.enabled) session.updServerTimer(id, false).requireOk("upd_server_timer") + } catch (e: CancellationException) { throw e } + catch (_: Exception) { + throw ScheduleException("The old native timer was removed, but its replacement could not be confirmed. Refresh before retrying; no rollback was attempted.") } + if (useServerTimer) { updateCloudRecord(timer.id, id, minute, hour, newWeekdays, date, timer.enabled, newSettings) } @@ -1030,9 +1092,20 @@ class VacuumRepository( return updated } - suspend fun toggleTimer(timer: CleanTimer) { + suspend fun toggleTimer(timer: CleanTimer) = scheduleWrite { + val job = timer.serverJob + if (job != null) { + val saved = scheduleEnablement.save(job, + JsonObject(mapOf("enabled" to JsonPrimitive(!timer.enabled))), true).toCleanTimer() + _timers.value = _timers.value.map { if (it.id == saved.id) saved else it } + } else toggleLegacyTimer(timer) + } + + private suspend fun toggleLegacyTimer(timer: CleanTimer) { val updated = timer.copy(enabled = !timer.enabled) - val useServerTimer = prefersServerTimer() + // A legacy-view record without a native name must use its legacy ID, even on a + // model whose feature flag advertises server_timer (the old-server fallback case). + val useServerTimer = timer.settings.serverTimerId != null val id = robotId(timer, useServerTimer) if (useServerTimer) { session.updServerTimer(id, updated.enabled).requireOk("upd_server_timer") @@ -1045,8 +1118,23 @@ class VacuumRepository( _timers.value = _timers.value.map { if (it.id == timer.id) updated else it } } - suspend fun deleteTimer(timer: CleanTimer) { - val useServerTimer = prefersServerTimer() + suspend fun deleteTimer(timer: CleanTimer) = scheduleWrite { + val job = timer.serverJob + if (job != null) { + ServerJobDeletion( + readJobs = { requireNotNull(scheduleMirror).list(duid) }, + readTimers = { session.getServerTimer().also { it.requireOk("get_server_timer") }.result }, + deleteTimer = { session.delServerTimer(it).requireOk("del_server_timer") }, + deleteJob = { requireNotNull(scheduleMirror).delete(duid, it) }, + ).delete(job) + _timers.value = _timers.value.filter { it.id != timer.id } + } else deleteLegacyTimer(timer) + } + + private suspend fun deleteLegacyTimer(timer: CleanTimer) { + // A legacy-view record without a native name must use its legacy ID, even on a + // model whose feature flag advertises server_timer (the old-server fallback case). + val useServerTimer = timer.settings.serverTimerId != null val id = robotId(timer, useServerTimer) if (useServerTimer) { session.delServerTimer(id).requireOk("del_server_timer") @@ -1497,3 +1585,4 @@ internal fun VacuumStatus.applyDpsPush(push: Map): VacuumStatu dryStatus = dryStatus, ) } + diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt index 0beb0f5e..ecd86624 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt @@ -67,6 +67,9 @@ import com.kodraliu.localrock.shared.vacuum.kind import com.kodraliu.localrock.shared.vacuum.summary import com.kodraliu.localrock.shared.vacuum.timerSettingsFor import kotlinx.coroutines.launch +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.currentCoroutineContext +import kotlinx.coroutines.ensureActive @OptIn(ExperimentalMaterial3Api::class) @Composable @@ -79,20 +82,34 @@ fun ScheduleScreen( val timers by repository.timers.collectAsState() var showAddDialog by remember { mutableStateOf(false) } var editing by remember { mutableStateOf(null) } + var loading by remember { mutableStateOf(true) } + var loadError by remember { mutableStateOf(null) } + var saving by remember { mutableStateOf(false) } + var refresh by remember { mutableIntStateOf(0) } val snackbarHostState = remember { SnackbarHostState() } - LaunchedEffect(Unit) { runCatching { repository.fetchTimers() } } + LaunchedEffect(refresh) { + loading = true + loadError = null + try { repository.fetchTimers() } + catch (e: CancellationException) { currentCoroutineContext().ensureActive(); loadError = "Schedule request timed out. Retry to refresh." } + catch (e: Exception) { loadError = e.message ?: "Could not load schedules" } + finally { loading = false } + } // A refused save is shown, and the list is read back so it matches what the robot really holds. fun saveTimer(action: suspend () -> Unit) { + if (saving) return + saving = true scope.launch { try { action() - } catch (e: Exception) { + } catch (e: CancellationException) { throw e } + catch (e: Exception) { runCatching { repository.fetchTimers() } snackbarHostState.showSnackbar(e.message ?: "The schedule could not be saved") - } + } finally { saving = false } } } @@ -107,12 +124,17 @@ fun ScheduleScreen( ) }, floatingActionButton = { - FloatingActionButton(onClick = { showAddDialog = true }) { + if (!saving && !loading && loadError == null) FloatingActionButton(onClick = { showAddDialog = true }) { Icon(Icons.Default.Add, "Add schedule") } }, ) { padding -> - if (timers.isEmpty()) { + if (loading || loadError != null) { + Column(Modifier.fillMaxSize().padding(padding).padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + Text(if (loading) "Loading schedules…" else loadError.orEmpty()) + if (!loading) TextButton(onClick = { refresh++ }) { Text("Retry") } + } + } else if (timers.isEmpty()) { Box(Modifier.fillMaxSize().padding(padding), contentAlignment = Alignment.Center) { Column(horizontalAlignment = Alignment.CenterHorizontally, verticalArrangement = Arrangement.spacedBy(12.dp)) { Icon(Icons.Default.Schedule, null, Modifier.size(48.dp), MaterialTheme.colorScheme.onSurfaceVariant) @@ -127,10 +149,11 @@ fun ScheduleScreen( } } else { LazyColumn(contentPadding = padding) { - items(timers, key = { it.id }) { timer -> + items(timers.sortedWith(compareBy { it.hour }.thenBy { it.minute }.thenBy { it.id }), key = { it.id }) { timer -> TimerRow( timer = timer, - onEdit = { editing = timer }, + busy = saving, + onEdit = { if (timer.editable) editing = timer }, onToggle = { saveTimer { repository.toggleTimer(timer) } }, onDelete = { saveTimer { repository.deleteTimer(timer) } }, ) @@ -146,7 +169,7 @@ fun ScheduleScreen( supportsSmartPlan = viewModel.supportsSmartPlan, supportsFastRoute = viewModel.supportsFastRoute, supportsWaterSlide = viewModel.supportsWaterSlide, - onSave = { hour, minute, weekdays, settings, once -> + onSave = { hour, minute, weekdays, settings, once, _, _, _ -> showAddDialog = false saveTimer { repository.createTimer(hour, minute, weekdays, settings, once) } }, @@ -160,19 +183,20 @@ fun ScheduleScreen( supportsSmartPlan = viewModel.supportsSmartPlan, supportsFastRoute = viewModel.supportsFastRoute, supportsWaterSlide = viewModel.supportsWaterSlide, - onSave = { hour, minute, weekdays, settings, once -> + onSave = { hour, minute, weekdays, settings, once, settingsChanged, timingChanged, enabled -> editing = null - saveTimer { repository.updateTimer(timer, hour, minute, weekdays, settings, once) } + saveTimer { repository.updateTimer(timer, hour, minute, weekdays, settings, once, settingsChanged, timingChanged, enabled) } }, + readNativeState = { repository.nativeScheduleState(timer) }, onDismiss = { editing = null }, ) } } @Composable -private fun TimerRow(timer: CleanTimer, onEdit: () -> Unit, onToggle: () -> Unit, onDelete: () -> Unit) { +private fun TimerRow(timer: CleanTimer, busy: Boolean, onEdit: () -> Unit, onToggle: () -> Unit, onDelete: () -> Unit) { Row( - modifier = Modifier.fillMaxWidth().clickable(onClick = onEdit).padding(horizontal = 16.dp, vertical = 12.dp), + modifier = Modifier.fillMaxWidth().clickable(enabled = !busy && timer.editable, onClick = onEdit).padding(horizontal = 16.dp, vertical = 12.dp), verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(16.dp), ) { @@ -187,7 +211,7 @@ private fun TimerRow(timer: CleanTimer, onEdit: () -> Unit, onToggle: () -> Unit } Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { Text( - formatClock(timer.hour, timer.minute, rememberUse24HourClock()), + if (timer.editable) formatClock(timer.hour, timer.minute, rememberUse24HourClock()) else timer.serverJob?.cron.orEmpty(), style = MaterialTheme.typography.titleMedium, fontWeight = FontWeight.SemiBold, color = if (timer.enabled) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, @@ -197,6 +221,10 @@ private fun TimerRow(timer: CleanTimer, onEdit: () -> Unit, onToggle: () -> Unit style = MaterialTheme.typography.bodySmall, color = MaterialTheme.colorScheme.onSurfaceVariant, ) + if (!timer.editable) Text("Unsupported format · read-only editor", style = MaterialTheme.typography.bodySmall) + timer.settings.segments?.let { rooms -> + Text(if (rooms == "0" || rooms.isBlank()) "Full" else "Rooms: $rooms", style = MaterialTheme.typography.bodySmall) + } timer.settings.summary()?.let { summary -> Text( summary, @@ -205,10 +233,10 @@ private fun TimerRow(timer: CleanTimer, onEdit: () -> Unit, onToggle: () -> Unit ) } } - IconButton(onClick = onDelete) { + IconButton(onClick = onDelete, enabled = !busy) { Icon(Icons.Default.Delete, "Delete", tint = MaterialTheme.colorScheme.onSurfaceVariant) } - Switch(checked = timer.enabled, onCheckedChange = { onToggle() }) + Switch(checked = timer.enabled, enabled = !busy, onCheckedChange = { onToggle() }) } } @@ -219,10 +247,17 @@ private fun TimerDialog( supportsSmartPlan: Boolean, supportsFastRoute: Boolean, supportsWaterSlide: Boolean, - onSave: (hour: Int, minute: Int, weekdays: Set, settings: TimerSettings, once: Boolean) -> Unit, + onSave: (hour: Int, minute: Int, weekdays: Set, settings: TimerSettings, once: Boolean, settingsChanged: Boolean, timingChanged: Boolean, enabled: Boolean) -> Unit, + readNativeState: (suspend () -> String)? = null, onDismiss: () -> Unit, ) { val start = initial?.settings ?: TimerSettings() + var enabled by remember { mutableStateOf(initial?.enabled ?: true) } + var touchedSettings by remember { mutableStateOf(emptySet()) } + val settingsChanged = touchedSettings.isNotEmpty() + var moreDetails by remember { mutableStateOf(false) } + var nativeState by remember { mutableStateOf("Not checked") } + val detailScope = rememberCoroutineScope() var hour by remember { mutableIntStateOf(initial?.hour ?: 8) } var minute by remember { mutableIntStateOf(initial?.minute ?: 0) } // Once is the official app's default for a new schedule. @@ -254,6 +289,12 @@ private fun TimerDialog( modifier = Modifier.verticalScroll(rememberScrollState()), verticalArrangement = Arrangement.spacedBy(16.dp), ) { + if (initial?.serverJob != null) { + Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { + Text("Enabled") + Switch(checked = enabled, onCheckedChange = { enabled = it }) + } + } Text("Time", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) ClockStepper(hour, minute, onHourChange = { hour = it }, onMinuteChange = { minute = it }) ChipRow( @@ -293,7 +334,7 @@ private fun TimerDialog( add(TimerKind.VACUUM to "Vacuum") }, selected = kind, - onSelect = { kind = it }, + onSelect = { kind = it; touchedSettings = touchedSettings + setOf("fan", "water", "route") }, ) if (kind == TimerKind.VACUUM || kind == TimerKind.VAC_AND_MOP) { ChipRow( @@ -305,7 +346,7 @@ private fun TimerDialog( VacuumFanPower.MAX to "Max", ), selected = fanPower, - onSelect = { fanPower = it }, + onSelect = { fanPower = it; touchedSettings = touchedSettings + "fan" }, ) } if (kind == TimerKind.VAC_AND_MOP || kind == TimerKind.MOP) { @@ -317,7 +358,7 @@ private fun TimerDialog( WaterBoxMode.HIGH to "High", ), selected = waterBoxMode, - onSelect = { waterBoxMode = it }, + onSelect = { waterBoxMode = it; touchedSettings = touchedSettings + "water" }, ) ChipRow( label = "Mop route", @@ -332,15 +373,32 @@ private fun TimerDialog( if (mopMode == MopRoute.DEEP_PLUS) add(MopRoute.DEEP_PLUS to "Deep+") }, selected = mopMode, - onSelect = { mopMode = it }, + onSelect = { mopMode = it; touchedSettings = touchedSettings + "route" }, ) } ChipRow( label = "Passes", options = listOf(1 to "1", 2 to "2", 3 to "3"), selected = repeat, - onSelect = { repeat = it }, + onSelect = { repeat = it; touchedSettings = touchedSettings + "repeat" }, ) + if (initial?.serverJob != null) { + TextButton(onClick = { moreDetails = !moreDetails }) { Text("More details") } + if (moreDetails) { + Text("Enabled updates the server job and verifies its linked native timer when present.", style = MaterialTheme.typography.bodySmall) + Text("Job: ${initial.id}", style = MaterialTheme.typography.bodySmall) + Text("Timezone: ${initial.serverJob.timezone.ifBlank { "Server default" }}", style = MaterialTheme.typography.bodySmall) + Text("Native timer: $nativeState", style = MaterialTheme.typography.bodySmall) + TextButton(onClick = { + detailScope.launch { + nativeState = "Checking…" + try { nativeState = readNativeState?.invoke() ?: "Not checked" } + catch (e: CancellationException) { currentCoroutineContext().ensureActive(); nativeState = "Unknown — request timed out" } + catch (_: Exception) { nativeState = "Unknown — could not read timer" } + } + }) { Text("Check native timer") } + } + } } }, confirmButton = { @@ -348,20 +406,30 @@ private fun TimerDialog( // Custom with no day picked would never run. enabled = repeatChoice != RepeatChoice.CUSTOM || weekdays.isNotEmpty(), onClick = { - val settings = timerSettingsFor( + val selectedSettings = timerSettingsFor( kind = kind, fanPower = fanPower, waterBoxMode = if (supportsWaterSlide) WaterBoxMode.forSlide(waterBoxMode) else waterBoxMode, mopMode = mopMode, repeat = repeat, ) + val settings = if (initial == null) selectedSettings else start.copy( + fanPower = if ("fan" in touchedSettings) selectedSettings.fanPower else start.fanPower, + waterBoxMode = if ("water" in touchedSettings) selectedSettings.waterBoxMode else start.waterBoxMode, + mopMode = if ("route" in touchedSettings) selectedSettings.mopMode else start.mopMode, + repeat = if ("repeat" in touchedSettings) selectedSettings.repeat else start.repeat, + ) val days = when (repeatChoice) { RepeatChoice.ONCE, RepeatChoice.EVERY_DAY -> emptySet() RepeatChoice.WEEKDAYS -> WEEKDAYS RepeatChoice.WEEKENDS -> WEEKENDS RepeatChoice.CUSTOM -> weekdays } - onSave(hour, minute, days, settings, repeatChoice == RepeatChoice.ONCE) + val timingChanged = initial == null || hour != initial.hour || minute != initial.minute || + repeatChoice != repeatChoiceOf(initial) || + (repeatChoice == RepeatChoice.CUSTOM && days != initial.weekdays) + onSave(hour, minute, days, if (initial != null && !settingsChanged) start else settings, + repeatChoice == RepeatChoice.ONCE, settingsChanged, timingChanged, enabled) }, ) { Text("Save") } }, @@ -423,7 +491,7 @@ private enum class RepeatChoice(val label: String) { } private fun repeatChoiceOf(timer: CleanTimer): RepeatChoice = when { - timer.date != null -> RepeatChoice.ONCE + timer.date != null || timer.serverJob?.repeated == false -> RepeatChoice.ONCE timer.weekdays.isEmpty() || timer.weekdays.size == 7 -> RepeatChoice.EVERY_DAY timer.weekdays == WEEKDAYS -> RepeatChoice.WEEKDAYS timer.weekdays == WEEKENDS -> RepeatChoice.WEEKENDS @@ -443,3 +511,4 @@ private fun formatRepeat(timer: CleanTimer): String { else -> choice.label } } + diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt new file mode 100644 index 00000000..fcbbb85d --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt @@ -0,0 +1,33 @@ +package com.kodraliu.localrock.shared.device + +import io.ktor.client.HttpClient +import io.ktor.client.engine.mock.* +import io.ktor.http.* +import kotlinx.coroutines.test.runTest +import kotlin.test.* + +class ScheduleJobsApiTest { + @Test fun lists_result_and_data_envelopes_and_keeps_raw_settings() = runTest { + for (key in listOf("result", "data")) { + val client = HttpClient(MockEngine { respond("""{"code":200,"$key":[{"id":42,"cron":"10 9 ? * 0","enabled":false,"unknown":7}]}""", headers = headersOf(HttpHeaders.ContentType,"application/json")) }) + try { val jobs = ScheduleApi(client).list("robot"); assertEquals("42", jobs.single().id); assertTrue("unknown" in jobs.single().raw) } + finally { client.close() } + } + } + @Test fun rejects_application_errors_even_with_http_200() = runTest { + val client = HttpClient(MockEngine { respond("""{"code":500,"data":[]}""") }) + try { assertFailsWith { ScheduleApi(client).list("robot") } } finally { client.close() } + } + @Test fun duplicate_ids_and_invalid_shapes_are_errors_not_empty_lists() = runTest { + for (data in listOf("{}", "[{\"id\":1},{\"id\":1}]", "[{\"cron\":\"x\"}]")) { + val client = HttpClient(MockEngine { respond("""{"code":200,"data":$data}""") }) + try { assertFailsWith { ScheduleApi(client).list("robot") } } finally { client.close() } + } + } + @Test fun unavailable_collection_preserves_http_status_for_legacy_fallback() = runTest { + for (status in listOf(HttpStatusCode.NotFound, HttpStatusCode.MethodNotAllowed, HttpStatusCode.Unauthorized, HttpStatusCode.InternalServerError)) { + val client = HttpClient(MockEngine { respond("{}", status) }) + try { assertEquals(status.value, assertFailsWith { ScheduleApi(client).list("robot") }.responseCode) } finally { client.close() } + } + } +} diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt new file mode 100644 index 00000000..9c80b071 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt @@ -0,0 +1,285 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.coroutines.CompletableDeferred +import kotlinx.coroutines.async +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.cancelAndJoin +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.* +import kotlin.test.* + +class ScheduleEnablementTest { + private class Fixture(serverEnabled: Boolean = false, native: Boolean = true, robotEnabled: Boolean = false) { + var job: ServerSchedule? = ServerSchedule(buildJsonObject { + put("id", 918265); put("cron", "10 9 ? * 0"); put("enabled", serverEnabled) + put("timeZoneId", "America/Los_Angeles"); put("repeated", true) + put("param", buildJsonObject { + put("method", "server_scheduled_start") + put("params", JsonArray(listOf(buildJsonObject { + if (native) put("name", "1680623937705") + put("map_index", 1); put("segments", "20,17"); put("fan_power", 102) + put("future", buildJsonObject { put("keep", true) }) + }))) + }) + }) + var extraJobs = emptyList() + var robot = robotEnabled + var reads = 0 + var timerReads = 0 + var timerWrites = 0 + var jobWrites = 0 + val events = mutableListOf() + var beforeRead: (Int) -> Unit = {} + var timerResponse: (() -> JsonElement?)? = null + var failTimerReadAt: Int? = null + var failJobReadAt: Int? = null + var applyTimer = true + var failTimerWrite = false + var timeoutTimerWrite = false + var timeoutTimerReadAt: Int? = null + var applyJob = true + var failJobWrite = false + var gate: CompletableDeferred? = null + val sync = ScheduleEnablement( + readJobs = { + reads++; beforeRead(reads) + events += "readJob" + if (failJobReadAt == reads) error("connection failed") + listOfNotNull(job) + extraJobs + }, + writeJob = { _, patch -> + jobWrites++; events += "writeJob" + if (applyJob) job = ServerSchedule(JsonObject(job!!.raw + patch)) + if (failJobWrite) error("HTTP response lost") + }, + readTimers = { + timerReads++; events += "readTimer" + gate?.await() + if (failTimerReadAt == timerReads) error("MQTT unavailable") + if (timeoutTimerReadAt == timerReads) withTimeout(1) { delay(2) } + timerResponse?.invoke() ?: JsonArray(listOf(JsonArray(listOf( + JsonPrimitive("1680623937705"), JsonPrimitive(if (robot) "on" else "off"), JsonObject(emptyMap()) + )))) + }, + writeTimer = { name, enabled -> + assertEquals("1680623937705", name) + timerWrites++; events += "writeTimer" + if (applyTimer) robot = enabled + if (timeoutTimerWrite) withTimeout(1) { delay(2) } + if (failTimerWrite) error("MQTT reply lost") + }, + ) + suspend fun set(enabled: Boolean, expected: ServerSchedule = job!!): ServerSchedule = + sync.save(expected, buildJsonObject { put("enabled", enabled) }, true) + } + + @Test fun both_directions_verify_robot_before_http_and_preserve_payload() = runTest { + for (desired in listOf(true, false)) { + val f = Fixture(serverEnabled = !desired, robotEnabled = !desired) + val before = f.job!!.raw + val result = f.set(desired) + assertEquals(desired, f.robot) + assertEquals(desired, result.enabled) + assertEquals(before - "enabled", result.raw - "enabled") + assertEquals(1, f.timerWrites); assertEquals(1, f.jobWrites) + assertEquals(listOf("readJob", "readTimer", "readJob", "writeTimer", "readTimer", "readJob", "writeJob", "readJob"), f.events) + } + } + + @Test fun mismatched_states_only_write_the_side_that_needs_it() = runTest { + for (desired in listOf(true, false)) { + val robotMismatch = Fixture(serverEnabled = desired, robotEnabled = !desired) + robotMismatch.set(desired) + assertEquals(1, robotMismatch.timerWrites); assertEquals(0, robotMismatch.jobWrites) + val serverMismatch = Fixture(serverEnabled = !desired, robotEnabled = desired) + serverMismatch.set(desired) + assertEquals(0, serverMismatch.timerWrites); assertEquals(1, serverMismatch.jobWrites) + val matching = Fixture(serverEnabled = desired, robotEnabled = desired) + matching.set(desired) + assertEquals(0, matching.timerWrites); assertEquals(0, matching.jobWrites) + } + } + + @Test fun server_only_server_scheduled_start_jobs_never_use_mqtt() = runTest { + val f = Fixture(native = false) + f.set(true); f.set(false) + assertEquals(0, f.timerReads); assertEquals(0, f.timerWrites) + assertEquals(2, f.jobWrites) + assertNull(f.job!!.nativeName) + } + + @Test fun missing_ambiguous_and_unknown_timers_are_not_recreated() = runTest { + val row = JsonArray(listOf(JsonPrimitive("1680623937705"), JsonPrimitive("off"))) + for (reply in listOf(JsonArray(emptyList()), JsonArray(listOf(row, row)), JsonObject(emptyMap()), + JsonArray(listOf(JsonArray(listOf(JsonPrimitive("1680623937705"), JsonPrimitive("unexpected"))))))) { + val f = Fixture() + f.timerResponse = { reply } + assertFailsWith { f.set(true) } + assertEquals(0, f.timerWrites); assertEquals(0, f.jobWrites) + } + } + + @Test fun malformed_native_reference_is_not_mistaken_for_server_only() = runTest { + for (name in listOf(JsonNull, JsonPrimitive(""), JsonPrimitive(123))) { + val f = Fixture() + val param = JsonObject(f.job!!.param!! + ("params" to JsonArray(listOf(JsonObject(f.job!!.settings!! + ("name" to name)))))) + f.job = ServerSchedule(JsonObject(f.job!!.raw + ("param" to param))) + assertFailsWith { f.set(true) } + assertEquals(0, f.timerReads); assertEquals(0, f.jobWrites) + } + } + + @Test fun read_failures_before_writes_change_nothing() = runTest { + for (failJob in listOf(true, false)) { + val f = Fixture() + if (failJob) f.failJobReadAt = 1 else f.failTimerReadAt = 1 + assertFailsWith { f.set(true) } + assertEquals(0, f.timerWrites); assertEquals(0, f.jobWrites) + } + } + + @Test fun failed_robot_verification_never_saves_server_or_rolls_back() = runTest { + for (unreadable in listOf(true, false)) { + val f = Fixture() + if (unreadable) f.failTimerReadAt = 2 else { f.applyTimer = false; f.failTimerWrite = true } + assertFailsWith { f.set(true) } + assertEquals(1, f.timerWrites); assertEquals(0, f.jobWrites) + assertFalse(f.job!!.enabled) + } + } + + @Test fun lost_replies_are_resolved_by_readback_without_duplicate_writes() = runTest { + val f = Fixture() + f.failTimerWrite = true; f.failJobWrite = true + assertTrue(f.set(true).enabled) + assertEquals(1, f.timerWrites); assertEquals(1, f.jobWrites) + } + + @Test fun http_failure_reports_partial_save_and_explicit_retry_skips_robot_write() = runTest { + val f = Fixture() + f.applyJob = false; f.failJobWrite = true + val error = assertFailsWith { f.set(true) } + assertTrue(error.message!!.contains("Robot timer was verified on")) + assertTrue(error.message!!.contains("Server save failed")) + assertTrue(f.robot); assertFalse(f.job!!.enabled) + f.applyJob = true; f.failJobWrite = false + assertTrue(f.set(true).enabled) + assertEquals(1, f.timerWrites); assertEquals(2, f.jobWrites) + } + + @Test fun http_success_without_readback_is_not_reported_as_confirmed() = runTest { + val f = Fixture() + f.failJobReadAt = 4 + val error = assertFailsWith { f.set(true) } + assertTrue(error.message!!.contains("Server save is unconfirmed")) + assertEquals(1, f.timerWrites); assertEquals(1, f.jobWrites) + } + + @Test fun conflicts_at_each_stage_preserve_concurrent_changes() = runTest { + for (at in 1..4) { + val f = Fixture() + val old = f.job!! + f.beforeRead = { n -> if (n == at) f.job = ServerSchedule(JsonObject(f.job!!.raw + ("cron" to JsonPrimitive("20 10 ? * 1")))) } + assertFailsWith { f.set(true, old) } + assertEquals("20 10 ? * 1", f.job!!.cron) + assertEquals(if (at <= 2) 0 else 1, f.timerWrites) + assertEquals(if (at < 4) 0 else 1, f.jobWrites) + } + } + + @Test fun unrelated_time_edit_never_reads_or_changes_native_enablement() = runTest { + val f = Fixture(serverEnabled = true, robotEnabled = false) + val result = f.sync.save(f.job!!, buildJsonObject { put("cron", "0 8 ? * 1,2,3,4,5") }, false) + assertTrue(result.enabled); assertFalse(f.robot) + assertEquals(0, f.timerReads); assertEquals(0, f.timerWrites) + } + + @Test fun simultaneous_requests_do_not_queue_duplicate_writes() = runTest { + val f = Fixture() + val gate = CompletableDeferred() + f.gate = gate + val first = async { f.set(true) } + testScheduler.runCurrent() + assertFailsWith { f.set(true) } + gate.complete(Unit) + assertTrue(first.await().enabled) + assertEquals(1, f.timerWrites); assertEquals(1, f.jobWrites) + } + + + @Test fun shared_native_references_and_multiple_settings_entries_are_rejected() = runTest { + val shared = Fixture() + shared.extraJobs = listOf(ServerSchedule(JsonObject(shared.job!!.raw + ("id" to JsonPrimitive(2))))) + assertFailsWith { shared.set(true) } + assertEquals(0, shared.timerReads); assertEquals(0, shared.timerWrites); assertEquals(0, shared.jobWrites) + val multiple = Fixture() + val param = JsonObject(multiple.job!!.param!! + ("params" to JsonArray(listOf(multiple.job!!.settings!!, multiple.job!!.settings!!)))) + multiple.job = ServerSchedule(JsonObject(multiple.job!!.raw + ("param" to param))) + assertFailsWith { multiple.set(true) } + assertEquals(0, multiple.timerWrites); assertEquals(0, multiple.jobWrites) + } + + @Test fun server_only_failures_are_not_described_as_robot_changes() = runTest { + val f = Fixture(native = false, serverEnabled = true) + f.applyJob = false; f.failJobWrite = true + val error = assertFailsWith { f.set(false) } + assertTrue(error.message!!.contains("Robot enablement was not changed")) + assertEquals(0, f.timerReads); assertEquals(1, f.jobWrites) + } + + @Test fun disappearing_job_after_native_update_is_reported_as_partial() = runTest { + val f = Fixture() + f.beforeRead = { n -> if (n == 3) f.job = null } + val error = assertFailsWith { f.set(true) } + assertTrue(error.message!!.contains("Robot timer was verified on")) + assertTrue(f.robot); assertEquals(0, f.jobWrites) + } + + @Test fun mqtt_timeout_is_verified_but_real_cancellation_stops_work() = runTest { + val lostReply = Fixture() + lostReply.timeoutTimerWrite = true + assertTrue(lostReply.set(true).enabled) + assertEquals(1, lostReply.timerWrites); assertEquals(1, lostReply.jobWrites) + for (at in listOf(1, 2)) { + val failedRead = Fixture() + failedRead.timeoutTimerReadAt = at + assertFailsWith { failedRead.set(true) } + assertEquals(0, failedRead.jobWrites) + assertEquals(if (at == 1) 0 else 1, failedRead.timerWrites) + } + val cancelled = Fixture() + cancelled.gate = CompletableDeferred() + val pending = async { cancelled.set(true) } + testScheduler.runCurrent() + pending.cancelAndJoin() + assertEquals(0, cancelled.timerWrites); assertEquals(0, cancelled.jobWrites) + cancelled.gate = null + assertTrue(cancelled.set(true).enabled) // Cancellation released the mutex. + } + + @Test fun native_rpc_uses_timer_name_in_a_nested_array() { + assertEquals("[[\"1680623937705\",\"on\"]]", JsonArray(nativeTimerUpdateParams("1680623937705", true)).toString()) + assertEquals("[[\"1680623937705\",\"off\"]]", JsonArray(nativeTimerUpdateParams("1680623937705", false)).toString()) + } + @Test fun server_reconciliation_after_native_write_needs_no_redundant_http_write() = runTest { + for (desired in listOf(true, false)) { + val f = Fixture(serverEnabled = !desired, robotEnabled = !desired) + f.beforeRead = { if (f.timerWrites > 0) f.job = ServerSchedule(JsonObject(f.job!!.raw + ("enabled" to JsonPrimitive(desired)))) } + val saved = f.set(desired) + assertEquals(desired, saved.enabled); assertEquals(1, f.timerWrites); assertEquals(0, f.jobWrites) + } + } + @Test fun reconciliation_of_initial_mismatch_does_not_block_explicit_repair() = runTest { + val f = Fixture(serverEnabled = true, robotEnabled = false) + f.beforeRead = { if (f.timerReads > 0) f.job = ServerSchedule(JsonObject(f.job!!.raw + ("enabled" to JsonPrimitive(f.robot)))) } + assertTrue(f.set(true).enabled) + assertEquals(1, f.timerWrites); assertEquals(0, f.jobWrites) + } + @Test fun unrelated_edit_during_server_reconciliation_remains_a_conflict() = runTest { + val f = Fixture() + f.beforeRead = { if (f.timerWrites > 0) f.job = ServerSchedule(JsonObject(f.job!!.raw + mapOf("enabled" to JsonPrimitive(true), "cron" to JsonPrimitive("changed")))) } + assertFailsWith { f.set(true) }; assertEquals(0, f.jobWrites) + } +} + diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt new file mode 100644 index 00000000..74d564cd --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt @@ -0,0 +1,55 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.coroutines.delay +import kotlinx.coroutines.withTimeout +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.* +import kotlin.test.* + +class ServerJobCreationTest { + private class Fixture { + val body = Json.parseToJsonElement("""{"id":"","enabled":true,"cron":"10 9 ? * 0","param":{"method":"server_scheduled_start","params":[{"name":"native","segments":"20,17"}]}}""").jsonObject + var jobs = emptyList(); var writes = 0 + var timer: JsonElement = Json.parseToJsonElement("""[["native","on",1]]""") + var apply = true; var fail = false; var timeout = false; var failRead = false; var duplicate = false + val creation = ServerJobCreation( + readTimers = { timer }, + createJob = { + writes++ + if (apply) { + jobs = listOf(ServerSchedule(JsonObject(it + ("id" to JsonPrimitive("http-id"))))) + if (duplicate) jobs += ServerSchedule(JsonObject(it + ("id" to JsonPrimitive("other")))) + } + if (timeout) withTimeout(1) { delay(2) } + if (fail) error("HTTP reply lost") + "http-id" + }, + readJobs = { if (failRead) error("offline"); jobs }, + ) + } + @Test fun confirms_creation_without_changing_payload() = runTest { + val f = Fixture(); val saved = f.creation.confirm("native", f.body) + assertEquals("http-id",saved.id); assertEquals(f.body - "id", saved.raw - "id"); assertEquals(1,f.writes) + } + @Test fun lost_http_reply_or_inner_timeout_uses_read_back_not_another_post() = runTest { + for (timeout in listOf(true,false)) { + val f = Fixture(); f.fail = !timeout; f.timeout = timeout + assertEquals("http-id",f.creation.confirm("native",f.body).id); assertEquals(1,f.writes) + } + } + @Test fun failed_verification_does_not_post() = runTest { + val f = Fixture(); f.timer = Json.parseToJsonElement("""[["native","off",1]]""") + assertFailsWith { f.creation.confirm("native",f.body) }; assertEquals(0,f.writes) + } + @Test fun missing_or_duplicate_job_reports_partial_save() = runTest { + for (duplicate in listOf(true,false)) { + val f = Fixture(); f.duplicate = duplicate; f.apply = duplicate + val e = assertFailsWith { f.creation.confirm("native",f.body) } + assertTrue(e.message!!.contains("No timer was deleted")); assertEquals(1,f.writes) + } + } + @Test fun failed_read_back_is_unconfirmed_without_retry() = runTest { + val f = Fixture(); f.failRead = true + assertFailsWith { f.creation.confirm("native",f.body) }; assertEquals(1,f.writes) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt new file mode 100644 index 00000000..649f7f38 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt @@ -0,0 +1,53 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.coroutines.test.runTest +import kotlinx.serialization.json.* +import kotlin.test.* + +class ServerJobDeletionTest { + private class Fixture(native: Boolean = true) { + val original = ServerSchedule(Json.parseToJsonElement("""{"id":"job","enabled":false,"param":{"method":"server_scheduled_start","params":[${if (native) "{\"name\":\"native\"}" else "{}"}]}}""").jsonObject) + var jobs = listOf(original) + var timer: JsonElement = Json.parseToJsonElement("""[["native","off",1]]""") + var robotWrites = 0; var jobWrites = 0; var robotReads = 0 + var failRobot = false; var applyRobot = true; var failJob = false; var applyJob = true + var afterRobot: () -> Unit = {} + val delete = ServerJobDeletion( + readJobs = { jobs }, + readTimers = { robotReads++; timer }, + deleteTimer = { assertEquals("native", it); robotWrites++; if (applyRobot) timer = JsonArray(emptyList()); afterRobot(); if (failRobot) error("lost MQTT reply") }, + deleteJob = { assertEquals("job", it); jobWrites++; if (applyJob) jobs = emptyList(); if (failJob) error("lost HTTP reply") }, + ) + } + @Test fun native_delete_uses_native_id_and_verifies_both_sides() = runTest { + val f = Fixture(); f.delete.delete(f.original) + assertEquals(1,f.robotWrites); assertEquals(1,f.jobWrites); assertEquals(2,f.robotReads) + } + @Test fun server_only_deletion_never_touches_native_timers() = runTest { + val f = Fixture(false); f.delete.delete(f.original) + assertEquals(0,f.robotReads); assertEquals(0,f.robotWrites); assertEquals(1,f.jobWrites) + } + @Test fun lost_acknowledgements_are_read_back_without_duplicate_deletes() = runTest { + val f = Fixture(); f.failRobot = true; f.failJob = true; f.delete.delete(f.original) + assertEquals(1,f.robotWrites); assertEquals(1,f.jobWrites) + } + @Test fun failed_native_verification_preserves_job() = runTest { + val f = Fixture(); f.applyRobot = false + assertFailsWith { f.delete.delete(f.original) } + assertEquals(0,f.jobWrites) + } + @Test fun partial_server_failure_is_reported_without_native_recreation() = runTest { + val f = Fixture(); f.applyJob = false; f.failJob = true + val error = assertFailsWith { f.delete.delete(f.original) } + assertTrue(error.message!!.contains("Native timer deletion was confirmed")) + assertEquals(1,f.robotWrites); assertEquals(1,f.jobWrites) + } + @Test fun conflict_after_native_delete_does_not_delete_modified_job() = runTest { + val f = Fixture(); f.afterRobot = { f.jobs = listOf(ServerSchedule(JsonObject(f.original.raw + ("cron" to JsonPrimitive("changed"))))) } + assertFailsWith { f.delete.delete(f.original) }; assertEquals(0,f.jobWrites) + } + @Test fun shared_native_name_blocks_all_deletion() = runTest { + val f = Fixture(); f.jobs += ServerSchedule(JsonObject(f.original.raw + ("id" to JsonPrimitive("other")))) + assertFailsWith { f.delete.delete(f.original) }; assertEquals(0,f.robotWrites); assertEquals(0,f.jobWrites) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt new file mode 100644 index 00000000..59563806 --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt @@ -0,0 +1,62 @@ +package com.kodraliu.localrock.shared.schedule + +import kotlinx.serialization.json.* +import kotlin.test.* + +class ServerScheduleTest { + private fun imported(stringParam: Boolean = false): ServerSchedule { + val param = Json.parseToJsonElement("""{"id":1,"method":"server_scheduled_start","params":[{"name":"native-123","map_index":1,"segments":"20,17","repeat":1,"clean_order_mode":2,"mop_template_id":7,"future":{"x":true}}],"futureParam":"keep"}""") + return ServerSchedule(buildJsonObject { + put("id", 42); put("cron", "28 8 ? * 1,2,3,4,5"); put("timeZoneId", "America/Los_Angeles") + put("enabled", true); put("repeated", true); put("param", if (stringParam) JsonPrimitive(param.toString()) else param) + }) + } + @Test fun time_only_update_omits_param() { + val job = imported() + val patch = job.update(WeeklyTime(9, 7, setOf(0, 6)), job.timezone, false) + assertEquals("7 9 ? * 0,6", patch["cron"]!!.jsonPrimitive.content) + assertFalse("param" in patch) + assertFalse(patch["enabled"]!!.jsonPrimitive.boolean) + } + @Test fun settings_edit_keeps_native_identity_and_unknown_fields() { + for (stringParam in listOf(false, true)) { + val job = imported(stringParam) + val patch = job.update(job.weekly!!, job.timezone, true, mapOf("segments" to JsonPrimitive("18"))) + val param = patch["param"]!!.jsonObject + assertEquals(job.param!!["futureParam"], param["futureParam"]) + val entry = param["params"]!!.jsonArray.single().jsonObject + assertEquals(JsonPrimitive("18"), entry["segments"]) + assertEquals(job.settings!!.filterKeys { it != "segments" }, entry.filterKeys { it != "segments" }) + } + } + @Test fun complex_schedules_are_not_rewritten() { + for (cron in listOf("*/5 8 * * *", "0 8 24 10 *", "0 8,9 * * 1", "0 24 * * 1", "0 8 * * 8", "0 8 * * 1,")) { + assertNull(WeeklyTime.parse(cron), cron) + } + val once = ServerSchedule(JsonObject(imported().raw + ("repeated" to JsonPrimitive(false)))) + assertTrue(once.editable) + val patch = once.update(WeeklyTime(8, 0, setOf(1)), "UTC", true) + assertFalse(patch["repeated"]!!.jsonPrimitive.boolean) + assertFalse("param" in patch) + } + @Test fun weekday_ranges_and_sunday_alias_are_supported() { + assertEquals(setOf(1,2,3,4,5), WeeklyTime.parse("10 8 * * 1-5")!!.days) + assertEquals(setOf(0,6), WeeklyTime.parse("10 8 ? * 6,7")!!.days) + assertEquals((0..6).toSet(), WeeklyTime.parse("10 8 ? * *")!!.days) + assertFailsWith { WeeklyTime(8, 0, emptySet()).cron() } + } + @Test fun new_jobs_are_disabled_and_have_no_native_timer_identity() { + val body = ServerSchedule.create(WeeklyTime(8, 0, setOf(1)), "UTC", mapOf("segments" to JsonPrimitive("18,19"))) + assertFalse(body["enabled"]!!.jsonPrimitive.boolean) + assertNull(body["param"]!!.jsonObject["params"]!!.jsonArray[0].jsonObject["name"]) + assertFailsWith { ServerSchedule.create(WeeklyTime(8,0,setOf(1)), "UTC", mapOf("name" to JsonPrimitive("bad"))) } + } + @Test fun native_timer_states_are_not_inferred_from_job_enabled() { + assertEquals("On", nativeTimerState(Json.parseToJsonElement("""[["x","on",{}]]"""), "x")) + assertEquals("Off", nativeTimerState(Json.parseToJsonElement("""[["x","off",{}]]"""), "x")) + assertEquals("Missing", nativeTimerState(JsonArray(emptyList()), "x")) + assertEquals("Unknown", nativeTimerState(null, "x")) + assertEquals("Ambiguous", nativeTimerState(Json.parseToJsonElement("""[["x","on"],["x","off"]]"""), "x")) + } +} + diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt new file mode 100644 index 00000000..b9c9b7aa --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt @@ -0,0 +1,50 @@ +package com.kodraliu.localrock.shared.vacuum + +import com.kodraliu.localrock.shared.schedule.ServerSchedule +import kotlinx.serialization.json.* +import kotlin.test.* + +class ServerJobEditingTest { + private fun job(cron: String = "10 9 ? * 0,6", repeated: Boolean = true) = ServerSchedule(buildJsonObject { + put("id", "http-id"); put("enabled", false); put("cron", cron); put("repeated", repeated) + put("param", buildJsonObject { + put("id", 1); put("method", "server_scheduled_start"); put("futureParam", true) + put("params", JsonArray(listOf(buildJsonObject { + put("name", "native-name"); put("segments", "20,17"); put("map_index", 1) + put("fan_power", 102); put("water_box_mode", 202); put("mop_mode", 300) + put("clean_mop", 1); put("futureOption", "keep") + }))) + }) + }) + + @Test fun time_only_edit_preserves_all_settings_and_enablement() { + val timer = job().toCleanTimer() + val patch = serverJobEditPatch(timer, 10, 20, setOf(1,2), timer.settings, false, null, false, true) + assertEquals(setOf("cron", "repeated"), patch.keys) + assertEquals("20 10 ? * 1,2", patch["cron"]?.jsonPrimitive?.content) + assertFalse("enabled" in patch) + } + @Test fun settings_edit_preserves_native_reference_rooms_and_unknown_fields() { + val original = job(); val timer = original.toCleanTimer() + val patch = serverJobEditPatch(timer, 9, 10, setOf(0,6), timer.settings.copy(fanPower = 103), false, null, true, false) + val saved = ServerSchedule(JsonObject(original.raw + patch)) + assertEquals(original.settings!! - "fan_power", saved.settings!! - "fan_power") + assertEquals(original.param!!["futureParam"], saved.param!!["futureParam"]) + assertFalse("cron" in patch); assertFalse("enabled" in patch) + } + @Test fun date_specific_and_repeated_false_jobs_remain_once() { + val dated = job("15 8 31 10 ?", false).toCleanTimer() + assertEquals(TimerDate(10,31), dated.date); assertTrue(dated.editable) + val once = job(repeated = false).toCleanTimer() + assertFalse(once.serverJob!!.repeated) + assertTrue(serverJobEditPatch(once, once.hour, once.minute, once.weekdays, once.settings, true, TimerDate(10,27), false, false).isEmpty()) + } + @Test fun unsupported_cron_is_visible_but_not_rewritten() { + val timer = job("*/15 * * * *").toCleanTimer() + assertFalse(timer.editable); assertEquals("http-id", timer.id) + assertFailsWith { serverJobEditPatch(timer, 9,10, emptySet(), timer.settings, false,null,false,true) } + } + @Test fun weekly_ranges_are_not_silently_lost() { + assertEquals(setOf(1,2,3,4,5), job("10 9 ? * 1-5").toCleanTimer().weekdays) + } +} diff --git a/docs/schedules.md b/docs/schedules.md new file mode 100644 index 00000000..06b56961 --- /dev/null +++ b/docs/schedules.md @@ -0,0 +1,21 @@ +# Schedules + +The schedule screen lists jobs from the server's `/user/devices/{duid}/jobs` API. A server with the schedule API and executor is required for server-triggered cleaning. The server must remain running and the robot must be reachable when a job is due. Saving a native timer entry alone is not proof that a scheduled clean will execute. + +If the jobs collection is unavailable with HTTP 404 or 405, the app uses the legacy timer interface. An empty supported list, authentication error, timeout or server error does not trigger that fallback. + +## Editing and enablement + +Tap a schedule to edit its time, repetition or cleaning settings. Model-specific SmartPlan, water and mop-route options are retained. Jobs in an unsupported format remain visible with a read-only editor rather than being silently converted. + +Server jobs retain their IDs, native references, room order and unedited settings. Time and cleaning-setting edits do not recreate native timers. Changing Enabled verifies a linked native timer, changes it only when necessary, then saves and reads back the server job. Jobs without a native reference use only the server API. The HTTP job ID and native timer name are different identifiers. + +The editor's More details section provides a read-only native-timer check. Not checked, unknown, missing and off are distinct states. The list does not display native-timer warnings. + +## Unconfirmed or partial saves + +A timeout may occur after a write succeeded. The app reads back state without repeating the write. A failed verification, concurrent edit or partial save is reported explicitly. It does not automatically recreate a timer or undo an uncertain write. Refresh and inspect both sides before retrying an unconfirmed operation. + +Deletion of a native-linked job verifies native deletion before deleting the server record. Server-only jobs never send native delete commands. Ambiguous or shared native references block deletion. + +Client read-back checks reduce stale writes but are not an atomic transaction across HTTP and MQTT. Other clients can still change a job between requests. From 7e2b37c3f500da43dc757351eaf87be816658b22 Mon Sep 17 00:00:00 2001 From: pponce Date: Mon, 26 Oct 2026 13:56:04 -0700 Subject: [PATCH 2/4] Clarify partial saves when the server reconciles enablement --- .../localrock/shared/schedule/ScheduleEnablement.kt | 8 ++++---- .../localrock/shared/schedule/ServerJobDeletion.kt | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt index 95935a1d..e71f1f24 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt @@ -39,7 +39,7 @@ class ScheduleEnablement( val desired = if (enabled) "On" else "Off" val initial = nativeTimerState(request { readTimers() }, name) if (initial !in listOf("On", "Off")) { - throw ScheduleException("Native timer is ${initial.lowercase()}. Nothing was changed; refresh and check More details. Timers are not recreated automatically.") + throw ScheduleException("Native timer is ${initial.lowercase()}. No client write was sent; refresh and check More details. Timers are not recreated automatically.") } if (initial != desired) { // A concurrent server edit must stop us before changing the robot. @@ -55,10 +55,10 @@ class ScheduleEnablement( val verified = try { nativeTimerState(request { readTimers() }, name) } catch (e: CancellationException) { throw e } catch (_: Exception) { - throw ScheduleException("$robotProgress Server job was not saved. Refresh before retrying; no rollback was attempted.") + throw ScheduleException("$robotProgress No HTTP job update was sent; server-side reconciliation may still have changed enablement. Refresh before retrying; no rollback was attempted.") } if (verified != desired) { - throw ScheduleException("Robot did not confirm the requested state. Server job was not saved. Refresh before retrying; no rollback was attempted.") + throw ScheduleException("Robot did not confirm the requested state. No HTTP job update was sent; server-side reconciliation may still have changed enablement. Refresh before retrying; no rollback was attempted.") } } verifiedEnabled = enabled @@ -99,7 +99,7 @@ class ScheduleEnablement( } throw e } catch (_: Exception) { - throw ScheduleException("$robotProgress Could not read the current schedule or timer state. Server job was not saved. Refresh before retrying.") + throw ScheduleException("$robotProgress Could not read the current schedule or timer state. No HTTP job update was sent; server-side reconciliation may still have changed enablement. Refresh before retrying.") } finally { mutex.unlock() } diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt index 81b6be46..ec006ade 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt @@ -13,7 +13,7 @@ class ServerJobDeletion( private val deleteJob: suspend (String) -> Unit, ) { suspend fun delete(expected: ServerSchedule) { - var progress = "Nothing was deleted." + var progress = "No native deletion was sent." try { val jobs = request { readJobs() } val current = jobs.filter { it.id == expected.id }.singleOrNull() From b14ced61593035b09c5ac520b7d0e040caf6b293 Mon Sep 17 00:00:00 2001 From: pponce Date: Mon, 26 Oct 2026 14:06:57 -0700 Subject: [PATCH 3/4] Use compact schedule cards and map editor with model-specific controls --- .../localrock/shared/vacuum/CleanTimer.kt | 5 +- .../shared/vacuum/ServerJobEditing.kt | 4 +- .../shared/vacuum/VacuumRepository.kt | 2 +- .../localrock/ui/vacuum/ScheduleScreen.kt | 464 +++++++++++------- .../localrock/ui/vacuum/VacuumDetailScreen.kt | 3 +- .../shared/vacuum/ServerJobEditingTest.kt | 15 + docs/schedules.md | 2 +- 7 files changed, 318 insertions(+), 177 deletions(-) diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt index cc5e514e..70d4d3c6 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt @@ -48,10 +48,11 @@ data class TimerSettings( ) /** The cleaning choice a schedule offers, as the official app words it. */ -enum class TimerKind { CURRENT, SMART_PLAN, VACUUM, VAC_AND_MOP, MOP } +enum class TimerKind { CURRENT, SMART_PLAN, CUSTOM, VACUUM, VAC_AND_MOP, MOP } val TimerSettings.kind: TimerKind get() = when { + isCustomizeModeSet(fanPower, waterBoxMode, mopMode) -> TimerKind.CUSTOM isSmartModeSet(fanPower, waterBoxMode, mopMode) -> TimerKind.SMART_PLAN waterBoxMode == WaterBoxMode.OFF -> TimerKind.VACUUM fanPower == VacuumFanPower.OFF -> TimerKind.MOP @@ -71,6 +72,7 @@ fun timerSettingsFor( mopMode: Int?, repeat: Int?, ): TimerSettings = when (kind) { + TimerKind.CUSTOM -> TimerSettings(VacuumFanPower.CUSTOM, WaterBoxMode.CUSTOM, MopRoute.CUSTOM, repeat) TimerKind.CURRENT -> TimerSettings(repeat = repeat) TimerKind.SMART_PLAN -> TimerSettings(VacuumFanPower.SMART, WaterBoxMode.SMART, MopRoute.SMART, repeat) TimerKind.VACUUM -> TimerSettings(fanPower, WaterBoxMode.OFF, null, repeat) @@ -143,6 +145,7 @@ fun TimerSettings.summary(): String? { return parts.joinToString(" · ") } when (kind) { + TimerKind.CUSTOM -> parts += "Custom" TimerKind.SMART_PLAN -> Unit TimerKind.VACUUM -> parts += "Vacuum" TimerKind.VAC_AND_MOP -> parts += "Vacuum and mop" diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt index 94f1b71d..ef095b17 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt @@ -45,8 +45,8 @@ internal fun serverJobEditPatch( val before = timer.settings.toActionObject() val after = settings.toActionObject() val edited = job.settings!!.toMutableMap() - // Only the dialog's cleaning controls can change these fields. Rooms/map/name stay intact. - for (key in listOf("fan_power", "water_box_mode", "mop_mode", "repeat")) { + // Only the dialog's cleaning controls can change these fields. Only explicit room changes replace segments; map/name stay intact. + for (key in listOf("fan_power", "water_box_mode", "mop_mode", "repeat", "segments")) { if (before[key] != after[key]) { val value = after[key] if (value == null) edited.remove(key) else edited[key] = value diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt index 4cc656be..cb8cf65d 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt @@ -1071,7 +1071,7 @@ class VacuumRepository( val id = robotId(timer, useServerTimer) // The new settings come from the edit dialog's own choices, which know nothing of the // mirror link; carry it forward so a second edit can still find the real robot-side id. - val newSettings = settings.copy(serverTimerId = timer.settings.serverTimerId, segments = timer.settings.segments, mapIndex = timer.settings.mapIndex, cleanMop = timer.settings.cleanMop) + val newSettings = settings.copy(serverTimerId = timer.settings.serverTimerId, segments = settings.segments ?: timer.settings.segments, mapIndex = timer.settings.mapIndex, cleanMop = timer.settings.cleanMop) if (useServerTimer) session.delServerTimer(id).requireOk("del_server_timer") else session.delTimer(id).requireOk("del_timer") try { diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt index ecd86624..b1e4f938 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt @@ -1,6 +1,15 @@ package com.kodraliu.localrock.ui.vacuum import androidx.compose.foundation.clickable +import androidx.compose.foundation.layout.* +import androidx.compose.foundation.shape.RoundedCornerShape +import androidx.compose.material3.* +import androidx.compose.material.icons.filled.* +import androidx.compose.ui.text.style.TextOverflow +import androidx.compose.ui.window.Dialog +import androidx.compose.ui.window.DialogProperties +import com.kodraliu.localrock.shared.vacuum.map.ParsedMap +import com.kodraliu.localrock.shared.vacuum.map.ParsedMapRoom import androidx.compose.foundation.rememberScrollState import androidx.compose.foundation.verticalScroll import androidx.compose.foundation.layout.Arrangement @@ -80,6 +89,16 @@ fun ScheduleScreen( val repository = viewModel.repository val scope = rememberCoroutineScope() val timers by repository.timers.collectAsState() + val rooms by repository.rooms.collectAsState() + val maps by repository.floorMaps.collectAsState() + val map by repository.parsedMap.collectAsState() + val currentFlag by repository.currentFloorFlag.collectAsState() + val mapName = maps.firstOrNull { it.mapFlag == currentFlag }?.name ?: "Current map" + LaunchedEffect(Unit) { + try { repository.fetchFloorMaps() } + catch (e: CancellationException) { currentCoroutineContext().ensureActive() } + catch (_: Exception) { /* Room editing remains unavailable until a map is loaded. */ } + } var showAddDialog by remember { mutableStateOf(false) } var editing by remember { mutableStateOf(null) } var loading by remember { mutableStateOf(true) } @@ -117,10 +136,13 @@ fun ScheduleScreen( snackbarHost = { SnackbarHost(snackbarHostState) }, topBar = { TopAppBar( - title = { Text("Schedule") }, + title = { Text("Schedules") }, navigationIcon = { IconButton(onClick = onBack) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Back") } }, + actions = { + IconButton(enabled = !saving && !loading, onClick = { refresh++ }) { Icon(Icons.Default.Refresh, "Refresh schedules") } + }, ) }, floatingActionButton = { @@ -148,16 +170,17 @@ fun ScheduleScreen( } } } else { - LazyColumn(contentPadding = padding) { + LazyColumn(modifier = Modifier.padding(padding), contentPadding = PaddingValues(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { items(timers.sortedWith(compareBy { it.hour }.thenBy { it.minute }.thenBy { it.id }), key = { it.id }) { timer -> TimerRow( timer = timer, busy = saving, + rooms = rooms, + currentFlag = currentFlag, onEdit = { if (timer.editable) editing = timer }, onToggle = { saveTimer { repository.toggleTimer(timer) } }, onDelete = { saveTimer { repository.deleteTimer(timer) } }, ) - HorizontalDivider(Modifier.padding(start = 72.dp)) } } } @@ -169,6 +192,7 @@ fun ScheduleScreen( supportsSmartPlan = viewModel.supportsSmartPlan, supportsFastRoute = viewModel.supportsFastRoute, supportsWaterSlide = viewModel.supportsWaterSlide, + rooms = rooms, map = map, mapName = mapName, currentFlag = currentFlag, onSave = { hour, minute, weekdays, settings, once, _, _, _ -> showAddDialog = false saveTimer { repository.createTimer(hour, minute, weekdays, settings, once) } @@ -183,72 +207,71 @@ fun ScheduleScreen( supportsSmartPlan = viewModel.supportsSmartPlan, supportsFastRoute = viewModel.supportsFastRoute, supportsWaterSlide = viewModel.supportsWaterSlide, + rooms = rooms, map = map, mapName = mapName, currentFlag = currentFlag, onSave = { hour, minute, weekdays, settings, once, settingsChanged, timingChanged, enabled -> editing = null saveTimer { repository.updateTimer(timer, hour, minute, weekdays, settings, once, settingsChanged, timingChanged, enabled) } }, readNativeState = { repository.nativeScheduleState(timer) }, + onDelete = { editing = null; saveTimer { repository.deleteTimer(timer) } }, onDismiss = { editing = null }, ) } } @Composable -private fun TimerRow(timer: CleanTimer, busy: Boolean, onEdit: () -> Unit, onToggle: () -> Unit, onDelete: () -> Unit) { - Row( - modifier = Modifier.fillMaxWidth().clickable(enabled = !busy && timer.editable, onClick = onEdit).padding(horizontal = 16.dp, vertical = 12.dp), - verticalAlignment = Alignment.CenterVertically, - horizontalArrangement = Arrangement.spacedBy(16.dp), - ) { - Surface( - shape = MaterialTheme.shapes.medium, - color = MaterialTheme.colorScheme.primaryContainer.copy(alpha = if (timer.enabled) 1f else 0.4f), - modifier = Modifier.size(44.dp), - ) { - Box(contentAlignment = Alignment.Center) { - Icon(Icons.Default.Schedule, null, Modifier.size(22.dp), MaterialTheme.colorScheme.onPrimaryContainer) +private fun TimerRow(timer: CleanTimer, busy: Boolean, rooms: List, currentFlag: Int, + onEdit: () -> Unit, onToggle: () -> Unit, onDelete: () -> Unit) { + Card(onClick = onEdit, enabled = !busy && timer.editable, + modifier = Modifier.fillMaxWidth(), shape = RoundedCornerShape(20.dp)) { + Column(Modifier.padding(16.dp)) { + Row(verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(if (timer.editable) formatClock(timer.hour, timer.minute, rememberUse24HourClock()) else timer.serverJob?.cron.orEmpty(), + style = MaterialTheme.typography.headlineSmall, fontWeight = FontWeight.SemiBold) + Text(formatRepeat(timer), Modifier.weight(1f), style = MaterialTheme.typography.labelSmall, + maxLines = 2, overflow = TextOverflow.Ellipsis) + Switch(checked = timer.enabled, enabled = !busy, onCheckedChange = { onToggle() }) } - } - Column(Modifier.weight(1f), verticalArrangement = Arrangement.spacedBy(4.dp)) { - Text( - if (timer.editable) formatClock(timer.hour, timer.minute, rememberUse24HourClock()) else timer.serverJob?.cron.orEmpty(), - style = MaterialTheme.typography.titleMedium, - fontWeight = FontWeight.SemiBold, - color = if (timer.enabled) MaterialTheme.colorScheme.onSurface else MaterialTheme.colorScheme.onSurfaceVariant, - ) - Text( - formatRepeat(timer), - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) - if (!timer.editable) Text("Unsupported format · read-only editor", style = MaterialTheme.typography.bodySmall) - timer.settings.segments?.let { rooms -> - Text(if (rooms == "0" || rooms.isBlank()) "Full" else "Rooms: $rooms", style = MaterialTheme.typography.bodySmall) + HorizontalDivider(Modifier.padding(vertical = 8.dp)) + Row(horizontalArrangement = Arrangement.spacedBy(12.dp)) { + val segments = timer.settings.segments.orEmpty() + val currentMap = timer.settings.mapIndex == null || timer.settings.mapIndex == -1 || timer.settings.mapIndex == currentFlag + val roomNames = segments.split(',', ';').mapNotNull { it.trim().toIntOrNull() }.map { id -> + if (currentMap) rooms.firstOrNull { it.id == id }?.name ?: "Room $id" else "Room $id" + } + Text(if (segments.isBlank() || segments == "0") "Full" else roomNames.joinToString(", ").ifBlank { "Saved rooms" }, + Modifier.weight(1f), style = MaterialTheme.typography.bodySmall) + Text(timer.settings.kind.label(), style = MaterialTheme.typography.bodySmall) } - timer.settings.summary()?.let { summary -> - Text( - summary, - style = MaterialTheme.typography.bodySmall, - color = MaterialTheme.colorScheme.onSurfaceVariant, - ) + if (!timer.editable) { + Text("Unsupported format · read-only editor", style = MaterialTheme.typography.bodySmall) + TextButton(enabled = !busy, onClick = onDelete) { Text("Delete schedule") } } } - IconButton(onClick = onDelete, enabled = !busy) { - Icon(Icons.Default.Delete, "Delete", tint = MaterialTheme.colorScheme.onSurfaceVariant) - } - Switch(checked = timer.enabled, enabled = !busy, onCheckedChange = { onToggle() }) } } +private fun TimerKind.label(): String = when (this) { + TimerKind.CURRENT -> "Saved settings" + TimerKind.SMART_PLAN -> "SmartPlan" + TimerKind.CUSTOM -> "Custom" + TimerKind.VACUUM -> "Vacuum" + TimerKind.VAC_AND_MOP -> "Vac & Mop" + TimerKind.MOP -> "Mop" +} + /** Adds a schedule, or edits [initial]. */ +@OptIn(ExperimentalMaterial3Api::class, ExperimentalLayoutApi::class) @Composable private fun TimerDialog( initial: CleanTimer?, supportsSmartPlan: Boolean, supportsFastRoute: Boolean, supportsWaterSlide: Boolean, + rooms: List, map: ParsedMap?, mapName: String, currentFlag: Int, onSave: (hour: Int, minute: Int, weekdays: Set, settings: TimerSettings, once: Boolean, settingsChanged: Boolean, timingChanged: Boolean, enabled: Boolean) -> Unit, readNativeState: (suspend () -> String)? = null, + onDelete: (() -> Unit)? = null, onDismiss: () -> Unit, ) { val start = initial?.settings ?: TimerSettings() @@ -281,112 +304,93 @@ private fun TimerDialog( var mopMode by remember { mutableStateOf(start.mopMode?.takeIf { it != MopRoute.SMART } ?: MopRoute.STANDARD) } var repeat by remember { mutableIntStateOf(start.repeat ?: 1) } - AlertDialog( - onDismissRequest = onDismiss, - title = { Text(if (initial == null) "New schedule" else "Edit schedule") }, - text = { - Column( - modifier = Modifier.verticalScroll(rememberScrollState()), - verticalArrangement = Arrangement.spacedBy(16.dp), - ) { - if (initial?.serverJob != null) { - Row(Modifier.fillMaxWidth(), horizontalArrangement = Arrangement.SpaceBetween, verticalAlignment = Alignment.CenterVertically) { - Text("Enabled") - Switch(checked = enabled, onCheckedChange = { enabled = it }) - } + var sheet by remember { mutableStateOf(null) } + var wholeHome by remember { mutableStateOf(start.segments.isNullOrBlank() || start.segments == "0") } + var selected by remember { mutableStateOf(start.segments.orEmpty().split(',', ';').mapNotNull { it.trim().toIntOrNull()?.takeIf { id -> id > 0 } }) } + var roomsChanged by remember { mutableStateOf(false) } + var confirmedMap by remember { mutableStateOf(null) } + var localError by remember { mutableStateOf(null) } + + fun save() { + val selectedSettings = timerSettingsFor( + kind = kind, + fanPower = fanPower, + waterBoxMode = if (supportsWaterSlide) WaterBoxMode.forSlide(waterBoxMode) else waterBoxMode, + mopMode = mopMode, + repeat = repeat, + ) + val cleaning = if (initial == null) selectedSettings else start.copy( + fanPower = if ("fan" in touchedSettings) selectedSettings.fanPower else start.fanPower, + waterBoxMode = if ("water" in touchedSettings) selectedSettings.waterBoxMode else start.waterBoxMode, + mopMode = if ("route" in touchedSettings) selectedSettings.mopMode else start.mopMode, + repeat = if ("repeat" in touchedSettings) selectedSettings.repeat else start.repeat, + ) + if (roomsChanged && !wholeHome && (confirmedMap != currentFlag || selected.isEmpty() || selected.any { id -> rooms.none { it.id == id } })) { + localError = "Choose rooms from the intended loaded map before saving." + return + } + val settings = if (roomsChanged) cleaning.copy(segments = if (wholeHome) "0" else selected.joinToString(",")) else cleaning + val days = when (repeatChoice) { + RepeatChoice.ONCE, RepeatChoice.EVERY_DAY -> emptySet() + RepeatChoice.WEEKDAYS -> WEEKDAYS + RepeatChoice.WEEKENDS -> WEEKENDS + RepeatChoice.CUSTOM -> weekdays + } + val timingChanged = initial == null || hour != initial.hour || minute != initial.minute || + repeatChoice != repeatChoiceOf(initial) || + (repeatChoice == RepeatChoice.CUSTOM && days != initial.weekdays) + onSave(hour, minute, days, if (initial != null && !settingsChanged && !roomsChanged) start else settings, + repeatChoice == RepeatChoice.ONCE, settingsChanged || roomsChanged, timingChanged, enabled) + + } + + Dialog(onDismissRequest = onDismiss, properties = DialogProperties(usePlatformDefaultWidth = false)) { + Scaffold(topBar = { + TopAppBar(title = { Text(if (initial == null) "New schedule" else "Scheduling") }, navigationIcon = { + IconButton(onClick = onDismiss) { Icon(Icons.AutoMirrored.Filled.ArrowBack, "Cancel editing") } + }, actions = { + if (onDelete != null) IconButton(onClick = onDelete) { Icon(Icons.Default.Delete, "Delete schedule") } + IconButton(enabled = repeatChoice != RepeatChoice.CUSTOM || weekdays.isNotEmpty(), onClick = { save() }) { Icon(Icons.Default.Check, "Save schedule") } + }) + }) { padding -> + Column(Modifier.padding(padding).fillMaxSize().verticalScroll(rememberScrollState()).padding(16.dp), verticalArrangement = Arrangement.spacedBy(18.dp)) { + localError?.let { Text(it, color = MaterialTheme.colorScheme.error) } + Card(shape = RoundedCornerShape(20.dp)) { + ScheduleRow("Start", formatClock(hour, minute, rememberUse24HourClock())) { sheet = "time" } + HorizontalDivider() + ScheduleRow("Repeat", if (repeatChoice == RepeatChoice.ONCE && initial?.date != null && hour == initial.hour && minute == initial.minute) formatRepeat(initial) else repeatChoice.label) { sheet = "repeat" } } - Text("Time", style = MaterialTheme.typography.labelLarge, color = MaterialTheme.colorScheme.onSurfaceVariant) - ClockStepper(hour, minute, onHourChange = { hour = it }, onMinuteChange = { minute = it }) - ChipRow( - label = "Repeat", - options = RepeatChoice.entries.map { it to it.label }, - selected = repeatChoice, - onSelect = { repeatChoice = it }, - ) - if (repeatChoice == RepeatChoice.CUSTOM) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { - val dayLabels = listOf("Su", "Mo", "Tu", "We", "Th", "Fr", "Sa") - dayLabels.forEachIndexed { index, label -> - val selected = index in weekdays - Surface( - onClick = { weekdays = if (selected) weekdays - index else weekdays + index }, - modifier = Modifier.weight(1f).aspectRatio(1f), - shape = CircleShape, - color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant, - ) { - Box(contentAlignment = Alignment.Center) { - Text( - label, - style = MaterialTheme.typography.labelSmall, - color = if (selected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant, - textAlign = TextAlign.Center, - ) + Text("Task", style = MaterialTheme.typography.labelLarge) + Card(shape = RoundedCornerShape(20.dp)) { + Column(Modifier.padding(16.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + SingleChoiceSegmentedButtonRow(Modifier.fillMaxWidth()) { + listOf("Full", "Rooms").forEachIndexed { index, label -> + SegmentedButton(selected = wholeHome == (index == 0), shape = SegmentedButtonDefaults.itemShape(index, 2), onClick = { + if (index == 0) { wholeHome = true; roomsChanged = true } else sheet = "rooms" + }) { Text(label) } } } + ScheduleRow("Cleaning Mode", if (initial != null && !settingsChanged) start.kind.label() else kind.label()) { sheet = "mode" } + ScheduleRow("Map", mapName) { sheet = "rooms" } + if (map != null) VacuumMapImage(map, if (wholeHome) emptyList() else selected, + onRoomTap = { sheet = "rooms" }, modifier = Modifier.fillMaxWidth().height(220.dp)) + Text(if (wholeHome) "Entire map" else selected.joinToString(", ") { id -> rooms.firstOrNull { it.id == id }?.name ?: "Room $id" }, + modifier = Modifier.align(Alignment.CenterHorizontally), style = MaterialTheme.typography.bodyMedium) + Text("Preview: currently loaded map", style = MaterialTheme.typography.labelSmall) } } - - ChipRow( - label = "Cleaning", - options = buildList { - if (supportsSmartPlan || kind == TimerKind.SMART_PLAN) add(TimerKind.SMART_PLAN to "SmartPlan") - add(TimerKind.VAC_AND_MOP to "Vacuum and mop") - add(TimerKind.MOP to "Mop") - add(TimerKind.VACUUM to "Vacuum") - }, - selected = kind, - onSelect = { kind = it; touchedSettings = touchedSettings + setOf("fan", "water", "route") }, - ) - if (kind == TimerKind.VACUUM || kind == TimerKind.VAC_AND_MOP) { - ChipRow( - label = "Suction", - options = listOf( - VacuumFanPower.QUIET to "Quiet", - VacuumFanPower.BALANCED to "Balanced", - VacuumFanPower.TURBO to "Turbo", - VacuumFanPower.MAX to "Max", - ), - selected = fanPower, - onSelect = { fanPower = it; touchedSettings = touchedSettings + "fan" }, - ) - } - if (kind == TimerKind.VAC_AND_MOP || kind == TimerKind.MOP) { - ChipRow( - label = "Water", - options = listOf( - WaterBoxMode.LOW to "Low", - WaterBoxMode.MEDIUM to "Medium", - WaterBoxMode.HIGH to "High", - ), - selected = waterBoxMode, - onSelect = { waterBoxMode = it; touchedSettings = touchedSettings + "water" }, - ) - ChipRow( - label = "Mop route", - // A schedule can only use these two routes: a Qrevo Pro that accepts Deep and - // Deep+ as its route setting refuses them inside a start command with -10005 - // "Param error", and the official app's schedule screen offers only these. A - // route an existing schedule already carries stays visible so it is not dropped. - options = buildList { - add(MopRoute.STANDARD to "Standard") - if (supportsFastRoute || mopMode == MopRoute.FAST) add(MopRoute.FAST to "Fast") - if (mopMode == MopRoute.DEEP) add(MopRoute.DEEP to "Deep") - if (mopMode == MopRoute.DEEP_PLUS) add(MopRoute.DEEP_PLUS to "Deep+") - }, - selected = mopMode, - onSelect = { mopMode = it; touchedSettings = touchedSettings + "route" }, - ) + if (initial?.serverJob != null) Card(shape = RoundedCornerShape(20.dp)) { + Row(Modifier.padding(horizontal = 16.dp, vertical = 8.dp), verticalAlignment = Alignment.CenterVertically) { + Text("Enabled", Modifier.weight(1f)); Switch(enabled, { enabled = it }) + } } - ChipRow( - label = "Passes", - options = listOf(1 to "1", 2 to "2", 3 to "3"), - selected = repeat, - onSelect = { repeat = it; touchedSettings = touchedSettings + "repeat" }, - ) if (initial?.serverJob != null) { TextButton(onClick = { moreDetails = !moreDetails }) { Text("More details") } if (moreDetails) { Text("Enabled updates the server job and verifies its linked native timer when present.", style = MaterialTheme.typography.bodySmall) Text("Job: ${initial.id}", style = MaterialTheme.typography.bodySmall) + initial.settings.mapIndex?.let { Text("Saved map reference: $it", style = MaterialTheme.typography.bodySmall) } + Text("Changing rooms preserves the saved map reference. Confirm the intended map is loaded before replacing rooms.", style = MaterialTheme.typography.bodySmall) Text("Timezone: ${initial.serverJob.timezone.ifBlank { "Server default" }}", style = MaterialTheme.typography.bodySmall) Text("Native timer: $nativeState", style = MaterialTheme.typography.bodySmall) TextButton(onClick = { @@ -399,44 +403,162 @@ private fun TimerDialog( }) { Text("Check native timer") } } } + } - }, - confirmButton = { - TextButton( - // Custom with no day picked would never run. - enabled = repeatChoice != RepeatChoice.CUSTOM || weekdays.isNotEmpty(), - onClick = { - val selectedSettings = timerSettingsFor( - kind = kind, - fanPower = fanPower, - waterBoxMode = if (supportsWaterSlide) WaterBoxMode.forSlide(waterBoxMode) else waterBoxMode, - mopMode = mopMode, - repeat = repeat, + } + when (sheet) { + "time" -> { + val time = rememberTimePickerState(hour, minute, is24Hour = rememberUse24HourClock()) + AlertDialog(onDismissRequest = { sheet = null }, title = { Text("Start time") }, text = { TimeInput(time) }, + confirmButton = { TextButton(onClick = { hour = time.hour; minute = time.minute; sheet = null }) { Text("Done") } }, + dismissButton = { TextButton(onClick = { sheet = null }) { Text("Cancel") } }) + } + "repeat" -> ModalBottomSheet(onDismissRequest = { sheet = null }) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + ChipRow( + label = "Repeat", + options = RepeatChoice.entries.map { it to it.label }, + selected = repeatChoice, + onSelect = { repeatChoice = it }, ) - val settings = if (initial == null) selectedSettings else start.copy( - fanPower = if ("fan" in touchedSettings) selectedSettings.fanPower else start.fanPower, - waterBoxMode = if ("water" in touchedSettings) selectedSettings.waterBoxMode else start.waterBoxMode, - mopMode = if ("route" in touchedSettings) selectedSettings.mopMode else start.mopMode, - repeat = if ("repeat" in touchedSettings) selectedSettings.repeat else start.repeat, + if (repeatChoice == RepeatChoice.CUSTOM) Row(horizontalArrangement = Arrangement.spacedBy(4.dp)) { + val dayLabels = listOf("Su", "Mo", "Tu", "We", "Th", "Fr", "Sa") + dayLabels.forEachIndexed { index, label -> + val selected = index in weekdays + Surface( + onClick = { weekdays = if (selected) weekdays - index else weekdays + index }, + modifier = Modifier.weight(1f).aspectRatio(1f), + shape = CircleShape, + color = if (selected) MaterialTheme.colorScheme.primary else MaterialTheme.colorScheme.surfaceVariant, + ) { + Box(contentAlignment = Alignment.Center) { + Text( + label, + style = MaterialTheme.typography.labelSmall, + color = if (selected) MaterialTheme.colorScheme.onPrimary else MaterialTheme.colorScheme.onSurfaceVariant, + textAlign = TextAlign.Center, + ) + } + } + } + } + + Button(enabled = repeatChoice != RepeatChoice.CUSTOM || weekdays.isNotEmpty(), onClick = { sheet = null }, modifier = Modifier.fillMaxWidth()) { Text("Done") } + } + } + "mode" -> ModalBottomSheet(onDismissRequest = { sheet = null }) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(24.dp), verticalArrangement = Arrangement.spacedBy(12.dp)) { + ChipRow( + label = "Cleaning", + options = buildList { + if (supportsSmartPlan || kind == TimerKind.SMART_PLAN) add(TimerKind.SMART_PLAN to "SmartPlan") + add(TimerKind.CUSTOM to "Custom") + add(TimerKind.VAC_AND_MOP to "Vacuum and mop") + add(TimerKind.MOP to "Mop") + add(TimerKind.VACUUM to "Vacuum") + }, + selected = kind, + onSelect = { kind = it; touchedSettings = touchedSettings + setOf("fan", "water", "route") }, ) - val days = when (repeatChoice) { - RepeatChoice.ONCE, RepeatChoice.EVERY_DAY -> emptySet() - RepeatChoice.WEEKDAYS -> WEEKDAYS - RepeatChoice.WEEKENDS -> WEEKENDS - RepeatChoice.CUSTOM -> weekdays + if (kind == TimerKind.VACUUM || kind == TimerKind.VAC_AND_MOP) { + ChipRow( + label = "Suction", + options = listOf( + VacuumFanPower.QUIET to "Quiet", + VacuumFanPower.BALANCED to "Balanced", + VacuumFanPower.TURBO to "Turbo", + VacuumFanPower.MAX to "Max", + ), + selected = fanPower, + onSelect = { fanPower = it; touchedSettings = touchedSettings + "fan" }, + ) } - val timingChanged = initial == null || hour != initial.hour || minute != initial.minute || - repeatChoice != repeatChoiceOf(initial) || - (repeatChoice == RepeatChoice.CUSTOM && days != initial.weekdays) - onSave(hour, minute, days, if (initial != null && !settingsChanged) start else settings, - repeatChoice == RepeatChoice.ONCE, settingsChanged, timingChanged, enabled) - }, - ) { Text("Save") } - }, - dismissButton = { - TextButton(onClick = onDismiss) { Text("Cancel") } - }, - ) + if (kind == TimerKind.VAC_AND_MOP || kind == TimerKind.MOP) { + ChipRow( + label = "Water", + options = listOf( + WaterBoxMode.LOW to "Low", + WaterBoxMode.MEDIUM to "Medium", + WaterBoxMode.HIGH to "High", + ), + selected = waterBoxMode, + onSelect = { waterBoxMode = it; touchedSettings = touchedSettings + "water" }, + ) + ChipRow( + label = "Mop route", + // A schedule can only use these two routes: a Qrevo Pro that accepts Deep and + // Deep+ as its route setting refuses them inside a start command with -10005 + // "Param error", and the official app's schedule screen offers only these. A + // route an existing schedule already carries stays visible so it is not dropped. + options = buildList { + add(MopRoute.STANDARD to "Standard") + if (supportsFastRoute || mopMode == MopRoute.FAST) add(MopRoute.FAST to "Fast") + if (mopMode == MopRoute.DEEP) add(MopRoute.DEEP to "Deep") + if (mopMode == MopRoute.DEEP_PLUS) add(MopRoute.DEEP_PLUS to "Deep+") + }, + selected = mopMode, + onSelect = { mopMode = it; touchedSettings = touchedSettings + "route" }, + ) + } + ChipRow( + label = "Passes", + options = listOf(1 to "1", 2 to "2", 3 to "3"), + selected = repeat, + onSelect = { repeat = it; touchedSettings = touchedSettings + "repeat" }, + ) + + if (kind == TimerKind.CUSTOM) Text("Uses the per-room cleaning settings saved on the robot.") + Button(onClick = { sheet = null }, modifier = Modifier.fillMaxWidth()) { Text("Done") } + } + } + "rooms" -> { + var draftFull by remember { mutableStateOf(false) } + var draftRooms by remember { mutableStateOf(selected) } + var confirmed by remember(currentFlag) { mutableStateOf(initial == null || confirmedMap == currentFlag) } + val unknown = draftRooms.filter { id -> rooms.none { it.id == id } } + ModalBottomSheet(onDismissRequest = { sheet = null }) { + Column(Modifier.fillMaxWidth().verticalScroll(rememberScrollState()).padding(24.dp), verticalArrangement = Arrangement.spacedBy(10.dp)) { + Text(mapName, style = MaterialTheme.typography.titleLarge) + Text("Currently loaded map. Load another floor from Maps before selecting its rooms.", style = MaterialTheme.typography.bodySmall) + Row(verticalAlignment = Alignment.CenterVertically) { Checkbox(draftFull, { draftFull = it }); Text("Full — entire map") } + if (!draftFull) { + if (initial != null) Row(verticalAlignment = Alignment.CenterVertically) { + Checkbox(confirmed, { confirmed = it }); Text("This is the map for this schedule") + } + if (map != null) VacuumMapImage(map, draftRooms, onRoomTap = { id -> + if (rooms.any { it.id == id }) draftRooms = if (id in draftRooms) draftRooms - id else draftRooms + id + }, modifier = Modifier.fillMaxWidth().height(220.dp)) + if (rooms.isEmpty()) Text("No rooms loaded. Open the vacuum map, then return here.") + rooms.forEach { room -> + Row(Modifier.fillMaxWidth().clickable { draftRooms = if (room.id in draftRooms) draftRooms - room.id else draftRooms + room.id }, verticalAlignment = Alignment.CenterVertically) { + Checkbox(room.id in draftRooms, { checked -> draftRooms = if (checked) (draftRooms + room.id).distinct() else draftRooms - room.id }) + Text(room.name, Modifier.weight(1f)) + } + } + if (unknown.isNotEmpty()) { + Text("Some saved rooms are unavailable on this map.") + TextButton(enabled = confirmed, onClick = { draftRooms = draftRooms - unknown.toSet() }) { Text("Remove unavailable rooms") } + } + } + Button(enabled = draftFull || (confirmed && draftRooms.isNotEmpty() && unknown.isEmpty()), onClick = { + wholeHome = draftFull; selected = draftRooms; roomsChanged = true; confirmedMap = currentFlag; sheet = null + }, modifier = Modifier.fillMaxWidth()) { Text("Done") } + } + } + } + } + } +} + +@Composable +private fun ScheduleRow(title: String, value: String, onClick: () -> Unit) { + Row(Modifier.fillMaxWidth().clickable(onClick = onClick).padding(horizontal = 16.dp, vertical = 14.dp), + verticalAlignment = Alignment.CenterVertically, horizontalArrangement = Arrangement.spacedBy(12.dp)) { + Text(title, Modifier.weight(1f), style = MaterialTheme.typography.bodyLarge) + Text(value, style = MaterialTheme.typography.bodyMedium, color = MaterialTheme.colorScheme.onSurfaceVariant, + maxLines = 2, overflow = TextOverflow.Ellipsis) + Icon(Icons.Default.ChevronRight, null, tint = MaterialTheme.colorScheme.onSurfaceVariant) + } } /** A labelled group of single-choice chips that wraps onto more lines, so the chosen one is always in view. */ diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt index fb688304..fad348fb 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt @@ -738,7 +738,7 @@ private fun SessionRoomsBadge(roomNames: List, modifier: Modifier = Modi } @Composable -private fun VacuumMapImage( +internal fun VacuumMapImage( map: ParsedMap, selectedRoomIds: List, onRoomTap: (Int) -> Unit, @@ -2260,3 +2260,4 @@ private fun stateTint(state: Int?): Color = when (state) { VacuumStateCodes.GOING_TO_TARGET, VacuumStateCodes.MAPPING -> MaterialTheme.colorScheme.primary else -> MaterialTheme.colorScheme.onSurfaceVariant } + diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt index b9c9b7aa..0425ef5b 100644 --- a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt @@ -47,4 +47,19 @@ class ServerJobEditingTest { @Test fun weekly_ranges_are_not_silently_lost() { assertEquals(setOf(1,2,3,4,5), job("10 9 ? * 1-5").toCleanTimer().weekdays) } + @Test fun explicit_room_change_preserves_map_native_name_and_room_order() { + val original = job(); val timer = original.toCleanTimer() + val patch = serverJobEditPatch(timer,9,10,setOf(0,6),timer.settings.copy(segments = "17,20,18"),false,null,true,false) + val saved = ServerSchedule(JsonObject(original.raw + patch)) + assertEquals("17,20,18", saved.settingsText("segments")) + assertEquals(original.settings!! - "segments", saved.settings!! - "segments") + assertFalse("enabled" in patch) + } + @Test fun custom_and_smartplan_remain_distinct_cleaning_modes() { + val custom = timerSettingsFor(TimerKind.CUSTOM, null,null,null,1) + val smart = timerSettingsFor(TimerKind.SMART_PLAN,null,null,null,1) + assertEquals(TimerKind.CUSTOM,custom.kind) + assertEquals(TimerKind.SMART_PLAN,smart.kind) + assertNotEquals(custom.toActionObject(),smart.toActionObject()) + } } diff --git a/docs/schedules.md b/docs/schedules.md index 06b56961..eec5cd46 100644 --- a/docs/schedules.md +++ b/docs/schedules.md @@ -6,7 +6,7 @@ If the jobs collection is unavailable with HTTP 404 or 405, the app uses the leg ## Editing and enablement -Tap a schedule to edit its time, repetition or cleaning settings. Model-specific SmartPlan, water and mop-route options are retained. Jobs in an unsupported format remain visible with a read-only editor rather than being silently converted. +The compact list is sorted by start time and shows repetition, Full or selected rooms, cleaning mode and an enable switch. Tap a schedule to open the editor, with separate Start, Repeat, Cleaning Mode and Map controls. Select Full or choose rooms from the loaded map; imported map references are preserved. Confirm the intended map before replacing saved rooms. Model-specific SmartPlan, water and mop-route options are retained. Jobs in an unsupported format remain visible with a read-only editor rather than being silently converted. Server jobs retain their IDs, native references, room order and unedited settings. Time and cleaning-setting edits do not recreate native timers. Changing Enabled verifies a linked native timer, changes it only when necessary, then saves and reads back the server job. Jobs without a native reference use only the server API. The HTTP job ID and native timer name are different identifiers. From 7c8ec771181eda24b11070cfea0fb6ed84a8db5c Mon Sep 17 00:00:00 2001 From: pponce Date: Mon, 26 Oct 2026 18:42:38 -0700 Subject: [PATCH 4/4] Restore legacy schedule rollback and test jobs-list fallback Restore the original legacy entry when a replacement fails and report restoration failures. Keep server-job edit behavior unchanged. Exercise 404/405 fallback, 500 propagation, empty jobs and legacy restoration outcomes. Use explicit schedule imports and remove trailing blank lines. --- .../localrock/shared/device/ScheduleApi.kt | 6 +- .../shared/schedule/ScheduleEnablement.kt | 9 ++- .../shared/schedule/ServerJobCreation.kt | 3 +- .../shared/schedule/ServerJobDeletion.kt | 6 +- .../shared/schedule/ServerSchedule.kt | 12 ++- .../localrock/shared/vacuum/CleanTimer.kt | 1 - .../shared/vacuum/LegacyScheduleOperations.kt | 36 +++++++++ .../localrock/shared/vacuum/ScheduleMirror.kt | 1 - .../shared/vacuum/ServerJobEditing.kt | 7 +- .../localrock/shared/vacuum/ServerTimer.kt | 1 - .../shared/vacuum/VacuumRepository.kt | 46 +++++++----- .../localrock/ui/vacuum/ScheduleScreen.kt | 17 ++++- .../localrock/ui/vacuum/VacuumDetailScreen.kt | 1 - .../shared/device/ScheduleJobsApiTest.kt | 13 +++- .../shared/schedule/ScheduleEnablementTest.kt | 16 +++- .../shared/schedule/ServerJobCreationTest.kt | 12 ++- .../shared/schedule/ServerJobDeletionTest.kt | 12 ++- .../shared/schedule/ServerScheduleTest.kt | 19 ++++- .../vacuum/LegacyScheduleOperationsTest.kt | 75 +++++++++++++++++++ .../shared/vacuum/ServerJobEditingTest.kt | 13 +++- 20 files changed, 254 insertions(+), 52 deletions(-) create mode 100644 composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperations.kt create mode 100644 composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperationsTest.kt diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt index b3c6a3e0..814e1d35 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/device/ScheduleApi.kt @@ -14,7 +14,10 @@ import io.ktor.http.ContentType import io.ktor.http.content.TextContent import io.ktor.http.isSuccess import io.ktor.http.encodeURLPathPart -import kotlinx.serialization.json.* +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.intOrNull +import kotlinx.serialization.json.put import kotlinx.serialization.json.Json import kotlinx.serialization.json.JsonObject import kotlinx.serialization.json.JsonPrimitive @@ -74,4 +77,3 @@ class ScheduleApi(private val client: HttpClient) : ScheduleMirror { return body } } - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt index e71f1f24..2039d7ef 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablement.kt @@ -4,7 +4,13 @@ import kotlinx.coroutines.CancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import kotlinx.coroutines.sync.Mutex -import kotlinx.serialization.json.* +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.put /** No retries or rollback: every write is preceded and followed by fresh reads. */ class ScheduleEnablement( @@ -152,4 +158,3 @@ class ScheduleEnablement( /** Captured native RPC shape; timer name and HTTP job ID must never be interchanged. */ fun nativeTimerUpdateParams(name: String, enabled: Boolean): List = listOf(JsonArray(listOf(JsonPrimitive(name), JsonPrimitive(if (enabled) "on" else "off")))) - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt index 73ca4257..c6856b25 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreation.kt @@ -3,7 +3,8 @@ package com.kodraliu.localrock.shared.schedule import kotlinx.coroutines.CancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive -import kotlinx.serialization.json.* +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject /** Complete a native creation with one HTTP POST, then read back even if its response was lost. */ class ServerJobCreation( diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt index ec006ade..eecacebe 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletion.kt @@ -3,7 +3,11 @@ package com.kodraliu.localrock.shared.schedule import kotlinx.coroutines.CancellationException import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive -import kotlinx.serialization.json.* +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.contentOrNull /** Verify each side of a deletion; uncertain writes are read back, never repeated or rolled back. */ class ServerJobDeletion( diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt index 5eb17d6a..008bb1a4 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/schedule/ServerSchedule.kt @@ -1,6 +1,15 @@ package com.kodraliu.localrock.shared.schedule -import kotlinx.serialization.json.* +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.add +import kotlinx.serialization.json.booleanOrNull +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.put /** Keep the original payload: firmware-specific fields must survive edits. */ data class ServerSchedule(val raw: JsonObject) { @@ -109,4 +118,3 @@ fun nativeTimerState(result: JsonElement?, name: String): String { else -> "Unknown" } } - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt index 70d4d3c6..487d73af 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/CleanTimer.kt @@ -166,4 +166,3 @@ fun TimerSettings.summary(): String? { repeat?.takeIf { it > 1 }?.let { parts += "$it passes" } return parts.takeIf { it.isNotEmpty() }?.joinToString(" · ") } - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperations.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperations.kt new file mode 100644 index 00000000..d15d06de --- /dev/null +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperations.kt @@ -0,0 +1,36 @@ +package com.kodraliu.localrock.shared.vacuum + +import com.kodraliu.localrock.shared.device.DeviceApiException +import com.kodraliu.localrock.shared.schedule.ScheduleException +import kotlinx.coroutines.CancellationException + +/** Only an unavailable jobs collection permits reading legacy schedules. */ +internal suspend fun loadScheduleList( + readJobs: (suspend () -> List)?, + readLegacy: suspend () -> List, +): List { + if (readJobs != null) { + try { return readJobs() } + catch (e: DeviceApiException) { + if (e.responseCode != 404 && e.responseCode != 405) throw e + } + } + return readLegacy() +} + +/** Used only for legacy delete-and-add edits, never for HTTP server-job edits. */ +internal suspend fun replaceLegacySchedule( + replace: suspend () -> Unit, + restore: suspend () -> Unit, +) { + try { replace() } + catch (e: CancellationException) { throw e } + catch (e: Exception) { + try { restore() } + catch (cancelled: CancellationException) { throw cancelled } + catch (rollback: Exception) { + throw ScheduleException("The schedule edit failed (${e.message}); restoring the old schedule also failed (${rollback.message}). Refresh to check its state.") + } + throw ScheduleException("The schedule edit failed (${e.message}). The old schedule was restored.") + } +} diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt index ec29c1e4..6160279b 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ScheduleMirror.kt @@ -61,4 +61,3 @@ internal fun mirrorJobBody( fields["param"] = param return JsonObject(fields) } - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt index ef095b17..2c02231c 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditing.kt @@ -2,7 +2,12 @@ package com.kodraliu.localrock.shared.vacuum import com.kodraliu.localrock.shared.schedule.ScheduleException import com.kodraliu.localrock.shared.schedule.ServerSchedule -import kotlinx.serialization.json.* +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.contentOrNull +import kotlinx.serialization.json.put import kotlinx.datetime.LocalDate /** Unsupported jobs stay visible rather than becoming a misleading empty schedule list. */ diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt index 9b9c3ef8..217f9411 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/ServerTimer.kt @@ -102,4 +102,3 @@ internal fun usesServerTimer(initStatusResult: JsonElement?): Boolean? { val featureSet = localInfo["featureset"]?.jsonPrimitive?.contentOrNull?.toIntOrNull() ?: return null return (featureSet and 1) != 0 } - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt index cb8cf65d..43c1ed2e 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/shared/vacuum/VacuumRepository.kt @@ -1,7 +1,11 @@ package com.kodraliu.localrock.shared.vacuum import com.kodraliu.localrock.shared.device.DeviceApiException -import com.kodraliu.localrock.shared.schedule.* +import com.kodraliu.localrock.shared.schedule.ScheduleEnablement +import com.kodraliu.localrock.shared.schedule.ScheduleException +import com.kodraliu.localrock.shared.schedule.ServerJobCreation +import com.kodraliu.localrock.shared.schedule.ServerJobDeletion +import com.kodraliu.localrock.shared.schedule.nativeTimerState import kotlinx.coroutines.currentCoroutineContext import kotlinx.coroutines.ensureActive import com.kodraliu.localrock.shared.model.Room @@ -889,18 +893,17 @@ class VacuumRepository( /** Only an unavailable collection permits legacy fallback; an empty jobs list does not. */ suspend fun fetchTimers() { - if (scheduleMirror != null && !demo) { - try { - _timers.value = scheduleMirror.list(duid).map { it.toCleanTimer() } + _timers.value = loadScheduleList( + readJobs = if (scheduleMirror != null && !demo) ({ + scheduleMirror.list(duid).map { it.toCleanTimer() } .sortedWith(compareBy { it.hour }.thenBy { it.minute }.thenBy { it.id }) - return - } catch (e: DeviceApiException) { - if (e.responseCode != 404 && e.responseCode != 405) throw e - } - } - val resp = session.getTimer() - resp.requireOk("get_timer") - _timers.value = parseTimerList(resp.result) + }) else null, + readLegacy = { + val resp = session.getTimer() + resp.requireOk("get_timer") + parseTimerList(resp.result) + }, + ) } suspend fun nativeScheduleState(timer: CleanTimer): String { @@ -1074,13 +1077,17 @@ class VacuumRepository( val newSettings = settings.copy(serverTimerId = timer.settings.serverTimerId, segments = settings.segments ?: timer.settings.segments, mapIndex = timer.settings.mapIndex, cleanMop = timer.settings.cleanMop) if (useServerTimer) session.delServerTimer(id).requireOk("del_server_timer") else session.delTimer(id).requireOk("del_timer") - try { - saveTimerEntry(useServerTimer, id, cron, enabled = timer.enabled, settings = newSettings) - if (useServerTimer && !timer.enabled) session.updServerTimer(id, false).requireOk("upd_server_timer") - } catch (e: CancellationException) { throw e } - catch (_: Exception) { - throw ScheduleException("The old native timer was removed, but its replacement could not be confirmed. Refresh before retrying; no rollback was attempted.") - } + replaceLegacySchedule( + replace = { + saveTimerEntry(useServerTimer, id, cron, enabled = timer.enabled, settings = newSettings) + if (useServerTimer && !timer.enabled) session.updServerTimer(id, false).requireOk("upd_server_timer") + }, + restore = { + val oldCron = buildCron(timer.minute, timer.hour, timer.weekdays, timer.date) + saveTimerEntry(useServerTimer, id, oldCron, enabled = timer.enabled, settings = timer.settings) + if (useServerTimer && !timer.enabled) session.updServerTimer(id, false).requireOk("upd_server_timer") + }, + ) if (useServerTimer) { updateCloudRecord(timer.id, id, minute, hour, newWeekdays, date, timer.enabled, newSettings) @@ -1585,4 +1592,3 @@ internal fun VacuumStatus.applyDpsPush(push: Map): VacuumStatu dryStatus = dryStatus, ) } - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt index b1e4f938..28c476fd 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/ScheduleScreen.kt @@ -1,10 +1,20 @@ package com.kodraliu.localrock.ui.vacuum import androidx.compose.foundation.clickable -import androidx.compose.foundation.layout.* +import androidx.compose.foundation.layout.PaddingValues import androidx.compose.foundation.shape.RoundedCornerShape -import androidx.compose.material3.* -import androidx.compose.material.icons.filled.* +import androidx.compose.material3.Button +import androidx.compose.material3.Card +import androidx.compose.material3.Checkbox +import androidx.compose.material3.ModalBottomSheet +import androidx.compose.material3.SegmentedButton +import androidx.compose.material3.SegmentedButtonDefaults +import androidx.compose.material3.SingleChoiceSegmentedButtonRow +import androidx.compose.material3.TimeInput +import androidx.compose.material3.rememberTimePickerState +import androidx.compose.material.icons.filled.Check +import androidx.compose.material.icons.filled.ChevronRight +import androidx.compose.material.icons.filled.Refresh import androidx.compose.ui.text.style.TextOverflow import androidx.compose.ui.window.Dialog import androidx.compose.ui.window.DialogProperties @@ -633,4 +643,3 @@ private fun formatRepeat(timer: CleanTimer): String { else -> choice.label } } - diff --git a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt index fad348fb..652f4d64 100644 --- a/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt +++ b/composeApp/src/commonMain/kotlin/com/kodraliu/localrock/ui/vacuum/VacuumDetailScreen.kt @@ -2260,4 +2260,3 @@ private fun stateTint(state: Int?): Color = when (state) { VacuumStateCodes.GOING_TO_TARGET, VacuumStateCodes.MAPPING -> MaterialTheme.colorScheme.primary else -> MaterialTheme.colorScheme.onSurfaceVariant } - diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt index fcbbb85d..22331dc2 100644 --- a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/device/ScheduleJobsApiTest.kt @@ -1,10 +1,17 @@ package com.kodraliu.localrock.shared.device import io.ktor.client.HttpClient -import io.ktor.client.engine.mock.* -import io.ktor.http.* +import io.ktor.client.engine.mock.MockEngine +import io.ktor.client.engine.mock.respond +import io.ktor.http.ContentType +import io.ktor.http.HttpHeaders +import io.ktor.http.HttpStatusCode +import io.ktor.http.headersOf import kotlinx.coroutines.test.runTest -import kotlin.test.* +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue class ScheduleJobsApiTest { @Test fun lists_result_and_data_envelopes_and_keeps_raw_settings() = runTest { diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt index 9c80b071..d7519dc4 100644 --- a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ScheduleEnablementTest.kt @@ -6,8 +6,19 @@ import kotlinx.coroutines.delay import kotlinx.coroutines.withTimeout import kotlinx.coroutines.cancelAndJoin import kotlinx.coroutines.test.runTest -import kotlinx.serialization.json.* -import kotlin.test.* +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonNull +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.put +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue class ScheduleEnablementTest { private class Fixture(serverEnabled: Boolean = false, native: Boolean = true, robotEnabled: Boolean = false) { @@ -282,4 +293,3 @@ class ScheduleEnablementTest { assertFailsWith { f.set(true) }; assertEquals(0, f.jobWrites) } } - diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt index 74d564cd..75225948 100644 --- a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobCreationTest.kt @@ -3,8 +3,16 @@ package com.kodraliu.localrock.shared.schedule import kotlinx.coroutines.delay import kotlinx.coroutines.withTimeout import kotlinx.coroutines.test.runTest -import kotlinx.serialization.json.* -import kotlin.test.* +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonObject +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue +import kotlin.test.fail class ServerJobCreationTest { private class Fixture { diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt index 649f7f38..7c3e9115 100644 --- a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerJobDeletionTest.kt @@ -1,8 +1,16 @@ package com.kodraliu.localrock.shared.schedule import kotlinx.coroutines.test.runTest -import kotlinx.serialization.json.* -import kotlin.test.* +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonElement +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.jsonObject +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertTrue class ServerJobDeletionTest { private class Fixture(native: Boolean = true) { diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt index 59563806..f7271bb5 100644 --- a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/schedule/ServerScheduleTest.kt @@ -1,7 +1,21 @@ package com.kodraliu.localrock.shared.schedule -import kotlinx.serialization.json.* -import kotlin.test.* +import kotlinx.serialization.json.Json +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.JsonPrimitive +import kotlinx.serialization.json.boolean +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonArray +import kotlinx.serialization.json.jsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNull +import kotlin.test.assertTrue class ServerScheduleTest { private fun imported(stringParam: Boolean = false): ServerSchedule { @@ -59,4 +73,3 @@ class ServerScheduleTest { assertEquals("Ambiguous", nativeTimerState(Json.parseToJsonElement("""[["x","on"],["x","off"]]"""), "x")) } } - diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperationsTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperationsTest.kt new file mode 100644 index 00000000..439f3c5f --- /dev/null +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/LegacyScheduleOperationsTest.kt @@ -0,0 +1,75 @@ +package com.kodraliu.localrock.shared.vacuum + +import com.kodraliu.localrock.shared.device.DeviceApiException +import com.kodraliu.localrock.shared.schedule.ScheduleException +import kotlinx.coroutines.CancellationException +import kotlinx.coroutines.test.runTest +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertSame +import kotlin.test.assertTrue + +class LegacyScheduleOperationsTest { + @Test fun unavailable_jobs_fall_back_for_404_and_405() = runTest { + for (status in listOf(404, 405)) { + var legacyReads = 0 + val result = loadScheduleList( + readJobs = { throw DeviceApiException(status, "unavailable") }, + readLegacy = { legacyReads++; listOf("legacy") }, + ) + assertEquals(listOf("legacy"), result) + assertEquals(1, legacyReads) + } + } + + @Test fun server_failure_does_not_fall_back() = runTest { + var legacyReads = 0 + val failure = DeviceApiException(500, "server failure") + val actual = assertFailsWith { + loadScheduleList({ throw failure }, { legacyReads++; listOf("legacy") }) + } + assertSame(failure, actual) + assertEquals(0, legacyReads) + } + + @Test fun empty_jobs_are_authoritative() = runTest { + var legacyReads = 0 + assertEquals(emptyList(), loadScheduleList({ emptyList() }, { legacyReads++; listOf("legacy") })) + assertEquals(0, legacyReads) + } + + @Test fun refused_legacy_replacement_restores_original() = runTest { + val old = CleanTimer("old", false, 7, 30, setOf(1, 3), settings = TimerSettings(fanPower = 102)) + var stored: CleanTimer? = null // The delete succeeded. + var restores = 0 + val error = assertFailsWith { + replaceLegacySchedule({ error("replacement refused") }, { restores++; stored = old }) + } + assertEquals(old, stored) + assertEquals(1, restores) + assertTrue(error.message.orEmpty().contains("old schedule was restored")) + } + + @Test fun failed_restoration_reports_both_failures() = runTest { + val error = assertFailsWith { + replaceLegacySchedule({ error("replacement refused") }, { error("restore refused") }) + } + assertTrue(error.message.orEmpty().contains("replacement refused")) + assertTrue(error.message.orEmpty().contains("restore refused")) + } + + @Test fun successful_replacement_does_not_restore() = runTest { + var restored = false + replaceLegacySchedule({}, { restored = true }) + assertEquals(false, restored) + } + + @Test fun cancellation_does_not_start_restoration() = runTest { + var restored = false + assertFailsWith { + replaceLegacySchedule({ throw CancellationException("cancelled") }, { restored = true }) + } + assertEquals(false, restored) + } +} diff --git a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt index 0425ef5b..832d4b88 100644 --- a/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt +++ b/composeApp/src/commonTest/kotlin/com/kodraliu/localrock/shared/vacuum/ServerJobEditingTest.kt @@ -1,8 +1,17 @@ package com.kodraliu.localrock.shared.vacuum import com.kodraliu.localrock.shared.schedule.ServerSchedule -import kotlinx.serialization.json.* -import kotlin.test.* +import kotlinx.serialization.json.JsonArray +import kotlinx.serialization.json.JsonObject +import kotlinx.serialization.json.buildJsonObject +import kotlinx.serialization.json.jsonPrimitive +import kotlinx.serialization.json.put +import kotlin.test.Test +import kotlin.test.assertEquals +import kotlin.test.assertFailsWith +import kotlin.test.assertFalse +import kotlin.test.assertNotEquals +import kotlin.test.assertTrue class ServerJobEditingTest { private fun job(cron: String = "10 9 ? * 0,6", repeated: Boolean = true) = ServerSchedule(buildJsonObject {