From 1dff4b7ddbbdbcbe529539d01d11c8f7f773133b Mon Sep 17 00:00:00 2001 From: Bryan Van Deusen Date: Fri, 27 Nov 2026 00:13:48 -0500 Subject: [PATCH] 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 --- .../minstrel/cache/mutations/MutationQueue.kt | 36 +++++++ .../minstrel/likes/data/LikesRepository.kt | 21 +++- .../quarantine/data/QuarantineRepository.kt | 25 ++++- .../likes/data/LikesRepositoryTest.kt | 101 ++++++++++++++++++ 4 files changed, 181 insertions(+), 2 deletions(-) create mode 100644 android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt diff --git a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt index aef499e5..3453248f 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/cache/mutations/MutationQueue.kt @@ -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 = 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 = 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( diff --git a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt index 05adf9cc..ec457985 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/likes/data/LikesRepository.kt @@ -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) = - 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() 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) } diff --git a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt index 23f16631..7f456f47 100644 --- a/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt +++ b/android/app/src/main/java/com/fabledsword/minstrel/quarantine/data/QuarantineRepository.kt @@ -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 diff --git a/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt b/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt new file mode 100644 index 00000000..1a4eb83a --- /dev/null +++ b/android/app/src/test/java/com/fabledsword/minstrel/likes/data/LikesRepositoryTest.kt @@ -0,0 +1,101 @@ +package com.fabledsword.minstrel.likes.data + +import com.fabledsword.minstrel.api.endpoints.LikesApi +import com.fabledsword.minstrel.auth.AuthController +import com.fabledsword.minstrel.cache.db.dao.CachedAlbumDao +import com.fabledsword.minstrel.cache.db.dao.CachedArtistDao +import com.fabledsword.minstrel.cache.db.dao.CachedLikeDao +import com.fabledsword.minstrel.cache.db.dao.CachedTrackDao +import com.fabledsword.minstrel.cache.db.entities.CachedLikeEntity +import com.fabledsword.minstrel.cache.mutations.MutationQueue +import com.fabledsword.minstrel.cache.mutations.likeToggleKey +import com.fabledsword.minstrel.models.UserRef +import com.fabledsword.minstrel.models.wire.LikedIdsWire +import io.mockk.coEvery +import io.mockk.coVerify +import io.mockk.every +import io.mockk.mockk +import io.mockk.slot +import kotlinx.coroutines.CoroutineScope +import kotlinx.coroutines.Dispatchers +import kotlinx.coroutines.SupervisorJob +import kotlinx.coroutines.cancel +import kotlinx.coroutines.flow.MutableStateFlow +import kotlinx.coroutines.test.runTest +import org.junit.jupiter.api.AfterEach +import org.junit.jupiter.api.Test +import retrofit2.Retrofit +import java.io.IOException +import kotlin.test.assertEquals + +/** + * A like or unlike is offline-first, and the user's last action wins: one + * made while an older toggle for the same entity is still queued queues + * behind it, and a refresh keeps what is still queued over the server's + * answer. + */ +class LikesRepositoryTest { + private val scope = CoroutineScope(SupervisorJob() + Dispatchers.Unconfined) + private val api: LikesApi = mockk(relaxed = true) + private val likeDao: CachedLikeDao = mockk(relaxed = true) + private val queue: MutationQueue = mockk(relaxed = true) + private val auth: AuthController = mockk { + every { currentUser } returns MutableStateFlow(UserRef(id = "u1", username = "listener")) + } + private val retrofit: Retrofit = mockk { + every { create(LikesApi::class.java) } returns api + } + private val repo = LikesRepository( + likeDao, mockk(), mockk(), mockk(), + queue, auth, scope, retrofit, + ) + + @AfterEach + fun teardown() = scope.cancel() + + @Test + fun `a toggle with nothing queued goes live`() = runTest { + coEvery { queue.pendingLikeStates() } returns emptyMap() + + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) + + coVerify { api.unlike("tracks", "t1") } + coVerify(exactly = 0) { queue.enqueueLikeToggle(any(), any(), any()) } + } + + @Test + fun `a toggle behind a queued one queues too, so the older one cannot land last`() = runTest { + coEvery { queue.pendingLikeStates() } returns + mapOf(likeToggleKey(LikesRepository.ENTITY_TRACK, "t1") to true) + + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = false) + + coVerify(exactly = 0) { api.unlike(any(), any()) } + coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", false) } + } + + @Test + fun `a toggle that cannot reach the server is queued`() = runTest { + coEvery { queue.pendingLikeStates() } returns emptyMap() + coEvery { api.like(any(), any()) } throws IOException("offline") + + repo.toggleLike(LikesRepository.ENTITY_TRACK, "t1", desiredState = true) + + coVerify { queue.enqueueLikeToggle(LikesRepository.ENTITY_TRACK, "t1", true) } + } + + @Test + fun `refresh keeps the likes and unlikes still queued over the server's list`() = runTest { + coEvery { api.ids() } returns LikedIdsWire(trackIds = listOf("kept", "unliked-here")) + coEvery { queue.pendingLikeStates() } returns mapOf( + likeToggleKey(LikesRepository.ENTITY_TRACK, "unliked-here") to false, + likeToggleKey(LikesRepository.ENTITY_TRACK, "liked-here") to true, + ) + val rows = slot>() + coEvery { likeDao.replaceAllForUser("u1", capture(rows)) } returns Unit + + repo.refreshIds() + + assertEquals(setOf("kept", "liked-here"), rows.captured.map { it.entityId }.toSet()) + } +}