fix(android): a like, unlike, flag or unflag made while an older one is still queued can't be undone by it (#8079)

A toggle went live first and queued only on failure, and the replayer
collapses toggles only among queued rows. So a like queued offline, then an
unlike that reached the server live before the queue drained, ended with
the queued like replaying last: the user's last action lost. A refresh also
replaced the local set with the server's, dropping a queued toggle's state
until it replayed.

- When the queue holds a toggle for the same entity, the new one queues
  behind it (as NormalizationRepository already does); the replayer then
  sends the newest per entity. Quarantine flag and unflag do the same.
- refreshIds and the quarantine refresh keep what is still queued over the
  server's answer (MutationQueue.pendingLikeStates /
  pendingQuarantineStates).

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-27 00:13:48 -05:00
co-authored by Claude Opus 5.5
parent e05673a9f1
commit 1dff4b7ddb
4 changed files with 181 additions and 2 deletions
@@ -181,6 +181,39 @@ class MutationQueue @Inject constructor(
}
.toSet()
/**
* The like state each still-queued like toggle sets, by
* [likeToggleKey], the newest toggle winning. A toggle for an entity
* found here must queue behind it rather than go live, or the older
* one replays after it and undoes it; and a refresh keeps these states
* over the server's, which hasn't seen them yet.
*/
suspend fun pendingLikeStates(): Map<String, Boolean> = buildMap {
dao.getAll().filter { it.kind == MutationKind.LIKE_TOGGLE }.forEach { row ->
runCatching { json.decodeFromString(LikeTogglePayload.serializer(), row.payload) }
.getOrNull()
?.let { put(likeToggleKey(it.entityType, it.entityId), it.desiredState) }
}
}
/**
* Whether each track with a quarantine flag or unflag still queued ends
* up flagged (true) or not, the newest winning. Read for the same two
* reasons as [pendingLikeStates].
*/
suspend fun pendingQuarantineStates(): Map<String, Boolean> = buildMap {
dao.getAll().forEach { row ->
when (row.kind) {
MutationKind.QUARANTINE_FLAG -> runCatching {
json.decodeFromString(QuarantineFlagPayload.serializer(), row.payload)
}.getOrNull()?.let { put(it.trackId, true) }
MutationKind.QUARANTINE_UNFLAG -> runCatching {
json.decodeFromString(QuarantineUnflagPayload.serializer(), row.payload)
}.getOrNull()?.let { put(it.trackId, false) }
}
}
}
suspend fun enqueueQuarantineFlag(
trackId: String,
reason: String,
@@ -258,6 +291,9 @@ class MutationQueue @Inject constructor(
@Serializable
data class QuarantineUnflagPayload(val trackId: String)
/** The key [MutationQueue.pendingLikeStates] files a like toggle under. */
fun likeToggleKey(entityType: String, entityId: String): String = "$entityType:$entityId"
/** Persisted payload for `MutationKind.PLAYLIST_APPEND`: the track IDs to append to one playlist. */
@Serializable
data class PlaylistAppendPayload(
@@ -1,5 +1,6 @@
package com.fabledsword.minstrel.likes.data
import com.fabledsword.minstrel.cache.mutations.likeToggleKey
import com.fabledsword.minstrel.api.endpoints.LikesApi
import com.fabledsword.minstrel.auth.AuthController
import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao
@@ -164,6 +165,13 @@ class LikesRepository @Inject constructor(
} else {
likeDao.delete(uid, entityType, entityId)
}
// An older toggle for this entity is still queued: going live would
// let it replay after this one and undo it. Queue behind it instead;
// the replayer sends only the newest toggle per entity.
if (mutationQueue.pendingLikeStates().containsKey(likeToggleKey(entityType, entityId))) {
mutationQueue.enqueueLikeToggle(entityType, entityId, desiredState)
return false
}
// 2. Best-effort REST call; 3. enqueue on failure.
val kindPath = serverPathFor(entityType)
return try {
@@ -194,17 +202,28 @@ class LikesRepository @Inject constructor(
* The server lists each kind most recently liked first but sends no
* times, so the rows are stamped a millisecond apart in that order;
* `likedAt` then sorts the way the server does.
*
* A like or unlike still queued here wins over the server's answer,
* which hasn't seen it yet: taking the server's would undo it on
* screen until the replay landed.
*/
suspend fun refreshIds() {
val uid = currentUserId()
val wire = api.ids()
val pending = mutationQueue.pendingLikeStates()
val now = Clock.System.now()
fun rowsOf(type: String, ids: List<String>) =
ids.mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) }
ids.filter { pending[likeToggleKey(type, it)] != false }
.mapIndexed { i, id -> CachedLikeEntity(uid, type, id, likedAt = now - i.milliseconds) }
val rows = mutableListOf<CachedLikeEntity>()
rows += rowsOf(ENTITY_ARTIST, wire.artistIds)
rows += rowsOf(ENTITY_ALBUM, wire.albumIds)
rows += rowsOf(ENTITY_TRACK, wire.trackIds)
val listed = rows.mapTo(HashSet()) { likeToggleKey(it.entityType, it.entityId) }
pending.filterValues { it }.keys.filter { it !in listed }.forEach { key ->
val (type, id) = key.split(":", limit = 2)
rows += CachedLikeEntity(uid, type, id, likedAt = now)
}
likeDao.replaceAllForUser(uid, rows)
}
@@ -10,6 +10,7 @@ import com.fabledsword.minstrel.models.TrackRef
import com.fabledsword.minstrel.models.wire.QuarantineMineWire
import com.fabledsword.minstrel.shared.secondsToMillis
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.first
import kotlinx.coroutines.flow.map
import kotlinx.datetime.Clock
import retrofit2.Retrofit
@@ -59,7 +60,19 @@ class QuarantineRepository @Inject constructor(
/** Pull the server snapshot and atomically replace the cached table. */
suspend fun refresh() {
val fresh = api.listMine().map { it.toEntity() }
dao.replaceAll(fresh)
// A flag or unflag still queued wins over the server's list, which
// hasn't seen it yet; a queued flag keeps the row made when it was
// flagged here.
val pending = mutationQueue.pendingQuarantineStates()
if (pending.isEmpty()) {
dao.replaceAll(fresh)
return
}
val kept = fresh.filter { pending[it.trackId] != false }
val listed = kept.mapTo(HashSet()) { it.trackId }
val flaggedHere = dao.observeAll().first()
.filter { pending[it.trackId] == true && it.trackId !in listed }
dao.replaceAll(kept + flaggedHere)
}
/** Server snapshot without touching the cache — used by the TrackActions hidden check. */
@@ -75,6 +88,12 @@ class QuarantineRepository @Inject constructor(
*/
suspend fun flag(track: TrackRef, reason: String, notes: String): FlagOutcome {
dao.upsert(track.toQuarantineEntity(reason, notes))
// An unflag for this track still queued would replay after a live
// flag and undo it: queue behind it instead.
if (mutationQueue.pendingQuarantineStates().containsKey(track.id)) {
mutationQueue.enqueueQuarantineFlag(track.id, reason, notes)
return FlagOutcome.QUEUED
}
return try {
api.flag(FlagRequest(trackId = track.id, reason = reason, notes = notes))
FlagOutcome.ACCEPTED
@@ -88,6 +107,10 @@ class QuarantineRepository @Inject constructor(
suspend fun unflag(trackId: String): UnflagOutcome {
dao.deleteByTrackId(trackId)
if (mutationQueue.pendingQuarantineStates().containsKey(trackId)) {
mutationQueue.enqueueQuarantineUnflag(trackId)
return UnflagOutcome.QUEUED
}
return try {
api.unflag(trackId)
UnflagOutcome.ACCEPTED