diff --git a/CHANGELOG.md b/CHANGELOG.md index a4bc385..4217ddd 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -56,6 +56,20 @@ uses semantic versioning (`MAJOR.MINOR.PATCH`). ### Fixed +- **Changing a fronting preference no longer wipes your system profile.** + Flipping either switch under Settings, Fronting sent the new value along with + an instruction to clear your system's description, tag, colour, note, avatar + and banner. Those fields are emptied by sending nothing for them, and that + screen sends nothing for anything except the switch you touched, so the save + cleared them every time. Present since the preferences arrived in 1.5.0. If + you lost a description or a tag this way it cannot be recovered from the app; + the values are gone from the server too. + +- **Turning quiet hours off on a notification channel now turns them off.** + Unticking the box reported success and left the window in place, because the + app never actually told the server the field had changed. The same fix stops + an unrelated channel edit from clearing a window you wanted to keep. + - **Sharing and custom fields no longer explain failures their own way.** The screens that tell three kinds of refusal apart, so they can ask for a password or say publishing is off, carried a second set of wordings for diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/PatchJsonAdapters.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/PatchJsonAdapters.kt index 964c2c2..5fcde9f 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/PatchJsonAdapters.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/data/api/PatchJsonAdapters.kt @@ -7,6 +7,7 @@ import com.squareup.moshi.Moshi import com.squareup.moshi.Types import systems.lupine.sheaf.data.model.GroupUpdate import systems.lupine.sheaf.data.model.MemberUpdate +import systems.lupine.sheaf.data.model.NotificationChannelUpdate import systems.lupine.sheaf.data.model.SystemUpdate /** @@ -37,9 +38,25 @@ import systems.lupine.sheaf.data.model.SystemUpdate internal class PatchWriter( private val writer: JsonWriter, private val anyAdapter: JsonAdapter, + /** + * Whether a null in a clearable field means "clear it". + * + * False for a body that carries only part of the form, where a null means + * the caller simply did not populate that field. Writing it anyway would + * clear something the user never touched, which is how toggling a front + * preference wiped the system's description, tag, colour, note, avatar and + * banner: that screen sends one boolean and nothing else. + */ + private val clearsUnsetFields: Boolean = true, ) { - /** Server clears the column on an explicit null, so always write it. */ + /** + * Server clears the column on an explicit null. + * + * A set value is always written. A null is written only when this body is + * the whole form, because only then does null mean the user emptied it. + */ fun clears(name: String, value: Any?) { + if (value == null && !clearsUnsetFields) return val previous = writer.serializeNulls writer.serializeNulls = true writer.name(name) @@ -64,7 +81,7 @@ class MemberUpdateJsonAdapter(moshi: Moshi) : JsonAdapter() { override fun toJson(writer: JsonWriter, value: MemberUpdate?) { if (value == null) { writer.nullValue(); return } writer.beginObject() - PatchWriter(writer, anyAdapter).apply { + PatchWriter(writer, anyAdapter, value.clearsUnsetFields).apply { // NOT NULL server-side: name, privacy. omitsWhenNull("name", value.name) omitsWhenNull("privacy", value.privacy) @@ -101,7 +118,7 @@ class GroupUpdateJsonAdapter(moshi: Moshi) : JsonAdapter() { override fun toJson(writer: JsonWriter, value: GroupUpdate?) { if (value == null) { writer.nullValue(); return } writer.beginObject() - PatchWriter(writer, anyAdapter).apply { + PatchWriter(writer, anyAdapter, value.clearsUnsetFields).apply { omitsWhenNull("name", value.name) omitsWhenNull("privacy", value.privacy) clears("description", value.description) @@ -124,13 +141,68 @@ class GroupUpdateJsonAdapter(moshi: Moshi) : JsonAdapter() { } } +class NotificationChannelUpdateJsonAdapter(moshi: Moshi) : JsonAdapter() { + private val anyAdapter: JsonAdapter by lazy { moshi.adapter(Any::class.java) } + + override fun toJson(writer: JsonWriter, value: NotificationChannelUpdate?) { + if (value == null) { writer.nullValue(); return } + writer.beginObject() + PatchWriter(writer, anyAdapter).apply { + // quiet_hours is the one genuinely nullable field on a channel, and + // the server keys on whether it was in the request rather than on + // its value. Moshi dropped the null, so unticking "Quiet hours" + // sent an empty body, the server left the column alone, and the + // window came back on the next refresh. + // + // Written only when the user actually touched it. This body is a + // partial patch, unlike the member and group ones, so an + // unconditional null here would clear the window on every unrelated + // channel save. + if (value.quietHoursSet) clears("quiet_hours", value.quietHours) + // webhook_secret, group_rules and member_rules are absent from the + // server's _reject_explicit_null list, so a null would be accepted + // rather than refused. That makes omitting them load-bearing: these + // are sent only when the user edited them, and an explicit null + // would wipe a secret or replace every rule with nothing. + omitsWhenNull("webhook_secret", value.webhookSecret) + omitsWhenNull("group_rules", value.groupRules) + omitsWhenNull("member_rules", value.memberRules) + omitsWhenNull("name", value.name) + omitsWhenNull("destination_config", value.destinationConfig) + omitsWhenNull("base_all_members", value.baseAllMembers) + omitsWhenNull("base_include_private", value.baseIncludePrivate) + omitsWhenNull("trigger_on_start", value.triggerOnStart) + omitsWhenNull("trigger_on_stop", value.triggerOnStop) + omitsWhenNull("trigger_on_cofront_change", value.triggerOnCofrontChange) + omitsWhenNull("cofront_redaction", value.cofrontRedaction) + omitsWhenNull("payload_sensitivity", value.payloadSensitivity) + omitsWhenNull("debounce_seconds", value.debounceSeconds) + omitsWhenNull("aggregation_window_seconds", value.aggregationWindowSeconds) + } + writer.endObject() + } + + override fun fromJson(reader: JsonReader) = requestOnly("NotificationChannelUpdate") + + companion object { + /** Needs the Moshi instance, so it registers as a factory. */ + val FACTORY = Factory { type, _, moshi -> + if (Types.getRawType(type) == NotificationChannelUpdate::class.java) { + NotificationChannelUpdateJsonAdapter(moshi) + } else { + null + } + } + } +} + class SystemUpdateJsonAdapter(moshi: Moshi) : JsonAdapter() { private val anyAdapter: JsonAdapter by lazy { moshi.adapter(Any::class.java) } override fun toJson(writer: JsonWriter, value: SystemUpdate?) { if (value == null) { writer.nullValue(); return } writer.beginObject() - PatchWriter(writer, anyAdapter).apply { + PatchWriter(writer, anyAdapter, value.clearsUnsetFields).apply { // NOT NULL server-side: name, privacy, show_member_created_date // and both front preferences (alongside date_format, which this // client does not send). diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt index ced1035..baefb7d 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/Models.kt @@ -375,6 +375,8 @@ data class SystemUpdate( // Only consulted when raising privacy to public is deferred. val password: String? = null, @Json(name = "totp_code") val totpCode: String? = null, + /** See [MemberUpdate.clearsUnsetFields]: default false is the safe answer. */ + @Json(ignore = true) val clearsUnsetFields: Boolean = false, ) // ── System Safety ───────────────────────────────────────────────────────────── @@ -650,6 +652,18 @@ data class MemberUpdate( // Only consulted when the edit is a deferred exposure. Never stored. val password: String? = null, @Json(name = "totp_code") val totpCode: String? = null, + /** + * Whether an optional field left null means "clear it" or "leave it alone". + * + * Only a caller that owns the WHOLE form can mean the first: it populates + * every clearable field from its own state, so a null there really is the + * user emptying the box. A caller patching one setting populates nothing + * else, and clearing on its behalf wipes whatever the user had. + * + * Default false so that is the safe answer, and a screen that only sends + * part of the body cannot destroy the rest of it by omission. + */ + @Json(ignore = true) val clearsUnsetFields: Boolean = false, ) // ── Fronts ──────────────────────────────────────────────────────────────────── @@ -801,6 +815,8 @@ data class GroupUpdate( // Popped server-side before persistence, never a group column. val password: String? = null, @Json(name = "totp_code") val totpCode: String? = null, + /** See [MemberUpdate.clearsUnsetFields]: default false is the safe answer. */ + @Json(ignore = true) val clearsUnsetFields: Boolean = false, ) @JsonClass(generateAdapter = true) diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/NotificationChannelModels.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/NotificationChannelModels.kt index b9005e9..6fbbe85 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/NotificationChannelModels.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/data/model/NotificationChannelModels.kt @@ -113,9 +113,14 @@ data class NotificationChannelRead( * * Note: backend rejects explicit null on most fields (only quiet_hours * accepts null = clear). The UI keeps the ones it isn't editing out of - * the request entirely by leaving them as `null` here, which Moshi omits - * by default. Whenever the user toggles a control, the corresponding - * field is set to a non-null value. + * the request entirely by leaving them as `null` here. Whenever the user + * toggles a control, the corresponding field is set to a non-null value. + * + * Serialised by [NotificationChannelUpdateJsonAdapter], not by Moshi's + * generated one. Moshi drops nulls, which cannot express the clear: this + * class once relied on "null = clear quiet hours" while the field was never + * reaching the server at all, so unticking the window reported success and + * changed nothing. */ @JsonClass(generateAdapter = true) data class NotificationChannelUpdate( @@ -134,6 +139,18 @@ data class NotificationChannelUpdate( @Json(name = "quiet_hours") val quietHours: QuietHoursSpec? = null, @Json(name = "group_rules") val groupRules: List? = null, @Json(name = "member_rules") val memberRules: List? = null, + /** + * Whether [quietHours] is an answer rather than an absence. Not serialised: + * it decides whether `quiet_hours` appears in the body at all. + * + * Needed because null means two different things here. The user turning + * the window off is a clear, and has to be sent; the user editing the + * channel's name while the window is untouched is an omission, and must + * not be. Without this they are the same value, and whichever meaning the + * adapter picked would break the other: dropping the null leaves quiet + * hours on forever, writing it always wipes them on any unrelated save. + */ + @Json(ignore = true) val quietHoursSet: Boolean = false, ) @JsonClass(generateAdapter = true) diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt index d8ea5d2..cb80878 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/di/NetworkModule.kt @@ -9,6 +9,7 @@ import systems.lupine.sheaf.data.api.CustomFieldValueSetJsonAdapter import systems.lupine.sheaf.data.api.SystemUpdateJsonAdapter import systems.lupine.sheaf.data.api.GroupUpdateJsonAdapter import systems.lupine.sheaf.data.api.MemberUpdateJsonAdapter +import systems.lupine.sheaf.data.api.NotificationChannelUpdateJsonAdapter import systems.lupine.sheaf.data.api.FrontUpdateJsonAdapter import systems.lupine.sheaf.data.model.FrontUpdate import systems.lupine.sheaf.data.api.RawJsonAdapter @@ -57,6 +58,7 @@ object NetworkModule { .add(MemberUpdateJsonAdapter.FACTORY) .add(GroupUpdateJsonAdapter.FACTORY) .add(SystemUpdateJsonAdapter.FACTORY) + .add(NotificationChannelUpdateJsonAdapter.FACTORY) .addLast(KotlinJsonAdapterFactory()) .build() diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/groups/GroupsViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/groups/GroupsViewModel.kt index a24e522..a446984 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/groups/GroupsViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/groups/GroupsViewModel.kt @@ -298,6 +298,7 @@ class GroupDetailViewModel @Inject constructor( )) } else { api.updateGroup(groupId!!, GroupUpdate( + clearsUnsetFields = true, name = f.name.trim(), description = f.description.takeIf { it.isNotBlank() }, color = f.color.takeIf { it.isNotBlank() }, diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/members/MembersViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/members/MembersViewModel.kt index 77437ec..00bc52f 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/members/MembersViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/members/MembersViewModel.kt @@ -514,6 +514,9 @@ class MemberDetailViewModel @Inject constructor( )).also { createdMemberId = it.id } } else { val update = MemberUpdate( + // The whole form, so a null here is the user emptying + // the box rather than this screen not knowing. + clearsUnsetFields = true, name = f.name.trim(), displayName = f.displayName.takeIf { it.isNotBlank() }, // Null clears it. That used to need an empty string, diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/notifications/ChannelsYouOwnViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/notifications/ChannelsYouOwnViewModel.kt index bdf751e..7b1b91e 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/notifications/ChannelsYouOwnViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/notifications/ChannelsYouOwnViewModel.kt @@ -204,8 +204,11 @@ class ChannelDetailViewModel @Inject constructor( debounceSeconds = draft.debounceSeconds, aggregationWindowSeconds = draft.aggregationWindowSeconds, // quietHours / groupRules / memberRules only sent when the - // user actively toggled them — otherwise we pass null and - // Moshi omits them from the wire JSON. + // user actively toggled them. For the two rule sets a null is + // enough to mean "untouched", since the adapter omits them. Quiet + // hours needs the flag as well: null there is also how the window + // is cleared, so the body has to say which of the two it means. + quietHoursSet = draft.quietHoursSet, quietHours = if (draft.quietHoursSet) draft.quietHours else null, groupRules = if (draft.groupRulesSet) draft.groupRules else null, memberRules = if (draft.memberRulesSet) draft.memberRules else null, diff --git a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SystemEditViewModel.kt b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SystemEditViewModel.kt index 4211e3b..4ddc6c9 100644 --- a/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SystemEditViewModel.kt +++ b/sheaf/app/src/main/java/systems/lupine/sheaf/ui/settings/SystemEditViewModel.kt @@ -132,6 +132,8 @@ class SystemEditViewModel @Inject constructor( _state.update { it.copy(isSaving = true, error = null, stepUpError = null) } runCatching { api.updateOwnSystem(SystemUpdate( + // The whole profile form, so an empty box really is a clear. + clearsUnsetFields = true, name = f.name.takeIf { it.isNotBlank() }, description = f.description.takeIf { it.isNotBlank() }, // Send empty string as-is so the backend's "empty clears" diff --git a/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/PatchFieldParityTest.kt b/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/PatchFieldParityTest.kt new file mode 100644 index 0000000..f6a3b01 --- /dev/null +++ b/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/PatchFieldParityTest.kt @@ -0,0 +1,125 @@ +package systems.lupine.sheaf.data.api + +import com.squareup.moshi.Json +import systems.lupine.sheaf.data.model.GroupRuleSpec +import systems.lupine.sheaf.data.model.GroupUpdate +import systems.lupine.sheaf.data.model.MemberRuleSpec +import systems.lupine.sheaf.data.model.MemberUpdate +import systems.lupine.sheaf.data.model.NotificationChannelUpdate +import systems.lupine.sheaf.data.model.QuietHoursSpec +import systems.lupine.sheaf.data.model.SystemUpdate +import systems.lupine.sheaf.di.NetworkModule +import kotlin.reflect.KClass +import kotlin.reflect.KParameter +import kotlin.reflect.KType +import kotlin.reflect.full.findAnnotation +import kotlin.reflect.full.memberProperties +import kotlin.reflect.full.primaryConstructor +import kotlin.test.Test +import kotlin.test.assertTrue +import kotlin.test.fail + +/** + * Every field on a hand-written PATCH body reaches the wire. + * + * A hand-written adapter only writes what it lists, so a field added to the + * data class and not to the adapter is dropped in silence. That has already + * happened twice: member ceilings and the step-up credentials were both added + * to the body and not to the adapter, so re-auth never reached the server and + * the guard switches never saved. + * + * The per-body tests next door guard that too, but by a hand-written list of + * names, so they only cover the fields somebody remembered to add to them. A + * new field passes them by construction. This one asks the data class what its + * fields are, so adding one and forgetting the adapter fails here with the + * field's own name in the message. + * + * Mirrors the shape of the server's own importer/exporter parity test, and for + * the same reason: the failure mode is silence. + */ +class PatchFieldParityTest { + + private val moshi = NetworkModule.provideMoshi() + + @Test fun `every member field reaches the wire`() = assertAllFieldsSerialise(MemberUpdate::class) + + @Test fun `every group field reaches the wire`() = assertAllFieldsSerialise(GroupUpdate::class) + + @Test fun `every system field reaches the wire`() = assertAllFieldsSerialise(SystemUpdate::class) + + @Test fun `every channel field reaches the wire`() = + assertAllFieldsSerialise(NotificationChannelUpdate::class) + + /** + * Populate every field, serialise, and insist each one shows up. + * + * Booleans are set true throughout, which also turns on the flags that let + * the clearable fields through ([MemberUpdate.clearsUnsetFields] and + * [NotificationChannelUpdate.quietHoursSet]), so this exercises the widest + * body each adapter can produce. + */ + private fun assertAllFieldsSerialise(klass: KClass) { + val body = klass.primaryConstructor + ?.let { ctor -> ctor.callBy(ctor.parameters.associateWith { sampleFor(it) }) } + ?: fail("${klass.simpleName} has no primary constructor") + + @Suppress("UNCHECKED_CAST") + val json = moshi.adapter(klass.java as Class).toJson(body) + + val missing = wireNames(klass).filterNot { "\"$it\":" in json } + assertTrue( + missing.isEmpty(), + "${klass.simpleName} does not send ${missing.joinToString()}. " + + "Add them to its adapter in PatchJsonAdapters.kt, choosing clears() or " + + "omitsWhenNull() to match the server's _reject_explicit_null list. Got: $json", + ) + } + + /** The JSON names this body is expected to carry, skipping ignored ones. */ + private fun wireNames(klass: KClass<*>): List = + klass.primaryConstructor!!.parameters.mapNotNull { param -> + val annotation = param.jsonAnnotation(klass) + when { + annotation?.ignore == true -> null + annotation != null && annotation.name != Json.UNSET_NAME -> annotation.name + // No @Json means the Kotlin name is the wire name, which holds + // for every one of these bodies (name, description, colour and + // the step-up credentials). + else -> param.name + } + } + + /** + * The `@Json` for a constructor parameter, from the parameter or from the + * property it declares. Which of the two carries it depends on how it was + * written, and both spellings appear in these models. + */ + private fun KParameter.jsonAnnotation(klass: KClass<*>): Json? = + findAnnotation() + ?: klass.memberProperties.firstOrNull { it.name == name }?.findAnnotation() + + private fun sampleFor(param: KParameter): Any = when (param.type.classifierName()) { + "String" -> "x" + "Boolean" -> true + "Int" -> 1 + "Long" -> 1L + "Double" -> 1.0 + "List" -> listForElement(param.type) + "Map" -> mapOf("k" to "v") + "QuietHoursSpec" -> QuietHoursSpec("22:00", "07:00", "UTC") + else -> fail( + "No sample value for ${param.name}: ${param.type}. Add one to sampleFor so this " + + "body stays covered.", + ) + } + + private fun listForElement(type: KType): List = + when (type.arguments.firstOrNull()?.type?.classifierName()) { + "String" -> listOf("x") + "GroupRuleSpec" -> listOf(GroupRuleSpec(groupId = "g", rule = "allow")) + "MemberRuleSpec" -> listOf(MemberRuleSpec(memberId = "m", rule = "allow")) + else -> fail("No sample element for $type. Add one to listForElement.") + } + + private fun KType.classifierName(): String? = (classifier as? KClass<*>)?.simpleName +} diff --git a/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/PatchJsonAdaptersTest.kt b/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/PatchJsonAdaptersTest.kt index 77efc1c..618fc53 100644 --- a/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/PatchJsonAdaptersTest.kt +++ b/sheaf/app/src/test/java/systems/lupine/sheaf/data/api/PatchJsonAdaptersTest.kt @@ -2,6 +2,8 @@ package systems.lupine.sheaf.data.api import systems.lupine.sheaf.data.model.GroupUpdate import systems.lupine.sheaf.data.model.MemberUpdate +import systems.lupine.sheaf.data.model.NotificationChannelUpdate +import systems.lupine.sheaf.data.model.QuietHoursSpec import systems.lupine.sheaf.data.model.SystemUpdate import systems.lupine.sheaf.di.NetworkModule import kotlin.test.Test @@ -30,11 +32,13 @@ class PatchJsonAdaptersTest { private fun member(u: MemberUpdate) = moshi.adapter(MemberUpdate::class.java).toJson(u) private fun group(u: GroupUpdate) = moshi.adapter(GroupUpdate::class.java).toJson(u) private fun system(u: SystemUpdate) = moshi.adapter(SystemUpdate::class.java).toJson(u) + private fun channel(u: NotificationChannelUpdate) = + moshi.adapter(NotificationChannelUpdate::class.java).toJson(u) // ── Member ──────────────────────────────────────────────────────────────── @Test fun `emptying a member's optional fields clears them`() { - val json = member(MemberUpdate(name = "Alex")) + val json = member(MemberUpdate(name = "Alex", clearsUnsetFields = true)) listOf("display_name", "description", "pronouns", "color", "birthday", "note", "emoji") .forEach { assertTrue("\"$it\":null" in json, "$it should clear, got: $json") } } @@ -42,7 +46,7 @@ class PatchJsonAdaptersTest { @Test fun `removing a member's emoji removes it`() { // This one needed an empty string before the adapter existed, because a // dropped null read as "leave it alone" and the old emoji stayed put. - assertTrue("\"emoji\":null" in member(MemberUpdate(name = "Alex", emoji = null))) + assertTrue("\"emoji\":null" in member(MemberUpdate(name = "Alex", emoji = null, clearsUnsetFields = true))) val wolf = "\uD83D\uDC3A" assertTrue("\"emoji\":\"$wolf\"" in member(MemberUpdate(emoji = wolf))) } @@ -62,20 +66,20 @@ class PatchJsonAdaptersTest { @Test fun `clearing an avatar reaches the wire`() { // Removing a picture is a clear, not an omission. - assertTrue("\"avatar_url\":null" in member(MemberUpdate(name = "Alex"))) - assertTrue("\"banner_url\":null" in member(MemberUpdate(name = "Alex"))) + assertTrue("\"avatar_url\":null" in member(MemberUpdate(name = "Alex", clearsUnsetFields = true))) + assertTrue("\"banner_url\":null" in member(MemberUpdate(name = "Alex", clearsUnsetFields = true))) } // ── Group ───────────────────────────────────────────────────────────────── @Test fun `a group's description and colour clear`() { - val json = group(GroupUpdate(name = "G")) + val json = group(GroupUpdate(name = "G", clearsUnsetFields = true)) assertTrue("\"description\":null" in json, json) assertTrue("\"color\":null" in json, json) } @Test fun `clearing a group's parent promotes it to top level`() { - assertTrue("\"parent_id\":null" in group(GroupUpdate(name = "G"))) + assertTrue("\"parent_id\":null" in group(GroupUpdate(name = "G", clearsUnsetFields = true))) } @Test fun `a group's name is omitted when null`() { @@ -85,7 +89,7 @@ class PatchJsonAdaptersTest { // ── System ──────────────────────────────────────────────────────────────── @Test fun `a system's tag, colour and description clear`() { - val json = system(SystemUpdate(name = "S")) + val json = system(SystemUpdate(name = "S", clearsUnsetFields = true)) listOf("description", "tag", "color", "note") .forEach { assertTrue("\"$it\":null" in json, "$it should clear, got: $json") } } @@ -167,7 +171,7 @@ class PatchJsonAdaptersTest { @Test fun `unset ceilings, credentials and privacy are left out`() { // All NOT NULL or step-up only: a null would fail the save or be noise. - listOf(member(MemberUpdate(name = "A")), group(GroupUpdate(name = "G")), system(SystemUpdate(name = "S"))) + listOf(member(MemberUpdate(name = "A")), group(GroupUpdate(name = "G", clearsUnsetFields = true)), system(SystemUpdate(name = "S", clearsUnsetFields = true))) .forEach { json -> listOf("never_shareable", "fronting_private", "privacy", "password", "totp_code") .forEach { assertFalse("\"$it\"" in json, "$it should be omitted: $json") } @@ -175,7 +179,7 @@ class PatchJsonAdaptersTest { } @Test fun `the bodies stay valid JSON objects`() { - listOf(member(MemberUpdate(name = "A")), group(GroupUpdate(name = "G")), system(SystemUpdate(name = "S"))) + listOf(member(MemberUpdate(name = "A")), group(GroupUpdate(name = "G", clearsUnsetFields = true)), system(SystemUpdate(name = "S", clearsUnsetFields = true))) .forEach { assertTrue(it.startsWith("{") && it.endsWith("}"), it) assertEquals(it.count { c -> c == '{' }, it.count { c -> c == '}' }) @@ -206,4 +210,90 @@ class PatchJsonAdaptersTest { val json = system(SystemUpdate(coalesceContiguousFronts = true)) assertFalse("replace_fronts_default" in json, json) } + + // ── A partial body must not clear what it did not send ──────────────────── + + // The other half of the contract, and the one that went wrong in the field. + // `clears` writes a null whether or not the caller populated the field, so a + // screen that sends one setting was destroying the rest of the record. + + @Test fun `toggling a front preference sends only that preference`() { + // Settings, Fronting sends one boolean. It used to arrive alongside six + // nulls, wiping the system's description, tag, colour, note, avatar and + // banner every time either switch was flipped. + val json = system(SystemUpdate(replaceFrontsDefault = true)) + assertEquals("""{"replace_fronts_default":true}""", json) + } + + @Test fun `no clearable field escapes a partial system body`() { + val json = system(SystemUpdate(coalesceContiguousFronts = false)) + listOf("description", "tag", "avatar_url", "banner_url", "color", "note") + .forEach { assertFalse(it in json, "$it must not be sent, got: $json") } + } + + @Test fun `a partial member or group body clears nothing either`() { + // Neither has a partial caller today. Both would be one rename away + // from losing an avatar, a birthday or a parent group. + val member = member(MemberUpdate(name = "Alex")) + assertEquals("""{"name":"Alex"}""", member) + val group = group(GroupUpdate(name = "G")) + assertEquals("""{"name":"G"}""", group) + } + + @Test fun `a partial body still sends the values it does carry`() { + val json = member(MemberUpdate(name = "Alex", pronouns = "they/them")) + assertTrue(""""pronouns":"they/them"""" in json, json) + assertFalse("avatar_url" in json, json) + } + + // ── Notification channel ────────────────────────────────────────────────── + + @Test fun `turning quiet hours off clears them`() { + // The bug this adapter exists for: unticking the box reported success + // and left the window in place, because the null was dropped and the + // server reads presence rather than value. + val json = channel( + NotificationChannelUpdate(quietHoursSet = true, quietHours = null), + ) + assertEquals("""{"quiet_hours":null}""", json) + } + + @Test fun `setting quiet hours sends the window`() { + val json = channel( + NotificationChannelUpdate( + quietHoursSet = true, + quietHours = QuietHoursSpec("22:00", "07:00", "UTC"), + ), + ) + assertTrue(""""start":"22:00"""" in json, json) + assertTrue(""""tz":"UTC"""" in json, json) + } + + @Test fun `editing something else does not touch quiet hours`() { + // Every channel save would otherwise clear the window, since the + // clearing field is written whether or not it was edited. + val json = channel(NotificationChannelUpdate(name = "Phone")) + assertFalse("quiet_hours" in json, json) + } + + @Test fun `a secret or a rule set is never cleared by omission`() { + // These three are absent from the server's _reject_explicit_null list, + // so a null would be accepted rather than refused: sending one would + // wipe a webhook secret or replace every rule with nothing. + val json = channel(NotificationChannelUpdate(quietHoursSet = true, quietHours = null)) + listOf("webhook_secret", "group_rules", "member_rules") + .forEach { assertFalse(it in json, "$it must not be sent, got: $json") } + } + + @Test fun `a channel toggle turned off is sent, not dropped`() { + val json = channel(NotificationChannelUpdate(triggerOnStart = false)) + assertTrue(""""trigger_on_start":false""" in json, json) + } + + @Test fun `a zero debounce is a value, not an absence`() { + // Zero means "deliver each change on its own", which is a real choice + // and the one somebody picks to turn batching off. + val json = channel(NotificationChannelUpdate(debounceSeconds = 0)) + assertTrue(""""debounce_seconds":0""" in json, json) + } }