Compare commits

...

22 Commits

Author SHA1 Message Date
bvandeusen 29fee5aa37 Merge pull request 'Release v2026.05.14.0 — player polish, CacheFiller, offline mutation queue' (#47) from dev into main 2026-05-15 01:17:44 +00:00
bvandeusen 02336967b4 chore(flutter): bump version to 2026.5.14+5 for v2026.05.14.0
Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 21:17:14 -04:00
bvandeusen 452e29bc59 fix(analyze): restore connectivity_provider import for drain()
Removed in f6ee837 thinking it was unused, but drain() still
reads connectivityProvider.future to gate replay attempts.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 21:01:55 -04:00
bvandeusen f6ee837be6 fix(test): drop eager connectivity listener in MutationReplayer
ref.listen(connectivityProvider, …) at start-time mounted the
StreamProvider immediately, which kicked off checkConnectivity()
with a 2s timeout. In tests that never reach the auth state
(smoke_test cold-launch path), that Timer leaked past widget tree
dispose and tripped the still-pending-timer assertion.

Drop the edge trigger — the 3s initial + 1min periodic + post-
enqueue nudge already cover the drain paths. Worst case on
reconnect is ~60s extra latency before the queue drains, which
is acceptable for an offline-resilience layer.

Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
2026-05-14 20:57:59 -04:00
bvandeusen d27dd69bfc fix(test): cancel one-shot Timers on CacheFiller / MutationReplayer dispose
Smoke test failed: "A Timer is still pending even after the widget
tree was disposed." Both workers fired their initial-delay Timer
via `Timer(duration, _sweep)` and stored only the periodic ticker
in the cancellable field — the one-shot Timer leaked past dispose
and tripped the test framework's invariant check.

Track both as _initialTimer + _intervalTimer; cancel both in
dispose(). Behavior is unchanged in production (ref.onDispose only
fires on process death normally); this is purely a test-harness
fix.
2026-05-14 18:38:38 -04:00
bvandeusen b991fde3fe fix(flutter): drop unnecessary String? casts on nullable map reads 2026-05-14 18:31:57 -04:00
bvandeusen 335940cf23 feat(cache): outbound mutation queue for offline-resilient REST
User intent (likes, hides, playlist adds, Lidarr requests, cancels)
now persists across network loss. Controllers write their optimistic
local state to drift first, then try the REST call; on failure
the call is enqueued in cached_mutations rather than rolled back.
MutationReplayer drains the queue on connectivity transitions and
a 1-minute periodic tick.

**Infrastructure (schema 8):**
* CachedMutations table — id / kind / payload (JSON) / createdAt
  / lastAttemptAt / attempts. Drop-after-5-attempts semantics: a
  permanently-failing mutation eventually drops, and next sync
  reconciles drift to the server's authoritative state.
* MutationQueue.enqueue / pendingCount
* MutationReplayer.start + .drain — start fires from app.dart's
  postFrameCallback alongside SyncController / Prefetcher / etc.
* Kind registry: like.add / like.remove / quarantine.flag /
  quarantine.unflag / playlist.append / request.create /
  request.cancel — each with a Ref+payload handler that re-fires
  the corresponding REST call.

**Wired surfaces:**
* LikesController.toggle — optimistic drift like/unlike stays
  across REST failure; queues the call. Drops the old rollback.
* MyQuarantineController.flag / .unflag — same pattern. Hide/unhide
  visibly persists offline; replays when back online.
* addToPlaylistActionProvider — now does an optimistic
  cached_playlist_tracks write (position = max + 1) so the
  playlist detail screen shows the new track instantly. Queues
  appendTracks on REST failure.
* DiscoverScreen._request — queues request.create on DioException.
  No drift state for the request itself (myRequestsProvider is
  still REST-only) so the row won't show on /requests until replay
  succeeds — acceptable for v1.
* MyRequestsController.cancel — optimistic in-memory remove no
  longer restores on failure; queues request.cancel instead.

**Test update:**
quarantine_provider_test "flag rolls back on server failure"
renamed and rewritten to assert the new offline behavior:
optimistic drift row persists, mutation is enqueued for replay.

**Out of scope (v2):**
* Playlist create / rename / delete (no Flutter UI exposes these yet)
* Lidarr request optimistic local row (would need a cached_requests
  drift table)
* UI "syncing N pending changes" indicator (operator preference:
  silent unless we find a concrete need)
2026-05-14 18:27:05 -04:00
bvandeusen 60085b1368 feat(cache): CacheFiller background metadata sweeper
Periodic worker that walks cached_artists for missing album lists
and cached_albums for missing track lists, then fills them via
/api/artists/:id + /api/albums/:id. Newly-discovered album covers
are pre-warmed into flutter_cache_manager's disk cache too.

Solves the "tap an artist → empty album area → pop in" experience:
artistAlbumsProvider was drift-first but the cache only got
populated when the user navigated TO an artist. SyncController's
/api/library/sync delta doesn't carry per-artist album lists (those
are query-time derived). Now the filler pre-populates them in the
background so the drift hit is real on first tap.

Pacing (intentionally conservative):
* 10-second initial delay so SyncController has time to land its
  first sync — the WHERE NOT EXISTS query has nothing to do until
  cached_artists is populated.
* 5-minute interval thereafter. Once steady state is reached the
  sweep is a cheap drift query + early exit.
* 200ms throttle between per-entity REST requests — never competes
  with active playback.
* 200 entities per sweep cap so a fresh install with thousands of
  artists doesn't tie up the network for one continuous run. Next
  sweep picks up where this one left off (NOT EXISTS naturally
  skips already-filled rows).

Wall time estimate for a 1000-artist library: ~3-4 minutes spread
over multiple sweeps. Single round-trip per artist (new
getArtistDetail API method returns artist + albums in one shot).

Activated from app.dart's postFrameCallback alongside the existing
SyncController / Prefetcher / MetadataPrefetcher / LiveEvents
hooks. Disposed via ref.onDispose when the provider scope tears
down (effectively process death in practice).
2026-05-14 17:34:42 -04:00
bvandeusen fb95a462fb fix(player): align audio + UI on track change, prewarm covers + palette
Four related fixes to the player flow that together remove the
audio↔UI lag on track change:

1. **Prefetcher pre-warms covers + palette for the next N tracks.**
   The existing prefetcher pinned audio files only. When auto-advance
   landed on the next track, the cover bytes were cold → mediaItem
   broadcast with artUri=null → now-playing screen stalled in
   _scheduleSwap awaiting precacheImage of a file that didn't exist
   yet. Each upcoming queue item now also fires
   AlbumCoverCache.getOrFetch (writes bytes to disk so _toMediaItem's
   peekCached returns the path) and AlbumColorCache.getOrExtract
   (memoizes the dominant color). Both fire-and-forget; idempotent
   if already cached.

2. **AlbumColorCache.peekColor sync getter** so the now-playing
   fast-path can read the memoized color without awaiting a Future.

3. **_scheduleSwap fast path** when cover bytes + palette are
   already cached (the common in-queue auto-advance case): commit
   _displayedMedia / _displayedDominant synchronously in setState
   without awaiting. The async preload remains as the slow-path
   fallback for genuine cold cache. This is what closes the gap
   the user reported: "art is loading and metadata hasn't updated
   but the new song is playing."

4. **setQueueFromTracks: build source before broadcasting queue /
   mediaItem.** Previously we broadcast immediately for snappy UI;
   if _buildAudioSource threw, the UI showed the new track while
   the player held the old source. Now: build first, broadcast
   only on success. Source build is sub-100ms on warm cache so the
   tap response cost is imperceptible. _suppressIndexUpdates is set
   around setAudioSources + broadcast so a transient currentIndex
   emission can't cross-broadcast the OLD queue's entry at the NEW
   index.

5. **playbackEventStream error handler skips past failing tracks.**
   Previously errors only logged. The player would go silent on a
   404 / decoder failure but mediaItem stayed on the failed track —
   user saw "now playing X" with no audio. Now seekToNext on error;
   if at queue tail, pause cleanly so PlaybackState reflects idle.
2026-05-14 16:42:19 -04:00
bvandeusen 67bacac84b fix(test): capture cacheFirst stream Future before feeding controller 2026-05-14 15:59:16 -04:00
bvandeusen e59ccba961 revert(player): MediaSession surface back to 5 advertised actions
Pixel Watch 2 stopped showing controls entirely after v2026.05.13.3's
MediaSession expansion. Reverting the additive pieces:

* systemActions back to the original 5 (play / pause / skipPrev /
  skipNext / seek). stop, skipToQueueItem, setShuffleMode,
  setRepeatMode, setRating removed.
* controls list back to skipPrev / play|pause / skipNext (no stop).
* stop() override removed — let BaseAudioHandler default apply
  (probably needs to be a no-op for the MediaSession to stay alive
  through certain lifecycle events that audio_service triggers
  internally; the override was actually halting the session).
* MediaItem.rating no longer set in _toMediaItem. The Android
  MediaSession.setRating() path requires setRatingType(RATING_HEART)
  to actually expose to controllers, and audio_service doesn't
  surface that config knob — broadcasting an unanchored rating
  appears to make Wear OS reject the session entirely.

Kept in place:
* skipToQueueItem override — still needed for QueueScreen's direct
  handler call (not routed through MediaSession actions).
* setRating override + LikeBridge wiring — harmless if never
  invoked, and lights up automatically if we figure out how to
  configure the rating type later.
* AlbumCoverCache.peekCached for sync artUri seed — that part
  worked, and the failure mode would be a missing cover, not a
  rejected session.

Watch should come back to its previous "sometimes works" state from
v2026.05.13.2 (basic controls only). Getting past that needs proper
MediaSession config that audio_service either doesn't expose or
requires platform-channel work.
2026-05-14 15:44:14 -04:00
bvandeusen e38189470b test(cache_first): update test for new yield-after-fetch semantics
The cacheFirst fix in 5511f87 added a yield after fetchAndPopulate
so streams never hang when populate is a no-op for this filter
(the liked-tab spinner-forever bug). Test expectation updated: the
first emission after an empty drift is now the still-empty yield
("we tried, nothing to show yet"), and the simulated drift re-emit
yields the populated rows as the second emission.
2026-05-14 15:41:00 -04:00
bvandeusen 5511f87b4b fix(flutter): cacheFirst no longer hangs on no-match cold fetches
Liked tab loaded into an infinite spinner when the user had likes
in one category but not all three. Root cause: the three liked-tab
providers share one _populateLikeIds function. When the populate
writes track rows, drift watch fires for cached_likes (the table
all three providers watch). The track provider's stream re-emits
with rows.isNotEmpty → yields populated. The album and artist
streams re-emit with rows.isEmpty (user has no album/artist likes),
re-enter cacheFirst's rows-empty branch, fire populate AGAIN, drift
fires again, repeat — never yielding, .isLoading stays true forever,
UI spins.

Generalises beyond the liked case: any cacheFirst with a populate
that writes to a watched table but produces no rows matching this
filter would loop. Fix tracks coldFetchAttempted per subscription
so the first fetch is the only fetch via the rows-empty branch;
subsequent empty emissions yield empty. Also yields current rows
after a successful populate so a true no-op fetchAndPopulate (server
genuinely empty, fresh-install with no library data) doesn't hang
when drift doesn't re-emit for an empty batch.

For populated cases, the order is: spinner → brief empty yield from
the post-populate yield → drift watch re-emits with rows → populated.
UI flashes empty for one frame. Acceptable trade-off for the
no-spin guarantee.

Also matches the timeout pattern: liked providers' isOnline gains
the same 3-second timeout the home/library-list providers already
had, so a stuck connectivity check can't extend the hang.
2026-05-14 15:21:55 -04:00
bvandeusen e5ab471ce1 Merge pull request 'release v2026.05.13.3: full-player seed + MediaSession expansion (Wear)' (#46) from dev into main 2026-05-14 18:19:39 +00:00
bvandeusen 28b0107925 chore(flutter): bump versionCode to 4 for v2026.05.13.3 hotfix 2026-05-14 14:19:11 -04:00
bvandeusen bfad4dddb6 fix(player): call Rating.hasHeart() as method, not getter 2026-05-14 14:07:02 -04:00
bvandeusen d1e276204e feat(player): expand MediaSession surface for Wear + lock-screen + Auto
External media controllers (Android Wear, Auto, Bluetooth dashes,
lock-screen widgets) consume the audio_service MediaSession and
silently no-op on any action that isn't in the handler's
systemActions set. Several handler methods were already implemented
but never advertised, plus stop() defaulted to a no-op — which
matched user reports of "media controller on the watch sometimes
works but doesn't play nice with Minstrel."

This patch lines the advertised surface up with what the handler
actually implements + wires a native heart-rating button.

**Expanded controls + systemActions:**
- Added MediaControl.stop to the expanded controls list.
- systemActions now also enumerates stop, skipToQueueItem (override
  shipped in v2026.05.13.1), setShuffleMode, setRepeatMode, and
  setRating. Without these in the set, Android 13+ drops the
  corresponding callbacks from external surfaces.

**stop() override:** halts _player and dismisses the foreground
notification via super.stop(). Default just flipped processingState
to idle without releasing the audio session — external surfaces
treated that as "paused forever".

**setRating wiring (native heart-button protocol):** new LikeBridge
adapter passes through configure() carrying toggleTrackLike +
isTrackLiked closures over LikesController and likedIdsProvider.
- setRating override flips the like through the bridge and re-emits
  mediaItem so the watch's heart icon updates immediately.
- _toMediaItem populates MediaItem.rating on every track change so
  the right filled/outlined heart shows on track-A → track-B.
- PlayerActions ref.listen on likedIdsProvider calls
  refreshCurrentRating so toggling a like from TrackRow / kebab /
  another device (SSE) also keeps the watch icon in sync.

**artUri seed on first broadcast:** AlbumCoverCache.peekCached
returns the file path synchronously when the cover is already on
disk. _toMediaItem uses this so warm-cache tracks broadcast with
artUri populated from the first frame — external controllers see
the cover immediately instead of waiting for the later async
_loadArtForCurrentItem path. Cold-cache tracks fall through to that
path unchanged.
2026-05-14 13:43:18 -04:00
bvandeusen 2df35e6227 fix(player): seed full-player display state from current mediaItem on mount
Regression from v2026.05.13.2's load-then-swap rewrite. _displayedMedia
only got populated by the ref.listen callback on mediaItem changes,
but ref.listen doesn't fire on initial subscription — it only fires
on transitions after the listener is registered. So opening the full
player while a track was already playing left _displayedMedia null
and the screen rendered "Nothing playing." even though the mini bar
showed a live track.

initState now reads the current mediaItem synchronously and seeds
_displayedMedia immediately (and _displayedDominant from the color
provider's cached value when available). A post-frame
_scheduleSwap(current) runs to ensure the cover bytes are decoded
and dominant color resolved when the user opens the player to a
track whose album hasn't yet been color-extracted in this session.
2026-05-14 13:16:20 -04:00
bvandeusen 573aa4226d Merge pull request 'release v2026.05.13.2: artist covers + load-then-swap player transitions' (#45) from dev into main 2026-05-14 16:31:43 +00:00
bvandeusen 30fc7603d4 chore(flutter): bump versionCode to 3 for v2026.05.13.2 hotfix 2026-05-14 12:31:05 -04:00
bvandeusen 86d67f6fc6 fix(player): preload-then-swap cover transitions on both player surfaces
Previous fixes layered AnimatedSwitcher fades on top of a race: the
audio_handler broadcasts MediaItem twice on every track change
(bare metadata first, then with artUri once AlbumCoverCache resolves)
and the image bytes themselves decode asynchronously after the
widget mounts. The fades just smeared the resulting placeholder
flash without addressing the underlying ordering.

Rewrite the decision process around "load first, then swap":

**Mini player** (rapid change is acceptable per operator preference):
- Drop AnimatedSwitcher entirely
- PlayerBar becomes stateful, holds the most-recent non-null artUri
- Builds the child MediaItem with artUri = currentArtUri ?? _lastArtUri,
  so the previous cover stays visible across the null-artUri gap and
  the new cover snaps in the moment its artUri arrives

**Full player** (operator wants the image fully loaded before any
visible change):
- Introduce _displayedMedia + _displayedDominant state
- ref.listen on mediaItemProvider schedules a preload for each new
  track id (and for the artUri-bearing rebroadcast on the same id)
- _scheduleSwap awaits precacheImage on the file:// artUri AND
  awaits albumColorProvider's future for the dominant color
- Only then setState flips _displayedMedia + _displayedDominant in
  one frame — cover, title, gradient all advance atomically
- Drop the per-element AnimatedSwitcher wrappers; the backdrop
  AnimatedContainer still tweens between successive dominant
  colors so the gradient transition is smooth, not snap

Concurrency: rapid skips drop stale preload completions via
_pendingPreloadId. Decode/color failures fall through to the
previous dominant + the ServerImage/error-builder fallbacks.
2026-05-14 12:07:50 -04:00
bvandeusen 8cb9a8b797 fix(flutter): restore artist coverUrl on drift-cached ArtistRef
Multi-artist surfaces (home Rediscover, Library Artists tab, Liked
Artists carousel) were all rendering the music-notes placeholder
instead of real artist covers. Root cause:

CachedArtist.toRef() returned an ArtistRef with empty coverUrl —
the cache doesn't store the representative album id the server
derives at query time, and the adapter never reconstructed it.
The artist detail screen worked coincidentally because it derives
its header cover from `artist.albums[0].id` directly rather than
the ArtistRef's coverUrl field.

Fix:
* CachedArtistAdapter.toRef() now accepts an optional coverAlbumId
  and reconstructs `/api/albums/<id>/cover` when given. Matches the
  pattern AlbumRef uses (deterministic URL from entity id).
* artistTileProvider, libraryArtistsProvider, and artistProvider
  (single-artist) each LEFT JOIN cached_albums ordered by sort_title.
  First row per artist carries the alphabetically-first album id;
  toRef projects that into the cover URL.
* Multi-artist queries dedup in toResult since the join multiplies
  rows by album count.

Artists with no albums yet in drift come through with empty
coverUrl — UI falls back to the music-notes placeholder, same
behavior as before for that legitimately-coverless state.
2026-05-14 12:01:02 -04:00
25 changed files with 1371 additions and 223 deletions
@@ -54,6 +54,24 @@ class LibraryApi {
return ArtistRef.fromJson(r.data ?? const {});
}
/// GET /api/artists/{id} — full response with the ArtistRef AND the
/// embedded album list, both parsed. Single round-trip variant used
/// by CacheFiller and other callers that want to populate both
/// cached_artists and cached_albums in one shot. The existing
/// getArtist / getArtistAlbums keep working for callers that only
/// need one half — they hit the same URL but the per-id Riverpod
/// caching layer dedupes.
Future<({ArtistRef artist, List<AlbumRef> albums})> getArtistDetail(
String id) async {
final r = await _dio.get<Map<String, dynamic>>('/api/artists/$id');
final body = r.data ?? const <String, dynamic>{};
final artist = ArtistRef.fromJson(body);
final albums = ((body['albums'] as List?) ?? const [])
.map((e) => AlbumRef.fromJson((e as Map).cast<String, dynamic>()))
.toList(growable: false);
return (artist: artist, albums: albums);
}
/// Pulls the "albums" array out of the same ArtistDetail body. Callers
/// that need both the artist and its albums should issue two provider
/// reads (artistProvider + artistAlbumsProvider) — both hit the same
+16
View File
@@ -1,7 +1,9 @@
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'cache/cache_filler.dart';
import 'cache/metadata_prefetcher.dart';
import 'cache/mutation_queue.dart';
import 'cache/prefetcher.dart';
import 'cache/sync_controller.dart';
import 'shared/live_events_dispatcher.dart';
@@ -39,6 +41,20 @@ class _MinstrelAppState extends ConsumerState<MinstrelApp> {
// arrive. Also installs an AppLifecycleState observer for
// resume-time defensive invalidation.
ref.read(liveEventsDispatcherProvider);
// Cache filler: background sweeper that walks cached_artists
// / cached_albums for missing relations and fetches the
// per-entity detail so tapping an artist surfaces albums
// immediately (drift hit, no /api/artists/:id round-trip at
// tap time). First sweep 10s after launch; every 5 minutes
// thereafter. Throttled 200ms between requests so it never
// competes with user activity.
ref.read(cacheFillerProvider);
// Mutation replayer: drains the cached_mutations queue when
// connectivity comes back. Controllers (LikesController,
// MyQuarantineController, the add-to-playlist + request flows)
// enqueue on REST failure so user intent persists across
// network loss instead of getting rolled back.
ref.read(mutationReplayerProvider);
});
}
+12 -1
View File
@@ -17,10 +17,21 @@ import '../models/track.dart';
import 'db.dart';
extension CachedArtistAdapter on CachedArtist {
ArtistRef toRef() => ArtistRef(
/// `coverAlbumId` lets the caller pass a representative album id so
/// the ArtistRef carries a reconstructed `/api/albums/<id>/cover`
/// URL. cached_artists doesn't store this directly — the server
/// derives it from the most-recent album at query time — so drift
/// readers that want the cover URL join cached_albums and pass the
/// first album's id through. Empty string yields empty coverUrl,
/// matching the server's behavior for endpoints that don't carry
/// the lookup (artist detail, search, raw cached_artists row reads).
ArtistRef toRef({String coverAlbumId = ''}) => ArtistRef(
id: id,
name: name,
sortName: sortName,
coverUrl: coverAlbumId.isNotEmpty
? '/api/albums/$coverAlbumId/cover'
: '',
);
}
+235
View File
@@ -0,0 +1,235 @@
// Background metadata sweeper that walks the drift cache for missing
// relations and fills them via /api/artists/:id + /api/albums/:id.
// Cover bytes for newly-filled albums are pre-warmed too so the
// per-tile display path doesn't have to wait on network.
//
// Why this layer on top of SyncController and HydrationQueue:
// - SyncController.sync only ingests entities the server emitted
// into the library_changes delta for this user. For a fresh
// install, that's everything; for an existing user, only recent
// changes. The per-artist album list and per-album track list
// are NOT in those deltas — they're derived at query time.
// - HydrationQueue fills these lazily on tile render. CacheFiller
// fills them proactively on a slow schedule so tapping an artist
// surfaces albums immediately instead of triggering a fresh
// /api/artists/:id at tap time.
//
// Pacing is conservative — 200ms between requests, max 200 entities
// per sweep, 5-minute interval. Designed to never compete with user
// activity. Wall time on a 1000-artist library: ~3-4 minutes spread
// over multiple sweeps.
import 'dart:async';
import 'package:drift/drift.dart' show Variable;
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:flutter_cache_manager/flutter_cache_manager.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../auth/auth_provider.dart'
show serverUrlProvider, sessionTokenProvider;
import '../cache/adapters.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/connectivity_provider.dart';
import '../library/library_providers.dart' show libraryApiProvider;
class CacheFiller {
CacheFiller(this._ref);
final Ref _ref;
Timer? _initialTimer;
Timer? _intervalTimer;
bool _running = false;
bool _disposed = false;
/// Delay between launch and the first sweep. Long enough for
/// SyncController to land its initial /api/library/sync so the
/// CacheFiller's "unfilled relations" query has meaningful work.
static const _initialDelay = Duration(seconds: 10);
/// Cadence between sweeps. Once a sweep finds nothing to do (steady
/// state) the interval becomes a cheap drift query + early exit.
static const _interval = Duration(minutes: 5);
/// Throttle between per-entity REST requests so the filler doesn't
/// saturate the server or compete with user-initiated playback.
static const _requestThrottle = Duration(milliseconds: 200);
/// Per-sweep cap. Without this, a fresh install with thousands of
/// artists would tie up the network for many minutes in one go.
/// The next sweep continues where this one left off (the WHERE
/// NOT EXISTS query naturally skips already-filled rows).
static const _maxIdsPerSweep = 200;
void start() {
_initialTimer = Timer(_initialDelay, _sweep);
_intervalTimer = Timer.periodic(_interval, (_) => _sweep());
}
Future<void> _sweep() async {
if (_disposed || _running) return;
final online = await _ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true);
if (!online) return;
_running = true;
try {
await _fillArtists();
if (_disposed) return;
await _fillAlbums();
} catch (e, st) {
debugPrint('cache_filler: sweep failed: $e\n$st');
} finally {
_running = false;
}
}
/// Find artists with no albums in cache and fetch /api/artists/:id
/// for each (single round-trip yields artist + albums via the new
/// getArtistDetail API method). Newly-discovered album covers
/// land in flutter_cache_manager's disk cache too so the next
/// visit to the artist's albums grid paints from disk.
Future<void> _fillArtists() async {
final db = _ref.read(appDbProvider);
final rows = await db.customSelect(
'''
SELECT a.id FROM cached_artists a
WHERE NOT EXISTS (
SELECT 1 FROM cached_albums b WHERE b.artist_id = a.id
)
LIMIT ?
''',
variables: [Variable.withInt(_maxIdsPerSweep)],
).get();
final ids = rows.map((r) => r.read<String>('id')).toList();
if (ids.isEmpty) return;
final api = await _ref.read(libraryApiProvider.future);
final newAlbumIds = <String>[];
for (final id in ids) {
if (_disposed) return;
try {
final detail = await api.getArtistDetail(id);
await db.transaction(() async {
await db
.into(db.cachedArtists)
.insertOnConflictUpdate(detail.artist.toDrift());
if (detail.albums.isNotEmpty) {
await db.batch((b) {
b.insertAllOnConflictUpdate(
db.cachedAlbums,
detail.albums.map((a) => a.toDrift()).toList(),
);
});
newAlbumIds.addAll(detail.albums.map((a) => a.id));
}
});
} catch (e) {
debugPrint('cache_filler: fillArtist($id) failed: $e');
}
await Future.delayed(_requestThrottle);
}
if (newAlbumIds.isNotEmpty) {
await _prewarmCovers(newAlbumIds);
}
}
/// Find albums with no tracks in cache and fetch /api/albums/:id
/// for each. The bulk response carries the album's track list which
/// we persist into cached_tracks for instant album detail render
/// on the next visit.
Future<void> _fillAlbums() async {
final db = _ref.read(appDbProvider);
final rows = await db.customSelect(
'''
SELECT a.id FROM cached_albums a
WHERE NOT EXISTS (
SELECT 1 FROM cached_tracks t WHERE t.album_id = a.id
)
LIMIT ?
''',
variables: [Variable.withInt(_maxIdsPerSweep)],
).get();
final ids = rows.map((r) => r.read<String>('id')).toList();
if (ids.isEmpty) return;
final api = await _ref.read(libraryApiProvider.future);
for (final id in ids) {
if (_disposed) return;
try {
final result = await api.getAlbum(id);
if (result.tracks.isNotEmpty) {
await db.batch((b) {
b.insertAllOnConflictUpdate(
db.cachedTracks,
result.tracks.map((t) => t.toDrift()).toList(),
);
});
}
} catch (e) {
debugPrint('cache_filler: fillAlbum($id) failed: $e');
}
await Future.delayed(_requestThrottle);
}
}
/// Pre-warm album cover bytes via flutter_cache_manager so the
/// per-tile ServerImage / CachedNetworkImage paints from disk on
/// the user's first visit. Mirrors SyncController's prewarm
/// helper — duplicated here intentionally to keep this file self-
/// contained; a shared helper can come out of #357 follow-up if
/// the duplication grows.
Future<void> _prewarmCovers(List<String> albumIds) async {
final baseUrl = await _ref.read(serverUrlProvider.future);
if (baseUrl == null || baseUrl.isEmpty) return;
final token = await _ref.read(sessionTokenProvider.future);
final headers = (token != null && token.isNotEmpty)
? {'Authorization': 'Bearer $token'}
: <String, String>{};
final base = baseUrl.endsWith('/')
? baseUrl.substring(0, baseUrl.length - 1)
: baseUrl;
final mgr = DefaultCacheManager();
var idx = 0;
Future<void> worker() async {
while (idx < albumIds.length) {
if (_disposed) return;
final i = idx++;
try {
await mgr.downloadFile(
'$base/api/albums/${albumIds[i]}/cover',
authHeaders: headers,
);
} catch (_) {
// Best-effort prewarm — 404 (missing collage) and 401
// (token refresh races) shouldn't abort the rest.
}
}
}
// Concurrency 3 — same as SyncController's prewarm. Covers are
// small enough that more parallelism doesn't help much and
// burns radio.
await Future.wait(List.generate(3, (_) => worker()));
}
void dispose() {
_disposed = true;
_initialTimer?.cancel();
_intervalTimer?.cancel();
}
}
/// Read once at app start (from app.dart's postFrameCallback) to
/// activate the filler. Disposed via ref.onDispose when the provider
/// scope tears down; in practice the scope lives for the app's
/// lifetime so dispose only fires on uninstall / process death.
final cacheFillerProvider = Provider<CacheFiller>((ref) {
final filler = CacheFiller(ref);
ref.onDispose(filler.dispose);
filler.start();
return filler;
});
+29 -2
View File
@@ -48,9 +48,22 @@ Stream<T> cacheFirst<D, T>({
// drift re-emission (otherwise the populate cycles forever).
var revalidated = false;
// Tracks whether we've already tried a cold-cache fetch on this
// subscription. Without this, providers can spin forever in the
// rows-empty branch when fetchAndPopulate writes rows that don't
// match THIS filter — e.g. three liked-tab streams sharing one
// populate: the track populate writes track-typed rows, drift
// watch fires for the cached_likes table, the album stream
// re-emits with rows-empty (no album likes), the rows-empty
// branch re-fires populate, repeats forever. Setting this guard
// makes the first fetch attempt also the last for any given
// subscription.
var coldFetchAttempted = false;
await for (final rows in driftStream) {
if (rows.isNotEmpty) {
yield toResult(rows);
coldFetchAttempted = true;
// Stale-while-revalidate: yield cache immediately, then kick off
// a REST refresh in the background. Drift watch() picks up the
// resulting writes and re-emits via this same stream loop.
@@ -62,11 +75,25 @@ Stream<T> cacheFirst<D, T>({
}
continue;
}
// rows is empty. If we've already attempted a cold fetch and
// drift is still empty for this filter, yield empty so the UI
// shows the no-content state instead of spinning forever.
if (coldFetchAttempted) {
yield toResult(rows);
continue;
}
coldFetchAttempted = true;
if (await isOnline()) {
try {
await fetchAndPopulate();
// The drift watch() stream re-emits with the populated rows on
// the next loop iteration. Don't yield here.
// Yield the current (still-empty) rows so the UI moves past
// loading even if populate was a no-op for this filter
// (server returned nothing matching, or all rows were
// already in drift via sync). If populate DID write rows
// matching this filter, the drift watch's next emission
// yields them via the rows.isNotEmpty branch — UI briefly
// shows empty then populates, instead of spinning.
yield toResult(rows);
} catch (e, st) {
if (tag != null) {
debugPrint('cacheFirst[$tag]: fetchAndPopulate failed: $e\n$st');
+31 -1
View File
@@ -178,6 +178,30 @@ class CachedHomeIndex extends Table {
Set<Column> get primaryKey => {section, position};
}
/// Outbound mutation queue for offline-resilient REST calls. Likes,
/// quarantine flag/unflag, playlist appendTracks, Lidarr request
/// create/cancel all enqueue here on REST failure so the user's
/// intent persists across network loss. MutationReplayer drains on
/// connectivity transitions and a 1-minute periodic tick; entries
/// with attempts >= 5 are skipped (the server treats them as
/// permanent failures and library_changes sync will correct any
/// resulting drift drift on next sync). Schema 8+.
class CachedMutations extends Table {
IntColumn get id => integer().autoIncrement()();
/// Stable kind string (see mutation_queue.dart constants). The
/// replayer looks up the handler in a kind→Function map; unknown
/// kinds are dropped to avoid getting stuck.
TextColumn get kind => text()();
/// JSON-encoded payload — args needed to replay the REST call.
/// Shape depends on kind; see mutation_queue.dart.
TextColumn get payload => text()();
DateTimeColumn get createdAt => dateTime().withDefault(currentDateAndTime)();
/// When the last drain attempt fired against this row. Null until
/// the first attempt. Useful for diagnostic queries.
DateTimeColumn get lastAttemptAt => dateTime().nullable()();
IntColumn get attempts => integer().withDefault(const Constant(0))();
}
/// Caller-scoped quarantine ("hidden") rows. Mirrors the wire shape of
/// /api/quarantine/mine — fully denormalized (track + album + artist
/// fields inline) because the Hidden tab renders straight from this row
@@ -217,12 +241,13 @@ enum CacheSource { manual, autoLiked, autoPlaylist, autoPrefetch, incidental }
CachedQuarantineMine,
CachedHomeIndex,
CachedSystemPlaylistsStatus,
CachedMutations,
])
class AppDb extends _$AppDb {
AppDb([QueryExecutor? e]) : super(e ?? driftDatabase(name: 'minstrel_cache'));
@override
int get schemaVersion => 7;
int get schemaVersion => 8;
@override
MigrationStrategy get migration => MigrationStrategy(
@@ -270,6 +295,11 @@ class AppDb extends _$AppDb {
// populates.
await m.createTable(cachedSystemPlaylistsStatus);
}
if (from < 8) {
// Schema 8: cached_mutations outbound queue. Empty on
// upgrade; populated by controllers when REST calls fail.
await m.createTable(cachedMutations);
}
},
);
}
+296
View File
@@ -0,0 +1,296 @@
// Outbound mutation queue for offline-resilient REST calls.
//
// Controllers (LikesController, MyQuarantineController, the add-to-
// playlist sheet, the Discover request flow, the Requests cancel
// action) write their optimistic local state to drift first and try
// the corresponding REST call. On failure they enqueue here. The
// replayer drains the queue when connectivity comes back; the user's
// intent persists across network loss without rolling back their
// visible action.
//
// Why this is separate from SyncController: sync ingests AUTHORITATIVE
// SERVER state into drift. The mutation queue carries USER INTENT
// outbound to the server. They flow in opposite directions and
// shouldn't be conflated — sync wins on conflict (server is the
// source of truth), and a mutation that fails forever (5 attempts)
// is dropped on the trust that next sync will reconcile drift to
// match the server's actual state.
//
// Drop semantics: 5 attempts then drop. The drop is intentional —
// holding onto a forever-failing mutation just delays sync's
// reconciliation. The user's optimistic drift state will diverge
// from server, and the next library_changes delta corrects it.
import 'dart:async';
import 'dart:convert';
import 'package:dio/dio.dart' show DioException, DioExceptionType;
import 'package:drift/drift.dart';
import 'package:flutter/foundation.dart' show debugPrint;
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/discover.dart';
import '../api/endpoints/likes.dart';
import '../library/library_providers.dart' show dioProvider;
import '../likes/likes_provider.dart' show likesApiProvider;
import '../models/lidarr.dart' show LidarrRequestKind;
import '../playlists/playlists_provider.dart' show playlistsApiProvider;
import '../quarantine/quarantine_provider.dart' show quarantineApiProvider;
import '../requests/requests_provider.dart' show requestsApiProvider;
import 'audio_cache_manager.dart' show appDbProvider;
import 'connectivity_provider.dart';
import 'db.dart';
/// Stable kind constants. Each controller emits one of these via
/// MutationQueue.enqueue; the replayer dispatches by kind.
class MutationKinds {
MutationKinds._();
static const likeAdd = 'like.add';
static const likeRemove = 'like.remove';
static const quarantineFlag = 'quarantine.flag';
static const quarantineUnflag = 'quarantine.unflag';
static const playlistAppend = 'playlist.append';
static const requestCreate = 'request.create';
static const requestCancel = 'request.cancel';
}
class MutationQueue {
MutationQueue(this._ref);
final Ref _ref;
/// Persist a mutation for replay. Caller has already done the
/// optimistic local mutation (drift write, in-memory state update)
/// — this only records the REST call that needs to fire eventually.
Future<void> enqueue(String kind, Map<String, dynamic> payload) async {
final db = _ref.read(appDbProvider);
await db.into(db.cachedMutations).insert(
CachedMutationsCompanion.insert(
kind: kind,
payload: jsonEncode(payload),
),
);
// Nudge the replayer in case we're online right now.
unawaited(_ref.read(mutationReplayerProvider).drain());
}
/// Count of pending mutations (attempts < 5). Diagnostic / future
/// UI surface for a "syncing N pending changes" indicator.
Future<int> pendingCount() async {
final db = _ref.read(appDbProvider);
final rows = await db.customSelect(
'SELECT COUNT(*) AS c FROM cached_mutations WHERE attempts < 5',
).get();
return rows.first.read<int>('c');
}
}
final mutationQueueProvider =
Provider<MutationQueue>((ref) => MutationQueue(ref));
class MutationReplayer {
MutationReplayer(this._ref);
final Ref _ref;
Timer? _initialTimer;
Timer? _intervalTimer;
bool _running = false;
bool _disposed = false;
/// Periodic poll cadence. The connectivity listener catches most
/// transitions; this is the belt-and-suspenders for cases where
/// connectivity_plus misses a state change (e.g. flaky Wi-Fi).
static const _interval = Duration(minutes: 1);
/// Max replay attempts before we drop a mutation. 5 is enough to
/// span a few reconnection cycles without holding onto a forever-
/// broken request. See file header for the drop rationale.
static const _maxAttempts = 5;
void start() {
// Drain shortly after launch in case there are queued mutations
// from a prior session that died offline. 3s lets the auth +
// server-url + dio providers finish their async warmup.
_initialTimer = Timer(const Duration(seconds: 3), drain);
// Periodic ticker is the only reconnect signal. We previously had
// a ref.listen(connectivityProvider, …) edge trigger here, but
// subscribing at start-time eagerly mounted the connectivity
// StreamProvider and leaked its initial-timeout Timer through
// tests that never reach the auth state. The drain() loop itself
// gates on connectivity via the .future read below.
_intervalTimer = Timer.periodic(_interval, (_) => drain());
}
/// Walk the queue oldest-first, replaying each mutation. Stops on
/// any transient network error (we'll retry on the next tick); a
/// permanent error (404 etc.) increments the attempt counter and
/// moves on to the next mutation. This is public so MutationQueue.
/// enqueue can trigger an immediate attempt after writing.
Future<void> drain() async {
if (_disposed || _running) return;
final online = await _ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true);
if (!online) return;
_running = true;
try {
while (!_disposed) {
final db = _ref.read(appDbProvider);
final next = await (db.select(db.cachedMutations)
..where((t) => t.attempts.isSmallerThanValue(_maxAttempts))
..orderBy([(t) => OrderingTerm.asc(t.createdAt)])
..limit(1))
.getSingleOrNull();
if (next == null) break;
final handler = _handlers[next.kind];
if (handler == null) {
debugPrint('mutation_replayer: unknown kind ${next.kind}, dropping');
await (db.delete(db.cachedMutations)
..where((t) => t.id.equals(next.id)))
.go();
continue;
}
Map<String, dynamic> payload;
try {
payload = jsonDecode(next.payload) as Map<String, dynamic>;
} catch (e) {
debugPrint('mutation_replayer: bad payload for ${next.kind}: $e');
await (db.delete(db.cachedMutations)
..where((t) => t.id.equals(next.id)))
.go();
continue;
}
try {
await handler(_ref, payload);
await (db.delete(db.cachedMutations)
..where((t) => t.id.equals(next.id)))
.go();
} on DioException catch (e) {
await (db.update(db.cachedMutations)
..where((t) => t.id.equals(next.id)))
.write(CachedMutationsCompanion(
attempts: Value(next.attempts + 1),
lastAttemptAt: Value(DateTime.now()),
));
if (_isTransient(e)) {
// Network is flaky again — bail and try the whole queue
// later. The current mutation will be retried next tick.
break;
}
// Permanent failure (4xx/5xx with a real response). Leave
// the row with bumped attempts and move on to the next so
// one bad mutation doesn't block the others.
} catch (e, st) {
debugPrint('mutation_replayer: unexpected error: $e\n$st');
await (db.update(db.cachedMutations)
..where((t) => t.id.equals(next.id)))
.write(CachedMutationsCompanion(
attempts: Value(next.attempts + 1),
lastAttemptAt: Value(DateTime.now()),
));
}
}
} finally {
_running = false;
}
}
bool _isTransient(DioException e) {
switch (e.type) {
case DioExceptionType.connectionError:
case DioExceptionType.connectionTimeout:
case DioExceptionType.sendTimeout:
case DioExceptionType.receiveTimeout:
return true;
default:
return false;
}
}
void dispose() {
_disposed = true;
_initialTimer?.cancel();
_intervalTimer?.cancel();
}
}
final mutationReplayerProvider = Provider<MutationReplayer>((ref) {
final r = MutationReplayer(ref);
ref.onDispose(r.dispose);
r.start();
return r;
});
/// Type signature for kind-specific replay handlers.
typedef _Handler = Future<void> Function(Ref, Map<String, dynamic>);
/// Kind → handler dispatch. Each handler decodes its payload and
/// re-fires the original REST call. Throws on failure (caught by the
/// replayer's drain loop above).
///
/// Payload shapes (see also enqueue call sites for the writer side):
/// * like.add / like.remove: {'kind': 'track'|'album'|'artist', 'id': uuid}
/// * quarantine.flag: {'trackId': uuid, 'reason': str, 'notes': str}
/// * quarantine.unflag: {'trackId': uuid}
/// * playlist.append: {'playlistId': uuid, 'trackIds': [uuid, …]}
/// * request.create: {full createRequest args; see DiscoverApi}
/// * request.cancel: {'id': uuid}
final Map<String, _Handler> _handlers = {
MutationKinds.likeAdd: (ref, p) async {
final api = await ref.read(likesApiProvider.future);
await api.like(_likeKindFromString(p['kind'] as String), p['id'] as String);
},
MutationKinds.likeRemove: (ref, p) async {
final api = await ref.read(likesApiProvider.future);
await api.unlike(
_likeKindFromString(p['kind'] as String), p['id'] as String);
},
MutationKinds.quarantineFlag: (ref, p) async {
final api = await ref.read(quarantineApiProvider.future);
await api.flag(
p['trackId'] as String,
p['reason'] as String,
notes: (p['notes'] as String?) ?? '',
);
},
MutationKinds.quarantineUnflag: (ref, p) async {
final api = await ref.read(quarantineApiProvider.future);
await api.unflag(p['trackId'] as String);
},
MutationKinds.playlistAppend: (ref, p) async {
final api = await ref.read(playlistsApiProvider.future);
final ids = (p['trackIds'] as List).cast<String>();
await api.appendTracks(p['playlistId'] as String, ids);
},
MutationKinds.requestCreate: (ref, p) async {
final dio = await ref.read(dioProvider.future);
final api = DiscoverApi(dio);
await api.createRequest(
kind: _lidarrKindFromString(p['kind'] as String),
artistMbid: p['artistMbid'] as String,
artistName: p['artistName'] as String,
albumMbid: p['albumMbid'] as String?,
albumTitle: p['albumTitle'] as String?,
trackMbid: p['trackMbid'] as String?,
trackTitle: p['trackTitle'] as String?,
);
},
MutationKinds.requestCancel: (ref, p) async {
final api = await ref.read(requestsApiProvider.future);
await api.cancel(p['id'] as String);
},
};
LikeKind _likeKindFromString(String s) => switch (s) {
'album' => LikeKind.album,
'artist' => LikeKind.artist,
_ => LikeKind.track,
};
LidarrRequestKind _lidarrKindFromString(String s) => switch (s) {
'album' => LidarrRequestKind.album,
'track' => LidarrRequestKind.track,
_ => LidarrRequestKind.artist,
};
+43 -6
View File
@@ -1,6 +1,9 @@
import 'dart:async';
import 'package:audio_service/audio_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../player/album_color_extractor.dart';
import '../player/player_provider.dart';
import 'audio_cache_manager.dart';
import 'cache_settings_provider.dart';
@@ -39,14 +42,48 @@ class Prefetcher {
(currentIdx + settings.prefetchWindow).clamp(0, queue.length - 1);
final mgr = _ref.read(audioCacheManagerProvider);
final coverCache = _ref.read(albumCoverCacheProvider);
final colorCache = _ref.read(albumColorCacheProvider);
// Walk the window. For each upcoming track we want THREE things
// ready when the player transitions into it:
//
// 1. Audio file on disk (otherwise playback stalls on stream
// load — the original prefetcher concern).
// 2. Cover bytes on disk under AlbumCoverCache (otherwise
// _toMediaItem's peekCached returns null, mediaItem
// broadcasts with artUri=null, and the now-playing screen
// stalls in _scheduleSwap awaiting precacheImage of a file
// that doesn't exist yet).
// 3. Palette color extracted and memoized in AlbumColorCache
// (otherwise the gradient backdrop has to wait for
// PaletteGenerator to run after the cover lands —
// visible as the cover snapping in before the gradient).
//
// Each call is idempotent (cache-aware): if already cached, it's
// a no-op. Everything fire-and-forget so the reconcile completes
// quickly even on a fresh queue.
for (var i = currentIdx; i <= endIdx; i++) {
final trackId = queue[i].id;
if (await mgr.isCached(trackId)) continue;
// Fire-and-forget; downloads happen in the background. Errors
// inside pin() are caught + cleaned up internally.
// ignore: unawaited_futures
mgr.pin(trackId, source: CacheSource.autoPrefetch);
final media = queue[i];
final trackId = media.id;
final albumId = media.extras?['album_id'] as String?;
if (!await mgr.isCached(trackId)) {
// ignore: unawaited_futures
mgr.pin(trackId, source: CacheSource.autoPrefetch);
}
if (albumId != null && albumId.isNotEmpty) {
// Cover bytes: getOrFetch returns the file path; the side
// effect (writing to disk) is what we care about.
// ignore: unawaited_futures
coverCache.getOrFetch(albumId);
// Palette: getOrExtract chains off coverCache.getOrFetch so
// it'll wait for the cover before sampling — safe to call
// in parallel here.
// ignore: unawaited_futures
colorCache.getOrExtract(albumId);
}
}
// Eviction pass after pinning new files.
+19 -2
View File
@@ -18,6 +18,7 @@
// subscriptions; drift handles this fine in practice but worth
// measuring if a future surface scales to hundreds.
import 'package:drift/drift.dart' as drift show OrderingTerm;
import 'package:drift/drift.dart' show leftOuterJoin;
import 'package:flutter_riverpod/flutter_riverpod.dart';
@@ -63,6 +64,12 @@ final albumTileProvider =
/// Watches the cached_artists row for [id]. Triggers background
/// hydration on miss; yields the row once it lands.
///
/// LEFT JOIN cached_albums ordered by sort_title so the first row per
/// artist carries a representative album id; toRef() reconstructs
/// `/api/albums/<id>/cover` from it. Without this join the ArtistRef
/// has an empty coverUrl and tiles fall back to the music-notes
/// placeholder even though the server has the cover available.
final artistTileProvider =
StreamProvider.family<ArtistRef?, String>((ref, id) async* {
if (id.isEmpty) {
@@ -70,7 +77,12 @@ final artistTileProvider =
return;
}
final db = ref.watch(appDbProvider);
final query = db.select(db.cachedArtists)..where((t) => t.id.equals(id));
final query = (db.select(db.cachedArtists)..where((t) => t.id.equals(id)))
.join([
leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.artistId.equalsExp(db.cachedArtists.id)),
])
..orderBy([drift.OrderingTerm.asc(db.cachedAlbums.sortTitle)]);
var enqueued = false;
await for (final rows in query.watch()) {
if (rows.isEmpty) {
@@ -83,7 +95,12 @@ final artistTileProvider =
yield null;
continue;
}
yield rows.first.toRef();
// First row has the alphabetically-first album (or null if artist
// has no albums in drift yet — yields a coverless ArtistRef which
// the UI falls back to the placeholder icon for).
final artist = rows.first.readTable(db.cachedArtists);
final firstAlbum = rows.first.readTableOrNull(db.cachedAlbums);
yield artist.toRef(coverAlbumId: firstAlbum?.id ?? '');
}
});
@@ -6,6 +6,7 @@ import 'package:go_router/go_router.dart';
import '../api/endpoints/discover.dart';
import '../api/errors.dart';
import '../cache/mutation_queue.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/lidarr.dart';
import '../shared/widgets/main_app_bar_actions.dart';
@@ -48,14 +49,23 @@ class _DiscoverScreenState extends ConsumerState<DiscoverScreen> {
Future<void> _request(LidarrSearchResult row) async {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final args = {
'kind': _kind.wire,
'artistMbid':
_kind == LidarrRequestKind.artist ? row.mbid : row.artistMbid,
'artistName':
_kind == LidarrRequestKind.artist ? row.name : row.secondaryText,
'albumMbid': _kind == LidarrRequestKind.album ? row.mbid : null,
'albumTitle': _kind == LidarrRequestKind.album ? row.name : null,
};
try {
final api = await ref.read(_discoverApiProvider.future);
await api.createRequest(
kind: _kind,
artistMbid: _kind == LidarrRequestKind.artist ? row.mbid : row.artistMbid,
artistName: _kind == LidarrRequestKind.artist ? row.name : row.secondaryText,
albumMbid: _kind == LidarrRequestKind.album ? row.mbid : null,
albumTitle: _kind == LidarrRequestKind.album ? row.name : null,
artistMbid: args['artistMbid'] as String,
artistName: args['artistName'] as String,
albumMbid: args['albumMbid'],
albumTitle: args['albumTitle'],
);
if (mounted) {
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
@@ -65,12 +75,18 @@ class _DiscoverScreenState extends ConsumerState<DiscoverScreen> {
// Re-run search to refresh the `requested` flag on the row.
_runSearch();
}
} on DioException catch (e) {
} on DioException catch (_) {
// Queue for replay so the user's request persists across
// network loss. We don't have a drift table for in-flight
// requests yet, so the row won't show on the Requests screen
// until replay succeeds — accept that for v1.
await ref
.read(mutationQueueProvider)
.enqueue(MutationKinds.requestCreate, args);
if (mounted) {
final code = ApiError.fromDio(e).code;
ScaffoldMessenger.of(context).showSnackBar(SnackBar(
content: Text('Request failed: $code'),
backgroundColor: fs.error,
content: Text('Request queued: ${row.name}'),
backgroundColor: fs.iron,
));
}
}
@@ -233,17 +233,28 @@ Map<String, dynamic> _trackToJson(TrackRef t) => {
final artistProvider =
StreamProvider.family<ArtistRef, String>((ref, id) {
final db = ref.watch(appDbProvider);
return cacheFirst<CachedArtist, ArtistRef>(
driftStream: (db.select(db.cachedArtists)..where((t) => t.id.equals(id)))
.watch(),
// LEFT JOIN cached_albums for cover-URL reconstruction (see
// CachedArtistAdapter.toRef). First row carries the alphabetically-
// first album.
final query = (db.select(db.cachedArtists)..where((t) => t.id.equals(id)))
.join([
drift.leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.artistId.equalsExp(db.cachedArtists.id)),
])
..orderBy([drift.OrderingTerm.asc(db.cachedAlbums.sortTitle)]);
return cacheFirst<drift.TypedResult, ArtistRef>(
driftStream: query.watch(),
fetchAndPopulate: () async {
final api = await ref.read(libraryApiProvider.future);
final fresh = await api.getArtist(id);
await db.into(db.cachedArtists).insertOnConflictUpdate(fresh.toDrift());
},
toResult: (rows) => rows.isEmpty
? const ArtistRef(id: '', name: '')
: rows.first.toRef(),
toResult: (rows) {
if (rows.isEmpty) return const ArtistRef(id: '', name: '');
final artist = rows.first.readTable(db.cachedArtists);
final firstAlbum = rows.first.readTableOrNull(db.cachedAlbums);
return artist.toRef(coverAlbumId: firstAlbum?.id ?? '');
},
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
+39 -7
View File
@@ -62,9 +62,19 @@ final _meApiProvider = FutureProvider<MeApi>((ref) async {
/// via /api/library/sync.
final _libraryArtistsProvider = StreamProvider<List<ArtistRef>>((ref) {
final db = ref.watch(appDbProvider);
final query = db.select(db.cachedArtists)
..orderBy([(t) => drift.OrderingTerm.asc(t.sortName)]);
return cacheFirst<CachedArtist, List<ArtistRef>>(
// LEFT JOIN cached_albums so each artist row carries a representative
// album id for cover-URL reconstruction. Sorted by artist sortName
// then album sortTitle: the first row per artist gets the
// alphabetically-first album. Dedup happens in toResult.
final query = db.select(db.cachedArtists).join([
drift.leftOuterJoin(db.cachedAlbums,
db.cachedAlbums.artistId.equalsExp(db.cachedArtists.id)),
])
..orderBy([
drift.OrderingTerm.asc(db.cachedArtists.sortName),
drift.OrderingTerm.asc(db.cachedAlbums.sortTitle),
]);
return cacheFirst<drift.TypedResult, List<ArtistRef>>(
driftStream: query.watch(),
fetchAndPopulate: () async {
// Cold-cache fallback: sync should have populated drift already,
@@ -80,7 +90,23 @@ final _libraryArtistsProvider = StreamProvider<List<ArtistRef>>((ref) {
);
});
},
toResult: (rows) => rows.map((r) => r.toRef()).toList(),
toResult: (rows) {
// The join multiplies rows by album count; dedup by artist id
// keeping the first occurrence so we get one ArtistRef per
// artist with the alphabetically-first album's id for the
// cover-URL projection. Artists with no albums in drift yet
// come through as a single row with null cachedAlbums and an
// empty coverUrl — UI falls back to the placeholder icon.
final seen = <String>{};
final out = <ArtistRef>[];
for (final r in rows) {
final a = r.readTable(db.cachedArtists);
if (!seen.add(a.id)) continue;
final album = r.readTableOrNull(db.cachedAlbums);
out.add(a.toRef(coverAlbumId: album?.id ?? ''));
}
return out;
},
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
@@ -216,7 +242,9 @@ final _likedTrackIdsProvider = StreamProvider<List<String>>((ref) {
driftStream: query,
fetchAndPopulate: () => _populateLikeIds(ref),
toResult: _idsForEntity,
isOnline: () async => (await ref.read(connectivityProvider.future)),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
alwaysRefresh: true,
tag: 'likedTrackIds',
);
@@ -232,7 +260,9 @@ final _likedAlbumIdsProvider = StreamProvider<List<String>>((ref) {
driftStream: query,
fetchAndPopulate: () => _populateLikeIds(ref),
toResult: _idsForEntity,
isOnline: () async => (await ref.read(connectivityProvider.future)),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
alwaysRefresh: true,
tag: 'likedAlbumIds',
);
@@ -248,7 +278,9 @@ final _likedArtistIdsProvider = StreamProvider<List<String>>((ref) {
driftStream: query,
fetchAndPopulate: () => _populateLikeIds(ref),
toResult: _idsForEntity,
isOnline: () async => (await ref.read(connectivityProvider.future)),
isOnline: () async => (await ref
.read(connectivityProvider.future)
.timeout(const Duration(seconds: 3), onTimeout: () => true)),
alwaysRefresh: true,
tag: 'likedArtistIds',
);
+13 -20
View File
@@ -7,6 +7,7 @@ import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/cache_first.dart';
import '../cache/connectivity_provider.dart';
import '../cache/db.dart';
import '../cache/mutation_queue.dart';
import '../library/library_providers.dart';
final likesApiProvider = FutureProvider<LikesApi>((ref) async {
@@ -147,26 +148,18 @@ class LikesController {
} else {
await api.like(kind, id);
}
} catch (e, st) {
// Rollback drift
if (wasLiked) {
await db.into(db.cachedLikes).insert(
CachedLikesCompanion.insert(
userId: user.id,
entityType: entityType,
entityId: id,
),
mode: drift.InsertMode.insertOrIgnore,
);
} else {
await (db.delete(db.cachedLikes)
..where((t) =>
t.userId.equals(user.id) &
t.entityType.equals(entityType) &
t.entityId.equals(id)))
.go();
}
Error.throwWithStackTrace(e, st);
} catch (_) {
// REST failed (network or HTTP). Don't roll back drift — the
// user's intent is to like/unlike, and we want that visible to
// them even when offline. Queue the call for replay; the
// MutationReplayer will retry on next connectivity transition.
// If retries exhaust (5 attempts), the row drops and the next
// SyncController.sync brings drift back in line with the
// server's authoritative state.
await _ref.read(mutationQueueProvider).enqueue(
wasLiked ? MutationKinds.likeRemove : MutationKinds.likeAdd,
{'kind': entityType, 'id': id},
);
}
}
@@ -39,6 +39,15 @@ class AlbumColorCache {
return color;
}
/// Synchronous peek. Returns the previously-extracted color if this
/// album has been resolved this process; otherwise null. Used by
/// the now-playing fast-path swap so a warm cache transitions the
/// gradient in lockstep with the audio, instead of awaiting the
/// async [getOrExtract] future. A null return means "either no
/// extraction yet or extraction returned null" — caller falls back
/// to the async path.
Color? peekColor(String albumId) => _cache[albumId];
Future<Color?> _extract(String albumId) async {
try {
final coverCache = _ref.read(albumCoverCacheProvider);
@@ -27,6 +27,32 @@ class AlbumCoverCache {
/// same album dedupe to one fetch.
final Map<String, Future<String?>> _inflight = {};
/// Cached covers directory path resolved once on the first
/// async cacheDir call, then reused for sync existsSync() checks
/// in [peekCached]. Without this every "is the cover already on
/// disk?" check would have to await path_provider, blocking the
/// MediaItem broadcast on every track change.
String? _coversDirPath;
/// Returns the local file path for [albumId]'s cover if it's
/// already cached on disk, or null otherwise. Synchronous — uses
/// File.existsSync() against a path computed from the directory
/// resolved by an earlier async [getOrFetch] call. Returns null
/// until at least one getOrFetch has populated _coversDirPath.
///
/// The audio handler uses this to seed MediaItem.artUri on the
/// initial broadcast so external media controllers (Wear, Android
/// Auto, Bluetooth) see the cover on the first frame for warm-cache
/// tracks. Cold-cache tracks still fall back to the async
/// _loadArtForCurrentItem path.
String? peekCached(String albumId) {
if (albumId.isEmpty) return null;
final dir = _coversDirPath;
if (dir == null) return null;
final path = '$dir/$albumId.jpg';
return File(path).existsSync() ? path : null;
}
/// Returns local file path to the album cover, or null on any
/// failure (network, 4xx/5xx, disk full, empty albumId).
Future<String?> getOrFetch(String albumId) {
@@ -44,6 +70,9 @@ class AlbumCoverCache {
final dir = await _cacheDirFactory();
final coversDir = Directory('${dir.path}/album_covers');
await coversDir.create(recursive: true);
// Cache the resolved directory so [peekCached] can do its
// existsSync() check without re-awaiting path_provider.
_coversDirPath = coversDir.path;
final filePath = '${coversDir.path}/$albumId.jpg';
final file = File(filePath);
if (await file.exists()) return filePath;
+173 -18
View File
@@ -15,11 +15,16 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
_player.playbackEventStream.listen(
_broadcastState,
// ExoPlayer surfaces stream errors (404, premature EOS, decoder
// failure, network drop) here. Without an error sink, the
// player just goes quiet — exactly the "starts then stops"
// symptom we hit.
// failure, network drop) here. Logging alone leaves the UI
// claiming "now playing X" while audio is silent — the user-
// observable mismatch between visual and audio state. Skip
// forward so the queue advances past the failed track and
// mediaItem updates to whatever's actually playing. If the
// failure is at the queue tail, just_audio will go idle on its
// own and _broadcastState reflects that.
onError: (Object e, StackTrace st) {
debugPrint('audio_handler: playbackEventStream error: $e\n$st');
unawaited(_handlePlaybackError());
},
);
_player.currentIndexStream.listen(_onCurrentIndexChanged);
@@ -40,6 +45,7 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
String? _token;
AlbumCoverCache? _coverCache;
AudioCacheManager? _audioCacheManager;
LikeBridge? _likeBridge;
/// Trackers to dedupe registration — once we've inserted an index row
/// for a trackId, don't repeat the work on every buffered-position
@@ -94,10 +100,12 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
required String? token,
AlbumCoverCache? coverCache,
AudioCacheManager? audioCacheManager,
LikeBridge? likeBridge,
}) {
_baseUrl = baseUrl;
_token = token;
if (coverCache != null) _coverCache = coverCache;
if (likeBridge != null) _likeBridge = likeBridge;
if (audioCacheManager != null) _audioCacheManager = audioCacheManager;
}
@@ -110,9 +118,6 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
// check and stop calling player mutations — important so a stale
// fill doesn't append old-playlist tracks into the new queue.
final myGen = ++_queueGeneration;
// Reset suppress flag in case a prior backward-fill bailed on
// gen check before reaching its `finally`.
_suppressIndexUpdates = false;
_lastTracks = tracks;
// Pause the old source immediately so the previous track stops
@@ -124,25 +129,49 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
await _player.pause();
}
// Populate the visible queue + current mediaItem immediately so
// the player UI reflects the user's tap before any source has
// been built. Source list at the just_audio layer fills in
// asynchronously below.
// Build MediaItems up front (pure — no side effects); we'll
// broadcast queue/mediaItem only AFTER setAudioSources resolves
// so the audio engine and the UI flip together. If the build
// throws, the UI stays on the previous track (correct: audio
// also stays on the previous track since setAudioSources never
// ran).
final items = tracks.map(_toMediaItem).toList();
queue.add(items);
mediaItem.add(items[clampedInitial]);
// Fast path: build only the initial source so the player can
// start. Remaining sources stream in via _fillRemainingSources()
// in the background — addAudioSource for next/auto-advance
// tracks, insertAudioSource for skipPrev tracks.
final initial = await _buildAudioSource(tracks[clampedInitial]);
// Build only the initial source for fast start. Remaining
// sources stream in via _fillRemainingSources() — addAudioSource
// for next/auto-advance tracks, insertAudioSource for skipPrev.
final AudioSource initial;
try {
initial = await _buildAudioSource(tracks[clampedInitial]);
} catch (e, st) {
// Source build failed (bad URL, missing baseUrl, etc.). Don't
// broadcast the new state — leaving queue/mediaItem on the
// previous track keeps UI in sync with what the player is
// actually doing (which is "still on the previous track,
// paused").
debugPrint('audio_handler: _buildAudioSource failed: $e\n$st');
return;
}
if (myGen != _queueGeneration) {
debugPrint('audio_handler: superseded before setAudioSources (gen=$myGen)');
return;
}
await _player.setAudioSources([initial], initialIndex: 0);
// Suppress _onCurrentIndexChanged side effects while the source
// list is being swapped — without this, a transient currentIndex
// emission during setAudioSources could broadcast the OLD queue's
// entry at the NEW index. Re-enabled after the broadcasts land.
_suppressIndexUpdates = true;
try {
await _player.setAudioSources([initial], initialIndex: 0);
// Broadcast in this order: queue first (so any consumer that
// reacts to mediaItem and reads queue.value sees the consistent
// pair), then mediaItem.
queue.add(items);
mediaItem.add(items[clampedInitial]);
} finally {
_suppressIndexUpdates = false;
}
unawaited(_loadArtForCurrentItem());
unawaited(_fillRemainingSources(tracks, clampedInitial, myGen));
@@ -301,12 +330,32 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
final extras = <String, dynamic>{};
if (t.albumId.isNotEmpty) extras['album_id'] = t.albumId;
if (t.artistId.isNotEmpty) extras['artist_id'] = t.artistId;
// Sync-peek the album cover cache so warm-cache tracks broadcast
// with artUri populated on the first frame. External media
// controllers (Android Wear, Bluetooth dashes, Auto, lock screen)
// can only render the cover bytes that audio_service hands them
// at MediaItem broadcast time; the later async _loadArtForCurrent
// Item path repopulates for cold-cache tracks. Without this seed,
// every track change starts with a generic icon on the watch and
// only gets the real cover after one or two seconds.
final coverPath = (t.albumId.isNotEmpty && _coverCache != null)
? _coverCache!.peekCached(t.albumId)
: null;
// MediaItem.rating intentionally NOT set: audio_service propagates
// it to MediaSession.setRating(), but the Android session also
// needs setRatingType(RATING_HEART) configured to expose that to
// controllers — audio_service doesn't surface that config knob,
// and broadcasting an unanchored rating made Wear OS reject the
// session entirely. The LikeBridge wiring stays in place so
// setRating can still fire from any surface that DOES route it,
// we just don't advertise it.
return MediaItem(
id: t.id,
title: t.title,
artist: t.artistName,
album: t.albumTitle,
duration: Duration(seconds: t.durationSec),
artUri: coverPath != null ? Uri.file(coverPath) : null,
extras: extras.isEmpty ? null : extras,
);
}
@@ -342,6 +391,37 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
await mgr.registerStreamCache(trackId, path, size);
}
/// Called when playbackEventStream emits an error. Skips past the
/// failing track so the UI and audio re-converge — without this,
/// _player goes silent on a 404 / decoder failure / EOS but
/// mediaItem stays on the failed track and the user sees a "now
/// playing" header for something that isn't.
///
/// If we're at the last track, seekToNext is a no-op; the state
/// drops to idle and _broadcastState reflects that.
Future<void> _handlePlaybackError() async {
final currentIdx = _player.currentIndex;
final queueLen = queue.value.length;
if (currentIdx == null || currentIdx + 1 >= queueLen) {
// Last track or no queue context — just pause; _broadcastState
// already reflects the idle/error processingState.
try {
await _player.pause();
} catch (_) {}
return;
}
try {
await _player.seekToNext();
} catch (_) {
// If seekToNext fails too (next source not built yet, etc.),
// there's nothing safe to do — pause and let the user recover
// manually.
try {
await _player.pause();
} catch (_) {}
}
}
void _onCurrentIndexChanged(int? idx) {
if (idx == null) return;
if (_suppressIndexUpdates) return;
@@ -391,6 +471,45 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
@override
Future<void> skipToPrevious() => _player.seekToPrevious();
/// Heart rating from external surfaces (Wear's favorite button,
/// lock-screen like) → LikesController.toggle(track). We only
/// route through the bridge when the rating actually flips relative
/// to the current state, so repeated taps from a flaky controller
/// don't ping-pong the like.
@override
Future<void> setRating(Rating rating, [Map<String, dynamic>? extras]) async {
final media = mediaItem.value;
final bridge = _likeBridge;
if (media == null || bridge == null) return;
final currentlyLiked = bridge.isTrackLiked(media.id);
final wantLiked = rating.hasHeart();
if (currentlyLiked == wantLiked) return;
try {
await bridge.toggleTrackLike(media.id);
} catch (_) {
// LikesController already rolls back on REST failure; nothing
// to do here beyond letting the broadcast skip.
return;
}
// Re-emit so the watch's heart icon updates immediately.
mediaItem.add(media.copyWith(rating: Rating.newHeartRating(wantLiked)));
}
/// Re-emits the current mediaItem with a fresh rating pulled from
/// the LikeBridge. Called by PlayerActions on likedIdsProvider
/// changes so the watch / lock-screen heart icon updates when the
/// user toggles a like from TrackRow, the kebab menu, or another
/// device's playback (SSE-routed). No-op if no track is playing
/// or the like state didn't change.
void refreshCurrentRating() {
final media = mediaItem.value;
final bridge = _likeBridge;
if (media == null || bridge == null) return;
final liked = bridge.isTrackLiked(media.id);
if (media.rating?.hasHeart() == liked) return;
mediaItem.add(media.copyWith(rating: Rating.newHeartRating(liked)));
}
@override
Future<void> setShuffleMode(AudioServiceShuffleMode shuffleMode) async {
await _player
@@ -433,6 +552,18 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
// systemActions enumerates which actions the system can invoke
// on us — without play/pause/skip in here, taps on lock-screen
// controls don't route back to the handler on Android 13+.
//
// v2026.05.13.3 added stop, skipToQueueItem, setShuffleMode,
// setRepeatMode, and setRating to this set; reverted because
// Pixel Watch 2 stopped showing controls entirely after that
// change. The MediaSession contract on Wear OS requires more
// setup than just advertising the action (e.g. setRatingType
// for setRating) and audio_service doesn't expose those knobs.
// Keep the override methods themselves (skipToQueueItem is
// still routed via QueueScreen's direct handler call;
// setRating is harmless if never invoked) so we don't lose
// the underlying functionality — just don't tell the system
// we support them.
systemActions: const {
MediaAction.play,
MediaAction.pause,
@@ -463,3 +594,27 @@ class MinstrelAudioHandler extends BaseAudioHandler with QueueHandler, SeekHandl
));
}
}
/// Adapter that lets the audio handler call into the app's
/// LikesController without depending on Riverpod directly. Constructed
/// in PlayerActions where ref is available; consumed inside the audio
/// handler's setRating override and MediaItem builder to keep external
/// media controllers (Wear, lock screen, Auto) in sync with the
/// likedIds drift cache.
class LikeBridge {
const LikeBridge({
required this.toggleTrackLike,
required this.isTrackLiked,
});
/// Flip the like state for [trackId]. Returns a Future that resolves
/// once the underlying LikesController has both updated drift
/// optimistically and rolled the change through the REST API
/// (errors result in drift rollback inside LikesController).
final Future<void> Function(String trackId) toggleTrackLike;
/// Read the current like state for [trackId] from the drift-backed
/// likedIdsProvider. Synchronous because the audio handler needs
/// to populate MediaItem.rating on the broadcast hot path.
final bool Function(String trackId) isTrackLiked;
}
+212 -86
View File
@@ -45,16 +45,132 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
// dismiss. Reset on each drag start.
double _dragOffset = 0;
/// Last resolved dominant color. Held across track changes so the
/// gradient backdrop tweens smoothly from the previous album's color
/// to the next, instead of dropping through fs.obsidian during the
/// brief moment albumColorProvider for the new id is still loading.
Color? _lastDominant;
/// The MediaItem currently displayed on the screen. Held separately
/// from the live mediaItemProvider so we can preload the new track's
/// cover bytes + dominant color BEFORE flipping the visible state.
/// Without this gate the full-player UI swapped to the new track's
/// title/cover slot immediately while the image was still decoding,
/// producing a visible "pop in" once the bytes arrived.
MediaItem? _displayedMedia;
/// Dedupe key for the cover precache side-effect. Without this we'd
/// fire precacheImage on every MediaItem rebroadcast (twice per track
/// change, once on artUri arrival).
String? _precachedArtUri;
/// Dominant color of [_displayedMedia]'s cover. Tweened by the
/// backdrop AnimatedContainer when it changes.
Color? _displayedDominant;
/// The id of the most-recent track we kicked a preload for. Used to
/// drop stale preload completions when the user skips rapidly past
/// a track whose cover hadn't finished decoding yet.
String? _pendingPreloadId;
@override
void initState() {
super.initState();
// Seed displayed state from the current mediaItem if a track is
// already playing when the full player is opened. ref.listen
// below only fires on CHANGES after subscription, so without
// this seed the screen sits on "Nothing playing." even though
// the mini bar shows a live track — the listener never gets a
// mediaItem emission because the stream's current value hasn't
// changed.
final current = ref.read(mediaItemProvider).value;
if (current == null) return;
_displayedMedia = current;
// Best-effort synchronous color seed: if albumColorProvider has
// already extracted this album's dominant color earlier in the
// session, pull it now so the backdrop renders correctly on
// first frame. Otherwise the post-frame _scheduleSwap below
// resolves it asynchronously and AnimatedContainer tweens.
final albumId = current.extras?['album_id'] as String?;
if (albumId != null && albumId.isNotEmpty) {
_displayedDominant =
ref.read(albumColorProvider(albumId)).asData?.value;
}
// Kick the preload pipeline post-frame so the cover bytes are
// decoded + the dominant color is resolved even when the user
// opens the player to a track that hasn't yet flowed through
// ref.listen.
WidgetsBinding.instance.addPostFrameCallback((_) {
if (!mounted) return;
_scheduleSwap(current);
});
}
/// Preload the new track's cover bytes + dominant color, then
/// atomically flip _displayedMedia / _displayedDominant. Until both
/// resolve, the screen continues to render the previous track —
/// the new title/cover/gradient appear together in one frame.
///
/// Concurrency: if a second track change arrives while the first
/// preload is still in flight, the older preload's
/// _pendingPreloadId check fails and its completion is dropped.
Future<void> _scheduleSwap(MediaItem newMedia) async {
_pendingPreloadId = newMedia.id;
// Fast path: when Prefetcher has already warmed both the cover
// bytes (file:// artUri populated via _toMediaItem's peekCached)
// AND the palette color (AlbumColorCache.peekColor returns
// non-null), we can commit synchronously. The slow async path
// exists for genuine cold-cache moments (first play of an album
// that sync hasn't seen yet); the fast path is what makes the
// common in-queue auto-advance flip the visual in lockstep with
// the audio transition instead of lagging a tick behind.
final artUri = newMedia.artUri;
final albumId = newMedia.extras?['album_id'] as String?;
if (artUri != null &&
artUri.isScheme('file') &&
albumId != null &&
albumId.isNotEmpty) {
final cachedColor = ref.read(albumColorCacheProvider).peekColor(albumId);
if (cachedColor != null) {
if (!mounted) return;
if (_pendingPreloadId != newMedia.id) return;
setState(() {
_displayedMedia = newMedia;
_displayedDominant = cachedColor;
});
return;
}
}
// Slow path: cover and/or color are not yet cached. Hold the
// current displayed state, preload, then atomic-commit.
//
// 1. Precache the cover image bytes so when _AlbumArt mounts with
// the new media, FileImage paints synchronously. Non-file
// artUris fall through to ServerImage which handles its own
// network load + 120ms fade — they won't snap.
if (artUri != null && artUri.isScheme('file') && context.mounted) {
try {
await precacheImage(FileImage(File.fromUri(artUri)), context);
} catch (_) {
// Decode failed (missing file, corrupt bytes) — proceed
// anyway; _AlbumArt's errorBuilder shows the slate fallback.
}
}
// 2. Wait for the dominant-color extraction so the gradient is
// populated when we swap. PaletteGenerator runs against the
// same FileImage, typically resolving within ~50ms once the
// decode completes.
Color? newDominant;
if (albumId != null && albumId.isNotEmpty) {
try {
newDominant = await ref.read(albumColorProvider(albumId).future);
} catch (_) {
// Color extraction failed — keep the previous dominant so the
// backdrop doesn't drop to obsidian on the swap.
}
}
// 3. Atomic flip. Bail if a newer swap superseded us, or the
// screen was disposed mid-preload.
if (!mounted) return;
if (_pendingPreloadId != newMedia.id) return;
setState(() {
_displayedMedia = newMedia;
if (newDominant != null) _displayedDominant = newDominant;
});
}
void _onDragStart(DragStartDetails _) {
_dragOffset = 0;
@@ -78,10 +194,61 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final media = ref.watch(mediaItemProvider).value;
final playback = ref.watch(playbackStateProvider).value;
if (media == null) {
// Listen for mediaItem changes and schedule a preload-then-swap.
// Build renders _displayedMedia / _displayedDominant; the live
// mediaItemProvider only drives the swap pipeline.
//
// Decision process:
// - On the first non-null mediaItem after mount, seed
// _displayedMedia immediately so the screen has something to
// paint.
// - On a track id change, kick off a preload. The new track's
// cover bytes + dominant color must both resolve before we
// flip the displayed state. The user sees the previous track
// in full until the new one is fully ready, then a clean
// atomic swap (no fade, no placeholder flash).
// - On the same track id but the artUri-bearing rebroadcast
// (audio_handler sends MediaItem twice on track change),
// refresh through the same preload pipeline so the displayed
// cover reflects the freshly-written AlbumCoverCache file.
ref.listen<AsyncValue<MediaItem?>>(mediaItemProvider, (prev, next) {
final newMedia = next.asData?.value;
if (newMedia == null) {
if (_displayedMedia != null) {
setState(() {
_displayedMedia = null;
_displayedDominant = null;
_pendingPreloadId = null;
});
}
return;
}
if (_displayedMedia == null) {
// First mount with a track playing — seed immediately, then
// kick the preload pipeline to update the dominant color and
// ensure the cover is decoded.
setState(() => _displayedMedia = newMedia);
_scheduleSwap(newMedia);
return;
}
final isNewTrack = newMedia.id != _displayedMedia!.id;
final coverGotPopulated =
newMedia.id == _displayedMedia!.id &&
newMedia.artUri != null &&
_displayedMedia!.artUri == null;
if (isNewTrack || coverGotPopulated) {
_scheduleSwap(newMedia);
}
});
final playback = ref.watch(playbackStateProvider).value;
final displayedMedia = _displayedMedia;
if (displayedMedia == null) {
// Either nothing playing, or the very first mount before a
// mediaItem has been emitted. The ref.listen above will seed
// _displayedMedia as soon as a non-null MediaItem arrives.
return const Scaffold(body: Center(child: Text('Nothing playing.')));
}
@@ -90,53 +257,22 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
// only fires on state transitions and would leave the bar frozen
// between them.
final pos = ref.watch(positionProvider).value ?? Duration.zero;
final dur = media.duration ?? Duration.zero;
final dur = displayedMedia.duration ?? Duration.zero;
final isPlaying = playback?.playing == true;
final shuffleOn = playback?.shuffleMode == AudioServiceShuffleMode.all;
final repeatMode = playback?.repeatMode ?? AudioServiceRepeatMode.none;
final actions = ref.read(playerActionsProvider);
final albumId = (media.extras?['album_id'] as String?) ?? '';
final albumId = (displayedMedia.extras?['album_id'] as String?) ?? '';
// Dominant-color gradient backdrop seeded from the current track's
// album cover. Tweens to the new color on track change via
// AnimatedContainer.
//
// We hold _lastDominant across builds so a track change doesn't
// briefly tween to fs.obsidian while albumColorProvider for the
// new id is loading — that brief stop produced the "background
// coloring snaps in" effect users saw. With a held color, the
// gradient stays on the previous album's color until the new
// extraction resolves, then animates straight to it.
final dominantAsync = ref.watch(albumColorProvider(albumId));
final resolved = dominantAsync.asData?.value;
if (resolved != null) _lastDominant = resolved;
final dominant = _lastDominant ?? fs.obsidian;
// 0.55 alpha keeps the color present without overwhelming contrast
// on the title / artist text below. The lower half of the screen
// stays obsidian for control legibility.
// Backdrop color: render the dominant we've already committed to
// _displayedDominant. AnimatedContainer tweens between successive
// values, so the only color changes the user sees are the
// atomic-with-cover swaps from _scheduleSwap. 0.55 alpha keeps
// the gradient present without overwhelming the title/artist
// text below.
final dominant = _displayedDominant ?? fs.obsidian;
final gradientTop = dominant.withValues(alpha: 0.55);
// Precache the cover image bytes the moment a new MediaItem (with
// a file:// artUri) is broadcast. Without this, AnimatedSwitcher's
// cross-fade for the cover would complete before FileImage finished
// decoding the bytes — visible as a "snap in" of the album art
// after the fade. precacheImage decodes in the background; by the
// time the new _AlbumArt mounts inside the switcher, the bytes are
// ready and the cover paints synchronously.
//
// Non-file artUris (the rare moment before AlbumCoverCache has
// written the file) fall back to ServerImage / CachedNetworkImage
// which has its own 120ms fade — no precache benefit there.
final artUri = media.artUri;
final artKey = artUri?.toString();
if (artUri != null &&
artUri.isScheme('file') &&
artKey != _precachedArtUri) {
_precachedArtUri = artKey;
// ignore: unawaited_futures
precacheImage(FileImage(File.fromUri(artUri)), context);
}
return Scaffold(
backgroundColor: fs.obsidian,
// The whole screen accepts vertical drag for dismissal. Buttons
@@ -167,46 +303,36 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
child: Column(
children: [
const Spacer(),
AnimatedSwitcher(
duration: _trackChangeDuration,
child: KeyedSubtree(
key: ValueKey('cover-${media.id}'),
child: _AlbumArt(
media: media, albumId: albumId, fs: fs),
),
),
// No AnimatedSwitcher: _displayedMedia only
// advances after the preload pipeline has the
// new cover + color ready, so a track change
// is an atomic swap. Fading would just smear a
// transition the user explicitly asked us not
// to add.
_AlbumArt(
media: displayedMedia, albumId: albumId, fs: fs),
const SizedBox(height: 28),
AnimatedSwitcher(
duration: _trackChangeDuration,
child: KeyedSubtree(
key: ValueKey('title-${media.id}'),
child: _TitleRow(media: media, fs: fs),
),
),
_TitleRow(media: displayedMedia, fs: fs),
const SizedBox(height: 4),
AnimatedSwitcher(
duration: _trackChangeDuration,
child: Column(
key: ValueKey('artist-album-${media.id}'),
mainAxisSize: MainAxisSize.min,
children: [
Column(
mainAxisSize: MainAxisSize.min,
children: [
Text(
displayedMedia.artist ?? '',
style: TextStyle(color: fs.ash, fontSize: 14),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if ((displayedMedia.album ?? '').isNotEmpty) ...[
const SizedBox(height: 2),
Text(
media.artist ?? '',
style: TextStyle(color: fs.ash, fontSize: 14),
displayedMedia.album!,
style: TextStyle(color: fs.ash, fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
if ((media.album ?? '').isNotEmpty) ...[
const SizedBox(height: 2),
Text(
media.album!,
style: TextStyle(color: fs.ash, fontSize: 12),
maxLines: 1,
overflow: TextOverflow.ellipsis,
),
],
],
),
],
),
const SizedBox(height: 24),
_SecondaryControls(
@@ -214,7 +340,7 @@ class _NowPlayingScreenState extends ConsumerState<NowPlayingScreen> {
actions: actions,
shuffleOn: shuffleOn,
repeatMode: repeatMode,
media: media,
media: displayedMedia,
),
const SizedBox(height: 8),
_SeekRow(position: pos, duration: dur, fs: fs, ref: ref),
+41 -31
View File
@@ -28,16 +28,37 @@ import 'player_provider.dart';
/// Tap anywhere on the bar (including art/title) ascends to the full
/// player. A vertical drag upward also ascends, so the gesture mirrors
/// the drag-down dismissal on the full screen.
class PlayerBar extends ConsumerWidget {
class PlayerBar extends ConsumerStatefulWidget {
const PlayerBar({super.key});
@override
Widget build(BuildContext context, WidgetRef ref) {
ConsumerState<PlayerBar> createState() => _PlayerBarState();
}
class _PlayerBarState extends ConsumerState<PlayerBar> {
/// Last non-null artUri we've seen from the mediaItem stream. Held
/// across the audio_handler's two-broadcast track-change pattern
/// (bare MediaItem first, then with artUri once AlbumCoverCache
/// resolves) so the mini bar keeps showing the previous track's
/// cover until the new one is known. Without this hold the bar
/// flickered to the slate placeholder for ~100ms on every track
/// change.
Uri? _lastArtUri;
@override
Widget build(BuildContext context) {
final fs = Theme.of(context).extension<FabledSwordTheme>()!;
final media = ref.watch(mediaItemProvider).value;
final playback = ref.watch(playbackStateProvider).value;
if (media == null) return const SizedBox.shrink();
// Capture the latest non-null artUri so _TrackInfo's cover stays
// continuous across track changes.
if (media.artUri != null) _lastArtUri = media.artUri;
final displayMedia = media.artUri == null && _lastArtUri != null
? media.copyWith(artUri: _lastArtUri)
: media;
// positionProvider is just_audio's positionStream (~200ms cadence)
// so the mini bar's seek crawls forward smoothly. PlaybackState
// only updates on event transitions and would leave it frozen.
@@ -65,7 +86,7 @@ class PlayerBar extends ConsumerWidget {
child: Row(
crossAxisAlignment: CrossAxisAlignment.center,
children: [
Expanded(child: _TrackInfo(media: media)),
Expanded(child: _TrackInfo(media: displayMedia)),
const SizedBox(width: 8),
_PlayControls(playback: playback, ref: ref),
],
@@ -96,27 +117,27 @@ class _TrackInfo extends StatelessWidget {
// than fade-cutting. Tag is stable per-route (not keyed by media.id)
// so the transition works regardless of what's playing.
//
// AnimatedSwitcher around the cover smooths the artUri null→file://
// swap that fires on every track change: audio_handler broadcasts
// the new MediaItem without artUri immediately, then re-broadcasts
// with artUri once AlbumCoverCache resolves the path. Without the
// crossfade the cover snaps from the previous track's image to a
// slate placeholder to the new image — visible as a flicker.
final Widget coverChild;
if (media.artUri != null) {
// Why no transition / placeholder handling: the audio_handler
// broadcasts MediaItem twice on track change — once with artUri
// null (the new track's bare metadata), then with artUri set once
// AlbumCoverCache resolves. The widget tree above hands us the
// most-recent non-null artUri (`displayArtUri`), so the previous
// track's cover stays visible across that null gap and the new
// cover snaps in the moment its artUri arrives. Rapid change is
// fine here per operator preference; AnimatedSwitcher previously
// smeared the swap and made the slate placeholder visible.
final displayArtUri = media.artUri;
final Widget cover;
if (displayArtUri != null) {
// CachedNetworkImageProvider for HTTPS art URIs so the mini bar
// hits the same disk cache the rest of the UI uses (ServerImage,
// discover thumbnails). FileImage stays for the file:// branch
// populated by AlbumCoverCache — bytes are already on disk and a
// second cache layer would only burn duplicate space.
coverChild = Image(
// Key includes the artUri so AnimatedSwitcher detects a swap;
// without this it treats successive Image widgets as the same
// tree node and skips the transition.
key: ValueKey('art-${media.artUri}'),
image: media.artUri!.isScheme('file')
? FileImage(File.fromUri(media.artUri!)) as ImageProvider
: CachedNetworkImageProvider(media.artUri.toString()),
cover = Image(
image: displayArtUri.isScheme('file')
? FileImage(File.fromUri(displayArtUri)) as ImageProvider
: CachedNetworkImageProvider(displayArtUri.toString()),
width: 48,
height: 48,
// Without a fit, Image paints the source at its intrinsic
@@ -128,19 +149,8 @@ class _TrackInfo extends StatelessWidget {
Container(width: 48, height: 48, color: fs.slate),
);
} else {
coverChild = Container(
key: const ValueKey('art-placeholder'),
width: 48,
height: 48,
color: fs.slate,
);
cover = Container(width: 48, height: 48, color: fs.slate);
}
final cover = AnimatedSwitcher(
duration: const Duration(milliseconds: 180),
switchInCurve: Curves.easeOut,
switchOutCurve: Curves.easeOut,
child: coverChild,
);
return Row(
// Default centering vertically aligns the like/kebab buttons
// against the album art (48dp) — visually they span the title +
+31 -1
View File
@@ -1,10 +1,12 @@
import 'package:audio_service/audio_service.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/likes.dart' show LikeKind;
import '../api/endpoints/radio.dart';
import '../auth/auth_provider.dart';
import '../cache/audio_cache_manager.dart';
import '../library/library_providers.dart' show dioProvider;
import '../likes/likes_provider.dart';
import '../models/track.dart';
import 'album_cover_cache.dart';
import 'audio_handler.dart';
@@ -49,7 +51,18 @@ final positionProvider = StreamProvider<Duration>(
);
class PlayerActions {
PlayerActions(this._ref);
PlayerActions(this._ref) {
// Keep MediaItem.rating in sync with the drift-backed likedIds
// cache so external media surfaces (Wear's heart button, lock-
// screen favorite, Auto's like icon) reflect the current state
// even when the user toggles a like from somewhere other than
// the watch itself — e.g. tapping the heart on a TrackRow, the
// kebab menu, or another logged-in device propagating via SSE.
_ref.listen<AsyncValue<LikedIds>>(likedIdsProvider, (_, next) {
if (next.value == null) return;
_ref.read(audioHandlerProvider).refreshCurrentRating();
});
}
final Ref _ref;
Future<void> playTracks(List<TrackRef> tracks, {int initialIndex = 0}) async {
@@ -63,11 +76,28 @@ class PlayerActions {
token: token,
coverCache: cache,
audioCacheManager: audioCache,
likeBridge: _buildLikeBridge(),
);
await h.setQueueFromTracks(tracks, initialIndex: initialIndex);
await h.play();
}
/// Builds the adapter the audio handler uses to read + flip the
/// current track's like state in response to external media-
/// controller events (Wear's heart button, lock-screen favorite).
/// Constructed here because the audio handler is initialized in
/// main.dart before the ProviderScope exists; passing the bridge
/// in via configure() keeps the handler Riverpod-agnostic while
/// still letting it call into LikesController + likedIdsProvider.
LikeBridge _buildLikeBridge() {
return LikeBridge(
toggleTrackLike: (id) =>
_ref.read(likesControllerProvider).toggle(LikeKind.track, id),
isTrackLiked: (id) =>
_ref.read(likedIdsProvider).value?.has(LikeKind.track, id) ?? false,
);
}
Future<void> playNext(TrackRef track) async {
final h = _ref.read(audioHandlerProvider);
await h.playNext(track);
@@ -8,6 +8,7 @@ import '../api/endpoints/quarantine.dart';
import '../cache/audio_cache_manager.dart' show appDbProvider;
import '../cache/connectivity_provider.dart';
import '../cache/db.dart';
import '../cache/mutation_queue.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/quarantine_mine.dart';
import '../models/track.dart';
@@ -110,17 +111,18 @@ class MyQuarantineController extends AsyncNotifier<List<QuarantineMineRow>> {
try {
final api = await ref.read(quarantineApiProvider.future);
await api.flag(track.id, reason, notes: notes);
} catch (e, st) {
// Rollback the optimistic insert; watch() re-emits the prior set.
await (db.delete(db.cachedQuarantineMine)
..where((t) => t.trackId.equals(track.id)))
.go();
Error.throwWithStackTrace(e, st);
} catch (_) {
// REST failed — don't roll back; queue for replay so the user's
// "hide this track" intent persists offline.
await ref.read(mutationQueueProvider).enqueue(
MutationKinds.quarantineFlag,
{'trackId': track.id, 'reason': reason, 'notes': notes},
);
}
}
/// Optimistic unflag: removes the drift row, calls server, restores
/// on error.
/// Optimistic unflag: removes the drift row, calls server, queues
/// the call on failure so the unhide intent persists offline.
Future<void> unflag(String trackId) async {
final db = ref.read(appDbProvider);
final existing = await (db.select(db.cachedQuarantineMine)
@@ -135,13 +137,11 @@ class MyQuarantineController extends AsyncNotifier<List<QuarantineMineRow>> {
try {
final api = await ref.read(quarantineApiProvider.future);
await api.unflag(trackId);
} catch (e, st) {
// Restore the row we just deleted — toCompanion(true) preserves
// every field including the original fetchedAt timestamp.
await db
.into(db.cachedQuarantineMine)
.insertOnConflictUpdate(existing.toCompanion(true));
Error.throwWithStackTrace(e, st);
} catch (_) {
// Don't restore the drift row; queue the unflag for replay.
await ref
.read(mutationQueueProvider)
.enqueue(MutationKinds.quarantineUnflag, {'trackId': trackId});
}
}
@@ -3,6 +3,7 @@ import 'dart:async';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import '../api/endpoints/requests.dart';
import '../cache/mutation_queue.dart';
import '../library/library_providers.dart' show dioProvider;
import '../models/admin_request.dart';
@@ -41,17 +42,20 @@ class MyRequestsController extends AsyncNotifier<List<AdminRequest>> {
}
}
/// Optimistic remove + REST cancel. Restores the row on failure so
/// the user can retry — silent failure would lie about success.
/// Optimistic remove + REST cancel. On failure the row stays
/// removed in-memory and the cancel is queued for replay — this
/// keeps the user's intent visible across network loss instead of
/// restoring a row they explicitly asked to remove.
Future<void> cancel(String id) async {
final api = await ref.read(requestsApiProvider.future);
final current = state.value ?? const <AdminRequest>[];
state = AsyncData(current.where((r) => r.id != id).toList());
try {
await api.cancel(id);
} catch (e, st) {
state = AsyncData(current);
Error.throwWithStackTrace(e, st);
} catch (_) {
await ref
.read(mutationQueueProvider)
.enqueue(MutationKinds.requestCancel, {'id': id});
}
}
}
@@ -1,8 +1,12 @@
import 'package:drift/drift.dart' as drift;
import 'package:flutter/material.dart';
import 'package:flutter_riverpod/flutter_riverpod.dart';
import 'package:go_router/go_router.dart';
import '../../../api/endpoints/likes.dart';
import '../../../cache/audio_cache_manager.dart' show appDbProvider;
import '../../../cache/db.dart';
import '../../../cache/mutation_queue.dart';
import '../../../likes/likes_provider.dart';
import '../../../models/track.dart';
import '../../../player/player_provider.dart';
@@ -255,7 +259,38 @@ typedef AddToPlaylistAction = Future<void> Function(String playlistId, String tr
final addToPlaylistActionProvider = Provider<AddToPlaylistAction>((ref) {
return (playlistId, trackId) async {
final api = await ref.read(playlistsApiProvider.future);
await api.appendTracks(playlistId, [trackId]);
final db = ref.read(appDbProvider);
// Optimistic drift write so the playlist detail screen shows the
// new track instantly. The position is best-effort — append after
// the current max for this playlist. The server's authoritative
// position lands on next playlistDetailProvider fetch (SWR), or
// when the queued mutation replays.
final maxPos = await (db.selectOnly(db.cachedPlaylistTracks)
..addColumns([db.cachedPlaylistTracks.position.max()])
..where(db.cachedPlaylistTracks.playlistId.equals(playlistId)))
.getSingleOrNull();
final nextPos =
((maxPos?.read(db.cachedPlaylistTracks.position.max()) ?? -1) + 1);
await db.into(db.cachedPlaylistTracks).insertOnConflictUpdate(
CachedPlaylistTracksCompanion.insert(
playlistId: playlistId,
trackId: trackId,
position: drift.Value(nextPos),
),
);
try {
final api = await ref.read(playlistsApiProvider.future);
await api.appendTracks(playlistId, [trackId]);
} catch (_) {
// REST failed — keep the optimistic drift row; queue the call.
await ref.read(mutationQueueProvider).enqueue(
MutationKinds.playlistAppend,
{
'playlistId': playlistId,
'trackIds': [trackId],
},
);
}
};
});
+1 -1
View File
@@ -1,7 +1,7 @@
name: minstrel
description: Minstrel mobile client
publish_to: 'none'
version: 2026.5.13+2
version: 2026.5.14+5
environment:
sdk: '>=3.5.0 <4.0.0'
+9 -2
View File
@@ -32,9 +32,16 @@ void main() {
isOnline: () async => true,
);
final firstFuture = results.first;
// Post-coldFetchAttempted guard, cacheFirst yields the current
// (still-empty) rows after the fetch returns, so the stream
// never hangs when populate is a no-op for this filter. The
// simulated drift re-emit then yields the populated rows.
// Capture the Future *before* feeding the controller so the
// listener is subscribed when the first add() lands.
final emissionsFuture = results.take(2).toList();
controller.add([]);
expect(await firstFuture, 42);
final emissions = await emissionsFuture;
expect(emissions, [0, 42]);
expect(fetchCalled, 1);
await controller.close();
});
@@ -92,8 +92,8 @@ void main() {
expect(rows.first.reason, 'bad_rip');
});
test('flag rolls back the drift insert on server failure', skip: _skipDrift,
() async {
test('flag keeps drift optimistic + queues mutation on server failure',
skip: _skipDrift, () async {
final db = AppDb(NativeDatabase.memory());
addTearDown(db.close);
final api = _StubQuarantineApi(shouldThrow: true);
@@ -101,14 +101,18 @@ void main() {
addTearDown(container.dispose);
await container.read(myQuarantineProvider.future);
await expectLater(
() => container
.read(myQuarantineProvider.notifier)
.flag(_track, 'bad_rip', ''),
throwsException,
);
// No longer rethrows — flag swallows the REST failure and queues
// for replay so the user's intent persists offline.
await container
.read(myQuarantineProvider.notifier)
.flag(_track, 'bad_rip', '');
final rows = await db.select(db.cachedQuarantineMine).get();
expect(rows, isEmpty);
expect(rows, hasLength(1),
reason: 'optimistic drift row should persist across REST failure');
final mutations = await db.select(db.cachedMutations).get();
expect(mutations, hasLength(1),
reason: 'failed flag should have been enqueued for replay');
expect(mutations.first.kind, 'quarantine.flag');
});
test('unflag deletes the drift row and calls the server', skip: _skipDrift,