4992 Commits

Author SHA1 Message Date
Deluan Quintão
944ca3100f
feat(artwork): new artwork pipeline with background resolution and Low Quality Image Placeholders (#5847)
* feat(artwork): add artwork, item_artwork and artwork_queue tables

* feat(artwork): add artwork models, repository interfaces and mocks

* feat(artwork): implement artwork repository

* feat(artwork): implement item_artwork repository with batched hydration

* feat(artwork): implement artwork_queue repository

* feat(artwork): add content-addressed originals store

* feat(artwork): add artwork prune (orphan cleanup)

* fix(artwork): never sweep files on transient DB errors during prune

* refactor(artwork): fold originals package into core/artwork as ImageStore

* refactor(artwork): merge item artwork state into ArtworkRepository

* fix(artwork): chunk unbounded IN clauses and restore interface docs

* refactor(artwork): apply simplify-pass cleanups

Internal item_artwork sqlRepository helper, toSQLArgs upserts, batched queue enqueue, EnqueueStaleAbsent moved to queue repo, snapshot-based prune sweep, mock/real semantics aligned.

* fix(artwork): address review findings on prune/sweep races and mock fidelity

Sweep now honors an mtime grace window (in-flight acquisitions and temp files), reacquired orphans reset the prune grace window, and the queue mock implements real stale-absent semantics.

* fix(artwork): atomic orphan deletion and timestamp semantics from review

DeleteOrphans re-checks age+references at delete time, PutItemArtwork defaults attempted_at, queue mock timestamps mirror SQL.

* fix(artwork): guard orphan file removal with the prune grace window

Duplicate ImageStore writes refresh the file mtime and Remove skips files newer than the cutoff, so overlapping acquisitions cannot lose their store files to a concurrent prune.

* fix(artwork): rewrite vanished duplicates and sweep stale mime variants

Write falls through to a real write when the liveness touch fails, and sweep retention now matches the recorded mime's extension so obsolete variants are reclaimed.

* fix(artwork): index artwork_queue in dequeue order

The previous leading retry_at range column forced a temp B-tree sort of the whole eligible set on every DequeueBatch; ordering the index by (priority DESC, enqueued_at) lets scans stop after the batch size.

* fix(artwork): honor the orphan cutoff in the repository mock

The mock's DeleteOrphans now applies createdBefore like the SQL implementation, and a new spec covers a freshly reacquired row surviving prune.

* fix(artwork): reject malformed hashes in ImageStore operations

Known-absent states carry an empty hash and malformed persisted hashes could panic path sharding or inject separators; Write/Open/Remove now return an error for anything but 16 lowercase hex chars.

* fix(artwork): mock PutImage refreshes created_at like the SQL repository

Prune specs now age fixtures directly instead of seeding stale timestamps through the upsert.

* fix(artwork): store backing-file provenance per item, not per hash

* feat(artwork): import blurhash encoder from #5797

* feat(artwork): add worker-side artwork resolvers

* fix(artwork): propagate playlist tile failures and dedupe external step

* feat(artwork): add acquisition processor

Resolves one queue item end to end: hash/dedup, decode + 128px thumbnail
blurhash, place bytes (store vs source file), and persist found/absent/
failed state for the worker (Task 4) to act on.

* style(artwork): tighten processor comments to budget

* feat(artwork): add acquisition worker service

* feat(artwork): enqueue artwork resolution from scan and CRUD paths

* feat(artwork): artwork backfill, fingerprint re-resolution and scheduled jobs

* test(artwork): leak/soak coverage and deferred assertions

* fix(artwork): propagate transient artist image errors to the worker

callGetImage swallowed all agent errors, so an agent outage surfaced as ErrNotFound and the worker settled artist artwork as a definitive absent (and reset the breaker). Add an additive ArtistImageResult path that returns the underlying agent error on transient failure while keeping ArtistImage byte-identical for existing callers; the worker's artist external step uses it via fromArtistExternalResult.

* fix(artwork): resolve full playlist source chain

resolvePlaylist only built the generated grid, dropping the uploaded-image, sidecar and ExternalImageURL sources the old reader_playlist.go chain serves. Port the full chain before the grid fallback: uploaded (upload), sidecar (folder), and ExternalImageURL routed through extGate with the same extError semantics as the other external steps. Also rewires the artist external step onto ArtistImageResult.

* fix(artwork): purge dangling queue rows and guard concurrent re-enqueues

Queue rows for deleted entities failed forever (Get -> ErrNotFound -> failed -> capped retries, unbounded). Add ArtworkQueueRepository.PurgeDangling, called from Prune next to the item_artwork purge. Separately, the found/absent path unconditionally deleted the dequeued row, erasing a concurrent scan re-enqueue; switch to DeleteIfUnchanged, which deletes only while retry_at still matches the dequeued value (verified retry_at is the column an Enqueue upsert resets).

* style(artwork): fix comment accuracy and budget; fingerprint ArtistImageFolder

Correct the inverted workerDeps.extGate comment, trim over-budget doc comments, and add conf.Server.ArtistImageFolder to the resolution fingerprint so an image-folder change re-resolves artist artwork.

* fix(artwork): treat missing local playlist cover as definitive, not transient

A playlist ExternalImageURL pointing at a local file that fails to open was
routed through extError, causing failed/48h-retry loops that burn a rate
limiter token forever instead of falling through to the generated grid.

* refactor(artwork): deduplicate purge loop, backfill table, and extGate alias

* fix(artwork): cap resolved image reads

A user-editable ExternalImageURL can point at an arbitrarily large endpoint;
a fast server could make the worker buffer hundreds of MB inside the 5s HTTP
timeout. Bound the read to a fixed 20MB cap (no config knob) via io.LimitReader
and fail the item if it is exceeded.

* fix(artwork): retry higher-priority external art after fallback hit

With CoverArtPriority="external,cover.jpg", a transient external failure
followed by a folder hit dropped the external error: the worker recorded
found and deleted the queue row, so the configured higher-priority external
art was never retried. Carry extError onto the fallback resolution and add
an outcomeFoundStale that persists+serves the art but reschedules via
MarkFailed, giving the external source another chance. When external later
answers definitively-not-found, the hit is not stale and the row is deleted.

* fix(artwork): treat playlist cover URL 404 as definitive miss

The playlist ExternalImageURL step used sources.go's fromURL, which maps any
non-200 to a generic error, so a stale URL returning 404/410 was classified
transient: infinite backoff plus it counted toward the circuit breaker,
blocking valid external work. Add a local fetch in resolve.go that maps
404/410 to model.ErrNotFound (definitive) while keeping other non-200s
transient. sources.go is left untouched.

* test(artwork): move soak test into the Ginkgo suite

* test(artwork): make leak and permission tests pass on linux

goleak now ignores notify's nonrecursive-tree goroutines (linux uses
inotify, which spawns dispatch+internal instead of darwin's recursive
dispatch), and the read-only-dir prune spec skips under root, where
permission bits cannot make Remove fail.

* fix(artwork): reject decompression-bomb dimensions before decoding

* fix(artwork): keep fresh re-enqueues ahead of stale failure backoff

* fix(artwork): include M3U external art flag in the config fingerprint

* fix(artwork): resolve private playlists with an admin context

* test(artwork): convert non-synctest timing tests to Ginkgo specs

TestArtworkBackoffSchedule and TestArtworkWorkerRunNoLeak needed no real
*testing.T (no synctest), so move them into worker_test.go as Ginkgo
specs. TestArtworkBreakerHalfOpen stays plain since testing/synctest
requires a real *testing.T, matching core/scrobbler's precedent.

* fix(artwork): store backing-file provenance per item, not per hash

* fix(artwork): apply image limits to playlist tile decoding

decodeTile ran image.Decode on every sampled album's resolved bytes
before processItem's maxImageBytes/maxImagePixels guards applied,
letting an oversized or decompression-bomb tile fully decode
unbounded. Enforce both caps inside decodeTile itself.

* refactor(artwork): reuse auth.WithAdminUser and dedupe image cap guards

* perf(artwork): fetch only IDs for backfill enumeration

Backfill enumerated every album, artist, playlist and radio via GetAll
and mapped out just the ID. GetAll materializes full entities (library
joins, participant/stats/tags JSON, annotation, artwork hydration), so on
a large library it loaded tens of thousands of heavy structs only to read
one field each — spiking transient RSS to ~1GB during the one-time
upgrade backfill, a memory risk on small NAS/Pi hardware.

Add GetAllIDs to the album, artist, playlist and radio repositories: it
reuses each repo's base row-set filter (library visibility, artist
content join, playlist userFilter) but projects only id, skipping the
heavy columns and post-processing. A per-repo parity test asserts
GetAllIDs returns exactly the same id set as GetAll.

Verified on a 727MB / 29k-artist production DB copy: peak RSS during
backfill dropped from ~1012MB to ~89MB, file descriptors flat, same
36,138 items enqueued.

* feat(artwork): promote worker concurrency and external rate to real configs

The artwork worker's drain speed was governed by two hidden Dev flags,
DevArtworkWorkerConcurrency and DevArtworkExternalRPS, both defaulting to 2.
On a large library's one-time backfill the external rate limiter is the real
ceiling: every art-less item waits on it before the (rate-limited) external
lookup, so the drain crawls at ~RPS items/sec while local-art items are
unaffected.

Promote both to documented, supported options: ArtworkWorkerConcurrency
(default 4) sets local-resolution parallelism, ArtworkExternalMaxRPS
(default 2, 0 = unlimited) caps external-agent lookups to stay polite to
Last.fm/Deezer/etc. Operators can now trade first-backfill speed against
external-API rate limits. The old Dev names still map for backward compat.

* fix(deezer): never return empty-image-id placeholder pictures

* feat(agents): enumerate enabled image-retriever agents per capability

* feat(artwork): worker fetches agent images directly with per-agent rate limits and breakers

* fix(artwork): treat agent not-found as breaker success

* feat(model): content-hash artwork id suffix and hydratable per-entity image state

* feat(persistence): hydrate artwork hash and absence onto entity pages

* feat(artwork): resolve media_file embedded art in the worker, invalidate on rescan

* feat(artwork): broadcast refresh events when artwork lands

* fix(artwork): broadcast refresh for stale-found artwork too

* feat(artwork): state-backed serving path with provisional read-through

* feat(server): serve artwork from persisted state with content-hash caching

* feat(subsonic): content-hash coverArt ids, omit artwork on known-absent

* refactor(artwork): delete the legacy reader chain, cache warmer, and provider image methods

* feat(artwork): precache on acquisition, bump on upload/radio changes, manual re-resolve API

* test(artwork): end-to-end coverage for the serving cutover

* chore(artwork): generic 500 bodies on refresh endpoint, trim stale test comments

* fix(artwork): request read-through must not reset the failure backoff

The provisional read-through and dangling re-enqueue used Enqueue, whose upsert
resets retry_at, so any browse of an unresolved entity that was backing off after
an external failure made it immediately eligible again — defeating the exponential
backoff during a provider outage. Add EnqueueBump, which raises priority but leaves
an existing row's retry_at intact, and route the serving path through it. Scan and
manual re-resolve keep Enqueue's reset (a detected change wants immediate retry).

* fix(artwork): keep an eligible track's cover requestable when its album is absent

An embedded-eligible track with no resolved item_artwork row inherited the album's
ImageAbsent, so when the album resolved absent (e.g. CoverArtPriority without
'embedded') the track's coverArt was omitted permanently — the client never
requested it, so the lazy mediafile path never resolved it — even though the
serving path would extract and serve the track's own embedded art. Hydration now
never copies the album's absence onto an eligible-but-unresolved track.

* fix(artwork): validate each agent image URL before picking the largest

bestImageURL selected the largest by size and only then parsed it, so a malformed
largest URL (e.g. a bad percent-escape) returned nil and shadowed a valid smaller
candidate, contradicting the documented skip-unparseable behavior. Parse per
candidate and compare sizes only among URLs that parse.

* fix(artwork): fall back to disc art, not the album, for multi-disc tracks

serveMediaFile delegated an absent/ineligible track straight to AlbumCoverArtID,
skipping the disc-specific lookup that MediaFile.CoverArtID (and the deleted legacy
reader) use. On multi-disc albums with per-disc images that served the album cover
instead of the configured disc artwork. Delegate through DiscCoverArtID.

* fix(artwork): enqueue uploaded artwork only after the filename is persisted

SetImage cleared state and enqueued the bump before the caller stored the new
filename, so a worker drain in that window could resolve against the old (already
deleted) file and settle absent, leaving the upload unused until a later scan. Move
the invalidate+enqueue into EnqueueArtwork, which each caller now invokes after the
entity Put.

* fix(artwork): keep multi-disc tracks requestable when the album is absent

Round-1's hydration fix still copied the album's known-absent onto a non-eligible
(or own-absent) track, but MediaFile.CoverArtID routes a multi-disc track to disc
art, which resolves provisionally and is never known-absent. Marking it absent made
Subsonic omit coverArt so clients never requested a valid disc image. Only mark a
single-disc track absent, and only when its own art won't resolve.

* fix(artwork): serve a local playlist ExternalImageURL as a file-backed reference

A local ExternalImageURL was resolved through the external step and labelled
external, so placeBytes copied it into the content-addressed store and dropped its
path/mtime — replacing the file never tripped the staleness check. Classify local
references as file-backed (resolved in place, even on the request path) and keep
store-backed behaviour only for http(s) URLs.

* fix(artwork): requeue playlist cover when its track set changes

A generated-grid cover went stale after track mutations: nothing re-resolved the
playlist's artwork, and the request path deliberately never rebuilds the grid, so
serveEntity kept returning the old grid hash indefinitely. Enqueue pl artwork from
refreshCounters (the choke point for every track-set change); no clear, so the old
cover keeps serving until the worker rebuilds.

* fix(artwork): open library-backed artwork through its on-disk root

A library configured with a file:// path stored absRoot as the raw URI, so Abs
produced strings like file:/music/cover.jpg that os.Open/os.Stat reject — folder,
upload and embedded art were treated as dangling on every request, looping forever.
Normalize a file:// path to its parsed OS path (the same root os.DirFS uses);
non-local schemes are left unchanged (out of scope, per the artwork-musicfs TODO).

* fix(artwork): only use disc resolution for multi-disc albums

DiscCoverArtID returns a dc- id for any track with DiscNumber>0, so serveDisc ran
the full DiscArtPriority chain even for single-disc albums, where a stray disc*/
embedded image could shadow higher-priority album art. Gate disc resolution on the
album having more than one disc, matching the legacy reader; single-disc tracks
serve album art directly.

* fix(artwork): invalidate artwork when an uploaded image is deleted

Deleting an artist/radio/playlist upload cleared the filename but left the found
item_artwork row and its hash, so lists kept advertising the deleted cover's
hash-suffixed immutable URL and clients could display it indefinitely. Call
EnqueueArtwork after the delete-side Put, symmetric with upload, so the state is
cleared and re-resolved to the next source (or absent).

* fix(artwork): restore synthetic-artist guard and unicode normalization in agent lookups

Moving agent calls into the worker bypassed two behaviors of the aggregate provider:
Agents.GetArtistImages' guard for Unknown/Various Artists (a direct retriever call
could assign an unrelated image to a synthetic artist), and auxAlbum/auxArtist.Name's
DevPreserveUnicodeInExternalCalls normalization (records with typographic quotes/dashes
missed exact-name searches). Re-apply both before enumerating retrievers.

* fix(artwork): enforce entity visibility on the Subsonic getCoverArt path

serveEntity reads persisted item_artwork by id, bypassing the library and private-
playlist filters that the legacy entity-load applied. On the authenticated Subsonic
path a user could fetch artwork for an inaccessible album or someone else's private
playlist by guessing an id. getCoverArt now resolves the underlying entity through
the request-scoped (filtered) repositories and serves the placeholder when it is not
visible, so existence isn't leaked and the always-an-image invariant holds. The
public share (JWT-authorized) and Jellyfin (admin) paths are intentionally untouched.

* fix(artwork): version the artwork ETag with the served representation

The ETag was the pixel hash of the original image, so a CoverArtQuality or
EnableWebPEncoding change altered the resized bytes without changing the ETag —
revalidating clients got a spurious 304 and kept the old encoding. Resized responses
now carry a representation ETag (hash + size + square + encode settings) used for the
ETag header and If-None-Match, while the immutable decision stays on the pixel hash
(URLs remain pixel-identity per the spec, so hash-suffixed clients keep zero-request
caching). Full-size originals fall back to the pixel hash as before.

* fix(artwork): don't stamp the album hash onto multi-disc tracks

The hydration fallback assigned a found album hash to every fallback track, but a
multi-disc track's CoverArtID emits a dc- id served from disc-specific art whose hash
is unknown at hydration time. Advertising dc-..._<albumHash> gave clients a content-
version that never changes when the disc image does, breaking id-based refresh. Only
stamp the album hash for single-disc tracks (DiscNumber == 0); multi-disc tracks stay
unhashed and rely on the correct ETag returned by the served response.

* fix(artwork): enqueue new empty playlists by id, and refresh on absent outcomes

Two worker/enqueue fixes from review:
- playlistRepository.Put assigned the generated id to the caller's Playlist but passed
  the stale copy (empty id) to refreshCounters, enqueueing a pl|"" row the worker
  failed until the daily dangling purge while the real playlist went unresolved. Set
  the id on the copy before enqueueing.
- The drain refresh batch only included found/foundStale, so a cover removed by a scan
  (found -> absent) never notified clients, leaving the old immutable image displayed.
  Broadcast absent outcomes too; precache still only warms found/foundStale.

* fix(artwork): honor disabled per-track art at serve time; use nanosecond mtime provenance

Two serving-correctness fixes from review:
- serveMediaFile served a persisted mf embedded image even after EnableMediaFileCoverArt
  was turned off (the setting isn't in the config fingerprint, so found rows aren't
  reprocessed). Direct mf- URLs now honor the setting at serve time and fall back to
  disc/album art.
- The file-backed staleness check compared whole-second mtimes, so a same-second content
  replacement (two writes in one second, or timestamp-preserving tools) could serve
  different bytes under the old hash + immutable policy. RefMtime is now unix-nanoseconds
  (no schema change; int64 column), detecting sub-second changes where the filesystem
  records them.

* fix(artwork): preserve the drive when normalizing Windows file:// library paths

url.Parse puts the volume of file://C:/Music in Host, not Path, so localOSRoot dropped
it and returned /Music — os.Open/os.Stat then failed and folder/embedded art on Windows
looped as dangling. Rejoin the host volume, matching core/storage/local's newLocalStorage.

* fix(artwork): clamp negative sizes to full-size; convert imghttp test to Ginkgo

- A negative size (Subsonic size / Jellyfin maxwidth accept signed ints) reached
  resizeStaticImage, where the square path builds image.NewNRGBA(Rect(0,0,size,size))
  — a giant rectangle that panics/OOMs. Clamp size<0 to 0 (full-size) at the Service
  entry. Positive sizes were already clamped to the original.
- imghttp used a plain func Test with a table; convert to a Ginkgo DescribeTable with
  the suite entry point in imghttp_suite_test.go (AGENTS.md test-framework requirement).

* test(artwork): use renamed ArtworkWorkerConcurrency in e2e tests

* feat(artwork): carry blurhash through item image hydration

* feat(nativeapi): expose artwork hash, absence and blurhash

* feat(artwork): hydrate the parent album's artwork state onto tracks

* test(artwork): add hydrateArtwork regression guard for AlbumImage wiring

Drives hydrateArtwork itself (not applyItemImage directly) over tracks that
take each of the loop's continue branches, so a future edit moving the
AlbumImage fill below a continue would fail loudly instead of passing silently.

* feat(jellyfin): version album and artist image tags by content hash

* fix(jellyfin): trim primaryImageTag comment to why-only, within budget

* feat(jellyfin): emit real blurhashes and drop the synthesized fallback

* feat(ui): version cover art urls by content hash and skip absent art

* feat(ui): add BlurHashCanvas placeholder component

* fix(ui): clear stale blurhash pixels and assert the draw path in tests

Clear the canvas before each decode attempt so a hash change that fails
to decode doesn't leave the previous frame's pixels on screen once this
wires into a list that recycles items. Also strengthen the specs to
assert createImageData/putImageData were actually invoked (and with
what), instead of only checking that a <canvas> element exists.

* feat(ui): show the blurhash while an album cover loads

* fix(artwork): hydrate cursor streams via an id pre-pass

The album, artist and playlist GetCursor built their own select and never
called hydrateArtwork, so every Jellyfin list endpoint (all six stream via
GetCursor) emitted entity-id image tags and no blurhash. Only GetAll
hydrated, which is why Subsonic and the native API were unaffected.

Each cursor now resolves its ordered/filtered/paginated id set with the
cheap id-only GetAllIDs query, then streams those ids in chunks through the
repo's existing GetAll, which already hydrates and applies the full select.
Max/Offset are consumed by the pre-pass alone; the chunk query carries only
the caller's filters, Sort and Order.

This also removes a pre-existing deep-pagination cost: keeping OFFSET out of
the joined query makes the pre-pass a covering index scan instead of paying
the library and annotation joins for every skipped row. Benchmarked on a
synthetic 100k-album DB with the real schema, page=500 at offset 90,000:
3.9ms via the id pre-pass, 52.5ms for the current shape, 192.7ms for a naive
join. An unpaginated full stream costs ~24% more, which is the trade.

GetAllIDs gains the annotation join whenever the caller's filters or sort
reference an annotation column (same gate CountAll uses), otherwise
Filters=IsFavorite and SortBy=PlayCount would fail in the pre-pass. The
playlist pre-pass repeats GetAll's columns so ORDER BY keeps resolving to
playlist.name rather than the joined user.name.

* fix(jellyfin): hydrate artwork on the song cursor

Jellyfin's listSongs streamed media files via GetCursor, which never
hydrates artwork, so songs emitted entity-id image tags and no blurhash.

media_file now uses the same id pre-pass as the other three cursors
(album/artist/playlist), for consistency, but on a separate method,
GetCursorWithArtwork: GetCursor itself must stay untouched, since it's
also the scanner's hot path and the scanner never reads artwork.

Measured on 1,000,000 tracks, the pre-pass over all ids costs +41.8 MB
heap and +298 ms versus GetCursor's bounded +0.0 MB. The Jellyfin path
is paginated, though, so in practice it only ever pre-passes a page's
worth of ids, not the full library, and doesn't pay that cost.

* feat(jellyfin): emit a song's own cover art when it differs from the album's

Real Jellyfin fills ImageTags from each item's own images before falling back
to the parent album, and Finamp checks imageTags.Primary before AlbumId. Our
mapper read only the album's image, so a track with distinct embedded art
silently showed the album cover.

Emit exactly one entry under ImageBlurHashes.Primary: Go marshals
map[string]string in sorted key order rather than insertion order, so a
second entry could pair the wrong blurhash with the image imageId resolves
to, and Finamp pins that pairing in its cache for 365 days.

* test(persistence): scope the GetCursorWithArtwork full-stream spec to tie-free ids

The fixture has title ties (e.g. three "Antenna" tracks), so the unscoped
positional comparison against GetAll only passed because SQLite's tie order
happened to coincide between the full scan and the pre-pass's id IN (...)
fetch. Scope it to onlySongs like the sibling ordering specs already do.

* refactor(artwork): route song own-art through primaryImageTag; align chunk size

Cleanups surfaced by /simplify: the song mapper's own-art branch reimplemented
primaryImageTag's tag+blurhash-map construction (and its one-entry invariant) — route
it through the helper so that invariant lives in one place. Tie artworkChunkSize to a
whole multiple of artworkBatchSize so a cursor page re-chunks into even hydration
batches. Hoist a duplicated imageLoading && blurHash boolean in the album grid.

* fix(ui): serve the placeholder for known-absent art instead of a broken icon

getCoverArtUrl returned '' for an imageAbsent record, so <img src={undefined}> rendered as the browser's broken-image icon on every absent cover. The server already serves a proper placeholder for absent art, so build the url and let it render.

* feat(ui): show the blurhash as the loading placeholder across cover surfaces

Add a shared CoverImage component (useImageUrl blob cache + blurhash + fade) and render the blurhash while a cover loads on the list thumbnails (CoverArtAvatar, radio) and the artist/album/playlist detail pages. The detail pages now go through CoverImage instead of a plain CardMedia, so their images come from the in-memory blob cache and survive React remounts without re-fetching. BlurHashCanvas gains an optional style prop.

* refactor(ui): unify list cover surfaces onto the shared CoverImage component

Route the album grid, CoverArtAvatar (artist/playlist lists) and the radio list's cover field through CoverImage instead of each carrying its own useImageUrl + blurhash-overlay wiring. CoverImage gains a default object-fit: cover. Radio keeps its uploaded-image gate and the generic radio placeholder for stations with no art.

* fix(ui): address CoverImage review findings

Restructure CoverImage so the size/shape lives on the root and the blurhash + image are absolute fills: the <img> mounts only once its blob is ready, so an unresolved cover never flashes a broken <img>. Add a fit prop (default cover) so album/playlist detail keep their letterbox instead of being cropped by a hardcoded object-fit. Remove the orphaned coverLoading styles and an unused subsonic import; add a CoverImage unit test.

* perf(ui): only refetch already-loaded records on SSE refresh

The artwork worker broadcasts a RefreshResource event per resolved chunk,
carrying every id in the chunk. useResourceRefresh was doing a getMany for
all of them, so any open list/detail page fetched hundreds of artists it
was not displaying. Filter the event ids to records already in the store;
the rest load fresh (with their new artwork) when navigated to.

* refactor(artwork): scale worker concurrency with CPU count

ArtworkWorkerConcurrency now defaults to max(2, NumCPU()/2) instead of a
fixed 4, mirroring MaxOpenConns: local resolution scales with the host but
stays at half the SQLite pool so it never starves the scanner/UI. External
RPS stays a fixed 2 — it gates third-party API calls and is bounded by their
tolerance, not the host, so it must not scale with CPUs.

Also drop the DevArtworkWorkerConcurrency/DevArtworkExternalRPS deprecated
aliases: those names were never released, so there is nothing to migrate.

* feat(artwork): re-queue an absent cover when its page is viewed

serveEntity now schedules a Bump recheck for an entity whose art was recorded
absent, so viewing a missing cover re-triggers resolution (e.g. after an
external source that was down during the scan comes back), matching the
request-time bump that already covers never-resolved entities.

Throttled by attempted_at against requestRecheckAge (1h) so repeatedly opening
a genuinely-absent page can't hammer external services. EnqueueBump preserves
an existing failed-state backoff via MAX(priority,...) and inserts a fresh,
immediately-eligible recheck for a settled-absent row (whose queue row was
already deleted).

* refactor(artwork): move ImageUploadService to artwork.Uploader

Relocate the image-upload service from core to core/artwork as
artwork.Uploader, co-locating it with the resolver/worker/serving that own
the artwork state it invalidates. MaxImageUploadSize moves too — its only
callers are the two image-upload handlers — which lets core/image_upload.go
be deleted entirely.

Extract the shared "clear resolved state + re-queue at Bump" invalidation
into artwork.Refresh and fold nativeapi's refreshArtwork handler onto it,
removing the duplicated DeleteForItem+Enqueue block that had drifted into
three places.

The wire provider moves from core's set to artwork's; the
playlists.ImageUploadService binding moves to the top-level injector so
core/artwork stays unaware of playlists. Behavior is unchanged.

* refactor(artwork): thread model.Kind through the artwork API

Entity-level artwork queries now take a typed model.Kind instead of a bare
prefix string. GetItemArtwork, DeleteForItem(s), GetInfoForItems,
EnqueueStaleAbsent, hydrateItemImages, enqueueBackfillKind and artwork.Refresh
convert to the prefix string only at the two real boundaries: the SQL
item_kind column (kind.Prefix() inside each repo) and external string inputs
(a new model.ParseKind for the nativeapi URL param, which also validates it).

The Backfill/stale-absent kind slices, the resolve.go dispatch switch, and the
kind→resource / kind→table lookup maps now use the Kind vars directly. The
queue lifecycle methods (MarkFailed/Delete*) keep string kinds — they operate
on a dequeued item's raw ItemKind column, which stays a string field, always
populated via kind.Prefix().

Removes every bare "al"/"ar"/… prefix literal from non-test code (27 -> 0);
behavior is unchanged.

* tune(artwork): drop backoff base from 5m to 15s

The exponential retry (base × 4^attempts, cap 48h) started at 5 minutes, so a
single transient failure — a timeout under load, an external blip — parked a
cover for 5 minutes even though a retry seconds later would have resolved it.
Start at 15s instead: transient failures recover almost immediately (15s → 1m
→ 4m → 16m …), while persistent failures still escalate to the 48h cap (now at
the 8th attempt instead of the 5th).

* tune(artwork): 5s backoff base + 12h give-up, drop the cap

Retry backoff now starts at 5s (was 15s) so a transient failure recovers on
essentially the next drain, and jitter widens to ±40% so a wave of correlated
failures doesn't re-clump into one poll.

Add a 12h give-up budget measured from enqueued_at: once the next backoff would
land past it, the worker stops retrying instead of grinding at a cap forever. A
bare failure settles absent (handed to the 24h stale-absent sweep, and still
recoverable on a page view); a found-stale keeps its already-served art. The
budget bounds the tail, so the separate 48h backoffCap is removed.

* fix(lastfm): match album.getInfo on name+artist only, not MBID

Last.fm's album.getInfo by MBID is unreliable: a correct MBID can return a
different album, or none. Observed with black midi's "7-eleven" (whose correct
MBID returned a FLEETWOOD release) and both missing The Chats albums (one MBID
404s, the other resolves to a different self-titled release). The worker then
recorded covers absent — or would fetch the wrong art — even though the correct
cover is on Last.fm by name+artist.

Stop passing the MBID to album.getInfo; query by name+artist only, which also
drops the now-dead error-6 MBID-retry fallback. The low-level client keeps its
MBID support for other callers; only the album lookup changes.

* fix(lastfm): return agents.ErrNotFound on error 6 (not found)

Last.fm returns error 6 for a missing artist/album — a definitive negative —
but the agent returned the raw *lastFMError, so the artwork worker treated
every not-found as a real fault: it counted toward the per-source circuit
breaker (5 in a row opens it, fast-failing all Last.fm calls including valid
ones) and was retried as a transient error instead of settling absent. On a
first scan of a library with many artists Last.fm lacks, this stalled valid
cover lookups and left entities churning in backoff.

Translate error 6 to the shared agents.ErrNotFound at the agent boundary
(callAlbumGetInfo / callArtistGetInfo), matching how the Deezer agent maps its
client's not-found, and log it at Debug instead of Error — which also removes
the not-found log spam.

* feat(artwork): log external image-lookup failures at debug

The worker's res.reader==nil && extError branch returned outcomeFailed with no
log, so a failing external cover lookup (agent error, dead image URL, download
timeout) was undiagnosable. Log the agent, entity, and underlying error at the
fetch site where it's in hand — this surfaced a Last.fm album.getInfo returning
an image URL that itself 404s.

* fix(artwork): treat a 404/410 image URL as not-found, not a transient fault

An agent (notably Last.fm's album.getInfo) can advertise a cover URL that is
itself dead — a 404. sources.go's fromURL returned a generic error for any
non-200, so a dead URL was treated as a transient failure: it churned in
backoff and counted toward the circuit breaker, stalling valid lookups.

Map 404/410 to model.ErrNotFound in fromURL so a dead URL settles absent, and
collapse the near-identical fetchPlaylistImageURL (which already did this for
M3U covers) into it.

* feat(artwork): make artwork re-resolution targeted, not blunt

Two gaps in when the pipeline re-resolves artwork:

The recheck job only requeued absent-state rows (hash=''), so an entity that was
never processed — added between scans, or on a server with the scanner disabled —
had no periodic safety net and stayed without artwork indefinitely. Add
EnqueueMissing(kind): a SQL set-difference enqueueing entities with no
item_artwork row at Recheck priority (ON CONFLICT DO NOTHING, so it never
disturbs a queued row). Run it once at startup and hourly alongside the
stale-absent recheck. Rename staleAbsentKinds -> recheckKinds accordingly.

Conversely, the config fingerprint included consts.Version, which embeds the git
SHA and so changed on every build, re-enqueueing every entity in the library
(~34k here) and re-querying external agents at the configured RPS for anything
without local art. Replace it with an explicit artworkEpoch constant, bumped
deliberately when resolution semantics change. The cases that motivated the
version input — absent art becoming available — are already covered by the
stale-absent and missing-row rechecks; only a corrected wrong-pick needs the
epoch. A test guards against reintroducing the version.

* test(artwork): restore resolution edge-case e2e coverage

The serving cutover removed the album/disc/artist/mediafile/playlist/radio e2e
specs that documented the folder-selection rules and guarded the #5376/#5456/
#5451/#5457 regressions; nothing replaced them, so compareImageFiles and the
parent-fallback logic were left untested.

Restore them driving the real pipeline: a real scanner populates the folder
graph from an in-memory library, the real Worker drains the queue, and the real
Service serves. Folder-backed art is file-backed (served via os.Open, which the
in-memory FS can't satisfy) so its selection is asserted on the persisted state
row; store-backed and real-disk sources are asserted byte-for-byte. Single-disc
disc resolution now serves album art directly, so only multi-disc disc scenarios
are ported.

* fix(artwork): run disc resolution for single-disc albums too

ed4178a6 gated serveDisc on len(album.Discs) > 1, claiming parity with the legacy
reader. The legacy reader has no such gate: artwork.go dispatches every dc- id to
newDiscArtworkReader, whose Reader() walks DiscArtPriority unconditionally.

The gate also lost art. For a single-disc album whose only image is disc1.jpg,
the disc request skipped the chain and fell through to album art, which does not
match CoverArtPriority — so tracks tagged disc 1 (whose CoverArtID is a dc- id)
served nothing at all, where before they served disc1.jpg.

A single disc can legitimately have its own cover, distinct from the album's, and
DiscArtPriority is what expresses that preference. Drop the gate and restore the
single-disc e2e scenarios that covered it.

* fix(artwork): register the GIF decoder in core/artwork

The deleted artwork.go carried blank imports for image/gif and
x/image/webp. WebP came back via resize.go's gen2brain/webp, which
self-registers, but GIF did not: core/artwork claims GIF support in
mimeForFormat and extForMime while relying on an unrelated server
package to have imported the decoder.

The guard lives in the e2e suite because that test binary has no other
image/gif importer; a spec in core/artwork would pass regardless, since
animation_test.go imports the package non-blank.

* fix(artwork): never record absent after a local I/O failure

Local sources swallowed their open errors, so a stale NFS/SMB mount was
indistinguishable from "this entity has no artwork": the chain returned
no reader, processItem took the absent branch, and the upsert replaced a
good content hash with the empty string. Clients then saw a placeholder
until the 1h request recheck or the 24h stale-absent sweep, and the
orphaned bytes became eligible for the next prune.

A candidate the resolver knows about — a file in the folder listing, a
track's own audio file — failing to open is not evidence of absence, so
it now forces a retry the same way an external agent error does.

* fix(artwork): keep served art when the retry budget runs out

Exhausting the 12h budget called writeAbsent unconditionally, so an
entity whose art was already resolved and serving lost it to a long
upstream outage: the hash went empty, clients fell back to the
placeholder, and the now-unreferenced bytes were freed by the next
prune even though nothing about the image had changed.

Exhaustion means the source stayed unreachable, not that the cover
disappeared, so absent is now recorded only when there is nothing to
keep.

* fix(artwork): restart the retry budget on re-enqueue

The conflict clause updated only priority and retry_at, so a row that
already existed kept its original attempts and enqueued_at. The worker
measures the 12h give-up budget from enqueued_at, so any row that had
been pending across a longer gap — a server left off, an upgrade, a
laptop asleep — gave up on its very first attempt and settled absent.

The manual re-resolve endpoint is the sharpest case: it clears artwork
state and re-queues, but inherited the old row's spent window, so a
deliberate retry got one shot. A fresh request now gets a fresh budget,
with the mock updated to match.

* fix(artwork): keep not-found distinct from artwork-absent

GetOrPlaceholder folded model.ErrNotFound in with ErrUnavailable, so an
id matching no entity returned 200 and the placeholder PNG. That made
the ErrorDataNotFound branch in getCoverArt unreachable: Subsonic went
from error 70 to a successful placeholder, and Jellyfin's Primary image
endpoint from 404 to 200. Neither is ours to change.

An entity with no art and an id with no entity are different answers;
only the first is a placeholder.

* fix(artwork): make the prune sweep cancellable

Sweep walked the whole store with no context, and RunPrune holds the
prune write lock for its full duration. In-flight acquisitions park on
the read lock, drain's WaitGroup never returns, and Run never reaches
its ctx.Err() check — so a SIGTERM during a daily prune over a large
store on slow storage waits out the container's grace period and dies
mid-remove.

* fix(artwork): hydrate the tracks reached through a playlist

loadTracks and the playlist-track cursor were the only entity-page
paths that never hydrated artwork state, so a song reached through a
playlist behaved differently from the same song in the songs list:
Subsonic emitted a hashless coverArt id, which imghttp downgrades to
no-cache, and advertised art even for known-absent albums; Jellyfin
emitted AlbumPrimaryImageTag as the bare album id — a tag that never
changes when the cover does — and no blurhash at all.

The media-file hydration moves next to the other hydration helpers so
both paths share one implementation rather than growing a third.

* feat(ui): cross-fade the cover over its blurhash

The blurhash unmounted the moment the blob arrived, so the placeholder
vanished a frame before the image painted. The image now mounts
transparent and fades in over the blurhash, which stays behind it until
the fade completes. A blob already cached when the instance mounts
skips the fade, so a remount does not re-animate.

* fix(ui): retire the blurhash on a timer, not transitionend

Under prefers-reduced-motion the img rule sets transition:none, so
toggling opacity fires no transitionend and the handler that unmounts
the blurhash never ran. The placeholder stayed mounted for the life of
the component — visible in the letterbox bars wherever the cover is
rendered with fit="contain", and a live canvas per tile everywhere else.

One duration constant now drives both the CSS transition and the timer,
so they cannot drift.

* fix(artwork): stop advertising a hash for bytes that won't be served

Hydration stamped the album's hash and blurhash onto an embedded-eligible
track that had no state row yet. Serving takes provisionalEmbedded for
exactly that case and returns the track's own embedded image, so the id
carried a content-version belonging to a different picture: every such
request fell back to no-cache instead of immutable, and a client keying
its cover cache on the blurhash paired the album's with the track's art.

AlbumCoverArtID had the mirror-image problem, building the album id from
the track's own ItemImage. It happened to work only because hydration
overwrote ImageHash in precisely the fallback cases; a track with its own
resolved art would have stamped that hash onto the album's id.

* perf(artwork): precache from the bytes just acquired

Warming the resize cache re-read the two rows and the file the
acquisition had just written, so every acquired image cost two extra
queries and a second full read of a file whose bytes were still in
memory. processItem now hands back what it persisted and precache warms
from that, under the same cache key the serving path computes.

Resolving the admin user also moves behind the empty-queue check: it is
needed only to resolve private playlists, so an idle server no longer
runs a user lookup on every poll.

* perf(artwork): keep the worker pool fed across a drain

The pool was fed from a batch sized to the pool itself (2x concurrency)
with a WaitGroup barrier before the next dequeue, so one item burning
its external timeout idled every other slot until it finished. The
legacy cache warmer had no such barrier: it streamed through a pipeline
of 4.

Dequeuing well past the pool keeps the slots fed for the whole pass at
no extra cost, since DequeueBatch does not mark rows taken and was
already one query per pass. Acquiring a slot now also observes
cancellation, so a larger batch cannot delay shutdown.

* perf(artwork): drain local and external artwork in separate pools

A first backfill enqueues artists before albums at a single priority, so
the drain took them in that order. Artists resolve through a
rate-limited agent, and gate() waits for its permit while holding a
worker slot, so the whole pool sat asleep in the limiter with every
album queued behind it.

Measured on a 96k-track library (29,115 artists to 6,949 albums, 4:1):
zero albums resolved in seven minutes, and roughly 3.3 hours before the
first album cover would have appeared. Splitting the drain gives each
class its own slots: albums now finish in under eight minutes while
artists trickle at the same 2/s they were always limited to.

The two budgets are carved out of MaxOpenConns so a second pool cannot
take connections the scanner and the UI need. Dequeue filters by kind,
and the drain index leads with item_kind so each pool seeks to its own
work instead of scanning past the other's backlog.

* fix(artwork): treat an unreadable upload as a failure, not a miss

resolveLocalFile swallowed every os.Open error, so uploads, playlist
sidecars, a local M3U image and the artist image folder still had the
bug that was fixed for folder and embedded sources: a permission or
transient I/O error on a file that exists read as "no image here". The
worker then settled the item absent and dropped its queue row.

Uploads outrank every other source, so an unreadable one now stops the
chain rather than letting a lower-priority image be persisted in its
place. A genuinely missing file stays a clean miss.

Reported by Codex on #5847.

* fix(artwork): make the pool-split worker test race-clean

CI runs the suite under -race, which the local `make test` does not, so
this only showed up there: 230 specs passed and the detector still
failed the run.

The drain-pools spec started Run and never waited for it, so pool
goroutines outlived the spec and raced the config snapshot Ginkgo
restores on cleanup. It now cancels, unparks the blocked lookups and
waits for Run to return.

Two test doubles also had to become concurrency-safe, since the spec is
the first to resolve several artists at once: fakeImageAgent's call
counters, and MockAlbumRepo.GetAll, which records the last query options
on a read path. MockDataStore's lazy accessors get the same treatment —
only MediaFile was guarded before, and two pools now reach them
concurrently. ArtworkQueue takes an unlocked helper for its internal
Artwork call, since repoMu is not reentrant.

* perf(artwork): stop reading and hashing disc art on every request

The resize-cache key was the content hash, which cannot be computed
without reading the file, so a warm cache never prevented the I/O: every
sized disc request read up to 20MB and hashed it before the lookup. The
legacy reader keyed on the id and the album's mtime and touched the file
only on a miss.

Disc art has no state row and therefore no stored hash, so the key is
that same identity — id, album mtime, DiscArtPriority — and the
selection chain now runs only when the cache misses. Full-size requests
stream the source instead of buffering and hashing it.

This matters more now that single-disc albums keep running the disc
chain, which puts every disc-tagged track without embedded art on this
path.

* fix(artwork): key disc art on folder image changes, not just the album

The identity cache key used album.UpdatedAt alone, which a replaced
disc image does not necessarily move — the sized response would then
serve the old image indefinitely. The legacy reader folded ImportedAt
and the folder's ImagesUpdatedAt into its key for exactly this reason,
and loadAlbumFoldersPaths already returns that timestamp; the disc
reader was discarding it.

* fix(artwork): return undispatched items when a drain is cancelled

claim() reserves the whole batch before dispatch, but the cancellation
path returned without releasing what it had not yet started, leaving
those items in the in-flight set permanently — no later drain could
claim them again.

Harmless until the batch grew past the pool size; now a cancel strands
up to a full batch. The e2e harness cancels mid-drain after every
acquire, so it surfaced there first: one spec timed out waiting for an
item that had been claimed and abandoned, and the suite went from 59s
to 87s on CI.

* fix(jellyfin): make a track's own cover reachable for Jellyfin clients

Media files are never enqueued — the scanner drops their state without
queueing them and the recheck kinds exclude them — so an unresolved
track keeps an empty ImageHash and SongToBaseItem always fell through to
AlbumPrimaryImageTag. Finamp then asks for the album image, nothing ever
requests mf-, and the read-through that resolves the track never fires:
the own-cover branch was unreachable for Jellyfin-only users.

An eligible, unresolved, not-known-absent track now advertises its id as
the Primary tag, which is what makes the client ask. The request serves
the embedded art and queues the track so the worker persists a real
hash. No blurhash is sent, since none exists yet and a fake would be
cached against that tag forever.

Serving gains the album fallback that made this safe to advertise: an
eligible track whose frame will not extract now falls back the way
CoverArtID does instead of answering with a placeholder.

Reported by Codex on #5847.

* fix(artwork): treat an unreadable artist-folder image as a failure

Third and last site in this class: findImageInFolder logged and skipped
an image the glob had already matched, so a permissions or mount failure
during the artist-folder traversal read as "no image here" and let
processItem settle the artist absent, discarding any artwork already
resolved.

A matched-but-unreadable file now propagates through fromArtistFolder
and lands as localError, the same as album folder art, embedded art and
uploads. A folder with no match stays a definitive miss.

Also normalizes the e2e path assertions with filepath.ToSlash: the
stored SourcePath is OS-native, so the forward-slash suffixes failed
all 23 folder specs on Windows.

Reported by Codex on #5847.

* fix(artwork): give full-size disc art a real ETag

Regression from 04d5a556. Keying the resize cache on identity meant the
disc response no longer carried a content hash, and the full-size branch
set no ETag either — so WriteImageHeaders fell back to the empty hash
and emitted `ETag: ""` for every full-size disc image. Since ifNoneMatch
compares the unquoted value, a client echoing that back matched, and got
a 304 even after the image was replaced.

The full-size branch now carries the same identity validator the sized
branch uses, so it moves when the folder's images change.

WriteImageHeaders is hardened against the class as well: an empty
validator is no validator, so it is neither emitted nor matched.

Reported by Codex on #5847.

* test(artwork): inject the unreadable source instead of chmod

os.Chmod cannot revoke read access on Windows — it only toggles the
read-only attribute — so the findImageInFolder spec opened the file
happily and failed there, and the upload spec passed for the wrong
reason: outcomeFailed came from the 1-byte payload failing to decode,
not from the source being unreadable.

findImageInFolder takes an fs.FS, so the failure is now injected and
the spec is filesystem-independent. The upload path goes through
os.Open directly and has nothing to inject, so it skips on Windows
rather than pretend to cover it.

* fix(artwork): compare the pixel cap without multiplying

Defence in depth rather than a live hole: the reported crafted PNG
(0xffffffff square) never reaches the multiplication, because
image/png rejects it at DecodeConfig, and the largest dimensions any
supported format can declare — 2^30-1 for PNG, 16-bit for JPEG and
GIF, 14-bit for WebP — cannot overflow the int64 product.

decodeCapped is format-agnostic though, so the guard should not depend
on a decoder's own limits staying where they are. Comparing by division
holds for any dimensions a decoder might report, and non-positive ones
are now rejected outright.

* refactor(ui): rename cover artwork components

* fix(ui): remove Artwork rendering gate

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(cache): re-fetch when a cache entry outlives its data file

fscache's Remove drops the in-memory entry, releases the lock, and only then
unlinks - blocking until every outstanding reader closes. A Get landing in that
window re-creates the file at the same path under a fresh entry, and the deferred
unlink deletes those new bytes. The entry survives pointing at nothing, and since
a present entry is treated as a hit, every later Get for that key returns ENOENT
for the rest of the process's life. Only a restart, which rebuilds the map from
disk, cleared it.

Get now drops such an entry and retries once, so a vanished data file costs one
re-fetch instead of poisoning the key permanently. This also covers a file
disappearing for reasons unrelated to that race, such as external deletion or a
restored backup.

Specs cover an in-process entry, one adopted at startup, and the deferred-removal
race itself.

* fix(artwork): log why a sized cover fell back to the placeholder

serveHash routed every non-cancel cache error into dangling(), which returns
ErrUnavailable and is then rendered as a placeholder at 200 OK. A cache-layer
fault was therefore indistinguishable from an album genuinely having no artwork,
and left no trace: a broken resize cache silently served placeholders for a
quarter of the library while the logs stayed clean.

Log the error before falling back, so the cause is recoverable from the logs.

* fix(artwork): precache the cover variant the UI actually requests

precache built its resizedItem without setting square, so it warmed
h-<hash>.<size>.false.<quality>. The list surfaces - album grid, artwork avatars,
playlist and radio details - all request square covers, so the warmed entry was
never read and every grid cover stayed a cold miss on first view.

Set square on the precache item so the key matches the request path. The existing
specs asserted the '.300.false.' key and were updated accordingly.

* fix(cache): give a re-created cache entry its own file

Create re-opened the path with O_TRUNC, which shrinks the file out from under an
older stream that may still be serving readers. stream.Reader then hits EOF from
the OS at the new, shorter length while the broadcaster still reports the original
size, so Wait() reports 'more data exists' and the reader retries forever - a tight
pread loop that burns a core and never releases its handle, which in turn blocks
Stream.Remove() indefinitely.

Unlink first and create with O_EXCL so the new entry gets a fresh inode. Existing
readers keep their descriptor on the old inode, see its full contents, and reach a
clean EOF.

Note this does not address the deferred unlink deleting the re-created file, which
is handled separately by the re-fetch in fileCache.Get.

* fix(cache): keep the in-place truncate on windows

Unlinking before re-creating fixes the premature-EOF spin on unix, but Windows
refuses to remove a file another handle still has open and returns a sharing
violation. Because Create surfaces that error, every cache miss on a path with a
live reader would have failed outright - worse than the spin it was meant to fix.

Split the create behind a build tag: unix unlinks for a fresh inode, Windows keeps
truncating in place and stays exposed to the spin, which is the behaviour it
already had. The unix-only spec is skipped there.

* fix(artwork): shape the blurhash placeholder to the artwork's aspect ratio

The UI decoded every blurhash into a 32x32 bitmap and stretched it to fill its
container, so a non-square cover showed a full-box blur that collapsed into a
letterboxed image the moment it loaded. On the album detail page the
placeholder overhung the image by a third of the box height.

A blurhash string carries no aspect ratio of its own, so the dimensions have to
come from the server. artwork.width/height were already stored and read by
nobody; they now surface on ItemImage as imageWidth/imageHeight, hydrated
through the join that was already in place. Existing rows already carry them,
so no migration or rescan is needed.

A square request is padded rather than cropped, which aspect-fits the content
inside the square the server returns. That made the grid a second instance of
the same bug, so `square` now implies contain for the image as well as the
placeholder, instead of the two renderers reading it differently.

* feat(jellyfin): expose PrimaryImageAspectRatio

Real Jellyfin carries width/height of the Primary image on BaseItemDto
(MediaBrowser.Model/Dto/BaseItemDto.cs), attaching it only when the request's
Fields asks for it (DtoService.cs ContainsField). The dimensions are now on
model.ItemImage for the web UI's blurhash placeholder, so the adapter can
report the same thing for free.

Gated behind Fields to match, and omitted rather than defaulted when the item
has no image or unknown dimensions: real Jellyfin falls back to a per-type
default of 1 for music, but a wrong ratio mis-shapes a client's placeholder,
and we only lack dimensions when the artwork is genuinely unresolved.

primaryImageTag becomes primaryImage, returning the tag, blurhashes and ratio
together, so the choice of which image is Primary is made once per mapper
rather than the same ItemImage being threaded through two calls.

ArtistToBaseItem and PlaylistToBaseItem take Fields now, like the album and
song mappers already did.

* refactor(model): give ItemImage an AspectRatio method

The zero/absent guards around width/height are ItemImage's own invariant, not
the Jellyfin adapter's. Moving them onto the model keeps one definition for
every consumer, so a second one cannot quietly disagree about what an unknown
ratio means.

* fix(ui): anchor detail pages to the top when opened from a list

React Router keeps the previous page's scroll offset, so opening an album from
a scrolled list started the detail page mid-song-list. Artist pages had the
same bug; it just shows less because the artist list is rarely long enough to
scroll far.

Keyed on the record id rather than mount, so detail-to-detail navigation (an
album's artist link) resets too, and so the scroll waits for the record instead
of firing against an empty page.

* fix(ui): stop the Random album grid collapsing on every keystroke

The grid was replaced by a spinner whenever the random list was loading, so
each search keystroke collapsed it to spinner height and back. That blanket
blanking is the flicker commit 9e559311a removed for every other list; random
kept the exception so a re-roll would not flash the roll it is replacing.

Blank on a seed change instead of on any load: a re-roll gets a new seed and
still blanks, while a search keeps the seed and leaves the grid in place. The
seed is tracked from empty rather than from the current value because a re-roll
redirects and remounts the grid, which would otherwise look already-settled
with the previous roll still on screen.

Same rule for the pagination, which was hidden on the same condition.

* refactor(artwork): move fingerprint property key const to `consts` package

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(tests): enhance database handling with resettable tables and truncation

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(artwork): narrow the prune lock and drop redundant in-flight tracking

The prune read-lock wrapped all of processItem, including external fetches under
their own timeout. Since a pending RWMutex writer blocks new readers, one prune
arriving behind a slow provider stalled every subsequent item in both drain
pools. Extract persist() so the lock covers only the window it protects: store
placement plus the two row writes.

The in-flight set guarded against a queue row appearing twice in one batch, but
artwork_queue's primary key makes that impossible, drains are serial per pool,
and the pools' kind lists are disjoint. Removing it also retires the cancellation
unwind loop that existed only to release those claims.

* fix(artwork): never settle absent for a kind no recheck job revisits

The 12h retry budget hands a bare failure to the periodic stale-absent
sweep, which is what makes the resulting absent row recoverable. Media
files are deliberately excluded from that sweep -- they resolve embedded
only, at scan or on view -- so exhausting the budget on a transient read
error recorded a "this track has no cover" verdict that nothing would
ever revisit.

Settle absent only for kinds a recheck job covers. Without a row the
track stays unresolved, so the next view re-enqueues it.

* refactor(artwork): remove dead plumbing from the serving path

artworkReader.LastUpdated had no callers: invalidation rides entirely on
the cache key, so the interface member, the resizedItem field and its
four assignments were vestigial. Reader's second return value was
likewise discarded at all three call sites.

resizedItem.Key duplicated representationTag's format string over
identical inputs, where drift would serve a wrong-keyed entry under a
right-looking validator; it now derives from it. newResizedItem had one
caller and a doc comment claiming a sharing with worker.precache that
never existed -- precache builds its own literal.

Also unexport Prune, which no caller outside the package used while
RunPrune documented itself as the only sanctioned path, drop a
single-call placeholder wrapper, and delete five fakeFolderRepo fields
no spec ever set.

* refactor(artwork): drop queue repository methods only tests called

MarkFailed and Delete had no production caller: the worker only ever uses
MarkFailedIfUnchanged and DeleteIfUnchanged, which refuse to act on a row
a concurrent scan re-enqueued. Keeping the unconditional pair meant the
interface offered the racy variant under the more obvious name.

MarkFailedIfUnchanged does not build on MarkFailed, so nothing in the
implementation needed them either. The repository tests used them to put
a row into a backed-off state; they now do that directly.

* test(artwork): pin that a request never fetches or samples album art

resolveItemLocal's guard against the remote ExternalImageURL fetch and
the 2x2 grid had no coverage: deleting it left the whole suite green
while putting synchronous network calls on the request path.

The worker resolving the same playlist is asserted alongside, so the
spec cannot pass by simply resolving nothing.

* refactor(artwork): give the resolver a receiver and one capability field

The resolve* chain walkers each took seven parameters -- ds, agents,
ffmpeg, gate, localOnly -- while the package already had workerDeps
bundling the same collaborators for processItem. They are now methods on
a resolver.

The external capability is one nilable field instead of three values
that had to agree. Previously a local-only resolution passed agents=nil,
gate=denyGate and localOnly=true, and only the localOnly check actually
protected anything: the external branch dereferences agents in the loop
header, before the gate closure runs, so denyGate could never fire. It
is deleted. A nil ext now both marks the resolution local-only and
removes the agents there were to dereference, and newLocalResolver takes
no parameter that could supply one.

The playlist tile loop hardcoded localOnly=false, safe only because an
early return 22 lines above it made that unreachable; it now inherits
the resolver's capability.

* refactor(artwork): funnel every served representation through one path

serveHash, serveBytes and serveDisc each hand-copied the same five steps
-- test for full size, stream or build a resizedItem, call the cache,
wrap with a validator -- with a different error policy bolted on. The
ETag rule was restated at four sites and applied inconsistently.

serveSource now states it once: full size streams open() directly, and
an ETag is attached only when the bytes are resized or there is no hash
to validate against. Each caller keeps just its own error policy, and
serveBytes folds into its single caller.

Two behavior changes fall out, both narrowing an aborted request's blast
radius: serveDisc propagates context.Canceled instead of falling back to
a full album resolution, and serveHash's full-size path propagates it
instead of going dangling, which would have enqueued a re-resolution for
a request nobody is waiting on.

* style(artwork): use one log prefix, spelled the way the codebase does

The package logged under three spellings of its own name -- "artwork: "
lowercase, "Prune: " and one "Artwork: " -- and the lowercase ones
carried lowercase message text, against 568 capitalized to 48 lowercase
elsewhere.

Prefixing itself is the convention here (Scanner:, API:, Watcher:) and
it earns its place: DevLogSourceLine is off by default, so without it a
line does not say which subsystem emitted it. So this normalizes the
spelling rather than dropping the prefix. Error strings stay lowercase
and unprefixed per Go convention.

* refactor(artwork): give workerDeps only what the processor uses

The bag carried cache, which processItem never reads and only the
worker's precache uses, and carried agents/ffmpeg/gate solely to
reconstruct a resolver on every queue item. cache and ffmpeg move to
Worker, where precache actually uses them, and the resolver is built
once in NewWorker.

persist's hash parameter was redundant: decodeArtwork sets Hash and
GetImage selects it, so art.Hash already holds it on both paths.

The type itself now lives beside Worker, which owns it, rather than in
the file of the function it is passed to.

* refactor(artwork): make acquisition a processor with its own receiver

workerDeps was a parameter bag threaded into two free functions that
nothing outside the worker calls. It becomes the processor type, with
processItem and persist as acquire and persist methods on it, and Worker
holds one collaborator instead of reaching through a bag.

Kept as a separate type rather than folding onto Worker: acquisition
takes a queue item and returns bytes, while Worker.process settles the
queue row around it. That boundary is what keeps retry policy out of the
image pipeline, and what lets the acquisition specs build a three-field
value instead of a Worker with drain pools, gates, a broker and a
real on-disk cache.

* refactor(artwork): collect the external gate contract in one file

gateFunc, passthroughGate and isTransientExternal sat in agent_images.go
while every implementation lived in worker.go: extGate, breaker,
Worker.gate, gateFor. isTransientExternal even carries a comment saying
it must stay consistent with breaker.record, which was in the other
file -- a rule spanning two files with only a comment holding it
together.

Pure move into gate.go: no symbol added or removed.

* refactor(artwork): put the whole playlist grid in playlist_cover.go

decodeTile and assembleTiles were in resolve.go while the geometry they
depend on -- rect, fillCenter, tileSize -- was in playlist_cover.go and
used nowhere else, so one file held the grid's helpers and another its
assembly.

Pure move.

* refactor(artwork): move resizedItem next to the interface it implements

resizedItem is the only implementation of artworkReader, which is
declared in image_cache.go, and it is used by the worker's precache as
well as the serving path -- so worker.go was reaching into serving.go
for a cache type. representationTag stays in serving.go, where the
HTTP validator belongs.

Pure move.

* refactor(artwork): fold Refresh into housekeeping

refresh.go was a 21-line file for one function that clears artwork state
and enqueues -- the same thing Backfill, EnqueueStaleAbsentAll and
EnqueueMissingAll already do next door.

Pure move.

* refactor(artwork): accumulate priority-chain state in one place

Every source in the album and artist chains repeated the same five
lines: stamp the accumulated external failure onto a hit, or OR the
local fault into the running total on a miss. Each new source was a
chance to forget the OR, which is how the local-I/O-settles-absent bug
happened.

chainState.try does both, so each case drops to three lines and the
omission is no longer expressible. Semantics are unchanged: a hit still
carries extErr only. Also drops localErr from resolvePlaylist, which
declared it but never assigned it.

* refactor(artwork): expose housekeeping through the Worker

scheduleArtworkHousekeeping received a *artwork.Worker and then called
CreateDataStore() for a second handle onto the state that Worker already
owns, because Backfill, EnqueueStaleAbsentAll and EnqueueMissingAll were
free functions taking a DataStore.

They are now Worker methods over unexported implementations, the same
shape prune/RunPrune already uses: one public path, and the specs keep
calling the plain function with a mock store instead of standing up a
Worker. Fingerprint is unexported too -- nothing outside the package
used it.

* refactor(artwork): name the service for its domain, not its role

Every other core interface is named for what it is -- Playlists,
Library, Scrobbler, MediaStreamer -- while this one was artwork.Service,
the only X.Service in the tree. It becomes artwork.Artwork/NewArtwork,
and serving.go follows the type to artwork.go.

ProvideImageStore was likewise the only "func Provide" in the repo; it
is GetImageStore now, matching GetImageCache beside it. cmd/wire_gen.go
regenerated via make wire.

* docs(artwork): give each Worker housekeeping method its own godoc

The three methods shared one comment attached to Backfill, so godoc
rendered the other two undocumented and the one it did show described
the group rather than the call. Each now opens with its own name and
says what that call does, including Backfill's bool return.

* refactor(artwork): move fakeFolderRepo to artwork_suite_test.go

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(artwork): unexport artwork.HashImage function

* fix(log): stop ShortDur eating significant trailing zeros

TrimSuffix(s, "0s") was meant to turn "4h0m0s" into "4h", but it strips
any trailing "0s"/"0m" -- so 10s logged as "1", 20s as "2", 1m30s as
"1m3", 2h30m as "2h3", and a zero duration as the empty string. Every
elapsed/duration field in the app was affected.

The suffix now has to include the preceding unit, so only a whole
zero-valued component is dropped. The existing table only covered values
that dodge the bug (4m, 4h, 4m3s); added the ones that don't.

* feat(artwork): prefix every log message and time the slow steps

Prefix: 22 messages still logged unprefixed, so a line from this package
was indistinguishable from any other subsystem's. All 40 now carry
"Artwork: ", matching Scanner:/API:/Watcher: -- which earns its place
because DevLogSourceLine is off by default.

Timing on what can actually be slow: total per acquisition (on every
exit, failures included), the read that also covers the provider
download, hashing, decode+blurhash, resize, drain batch, precache,
prune, backfill, and the external agent call -- with the rate-limiter
wait counted separately, since a throttled agent and a slow one look
identical from the drain.

Debug coverage for states that were previously silent: dedup hit vs
decode, settling absent, serving a lower-priority source after an
external failure, retry scheduling with attempts and budget left, giving
up when the budget runs out, breaker open/close per agent, provisional
read-through, dangling state rows, and the mtime mismatch that makes art
appear to vanish. outcome gained a String() so it reads as a name.

* refactor(artwork): log decoded dimensions as fields, not a formatted string

fmt.Sprintf ran on every newly-decoded image even with Debug off, since
Go evaluates log arguments regardless of level. Separate width/height
fields also query better than a "300x300" string.

Correction to e0f1acd1a's message: it said "all 40" messages carry the
prefix. The package has 68 log call sites and 62 distinct messages; 40
was only what the test suite happened to exercise. The sweep itself was
complete -- zero unprefixed messages remain.

* fix(subsonic): stop serving artwork for a deleted radio

artworkAccessible checked every kind except radio, which fell through to
the default "no per-user access control" branch and returned true without
a lookup. Radio deletion removes only the entity row -- item_artwork and
the uploaded file survive until the next prune -- so the old ra- id kept
serving the removed radio's image for up to a day.

This is a regression against master, where newRadioArtworkReader loaded
the radio first and returned its error, so deletion took effect at once.
Radios stay globally visible; only existence is checked.

CreateMockedRadioRepo left Data nil, so its own Put panicked on first
use; initialized it.

Reported by Codex on #5847.

* fix(artwork): stop serving artwork for entities that no longer exist

Artwork state and its bytes outlive a deleted entity until the next
prune (@daily), and the serving path consulted only item_artwork, so a
Subsonic id or a signed public token kept serving a removed entity's
image in the meantime. Master's readers loaded the entity first, so this
was a regression.

The check goes in serveHash, the one path that can hand back a found
row's bytes: absent rows are already unavailable, and the provisional
and disc paths load their entity to resolve at all. Doing it there
instead of per-handler also settles who owns the invariant. Subsonic had
worked around it with artworkAccessible, whose comment described the
service "bypassing the library and private-playlist filters"; that
workaround is now deleted, since the service resolves through the
request-scoped repositories and enforces the filters itself.

Because those repositories are ctx-scoped, each caller says what it
wants by what it passes: Subsonic hands over the request context and so
gets visibility as well as existence, while the public image route
elevates like the Jellyfin one already did -- a token is the
authorization there, and a visibility check would hide a shared private
playlist, the very case shares exist for.

Two supporting fixes. albumRepository.Exists and mediaFileRepository
.Exists used the plain exists() helper, which applies no library filter,
so they reported rows in libraries the caller cannot see; they now count
through applyLibraryFilter as CountAll and artistRepository.Exists
already do. Neither had a production caller. RadioRepository gained the
Exists it lacked.

Tests follow the layers: the service refuses a found row whose entity is
gone, the repositories hide rows the caller may not see, and the
handlers only assert the context they hand over. Jellyfin needed no
change -- resolveArtworkID probes the entity tables, so a deleted item
yields an empty artwork id -- but that protection was incidental and
untested, so it is pinned now.

* fix(playlist): rebuild the generated cover only when the tracks change

The enqueue sat in refreshCounters, which Put also reaches for an
ordinary metadata update, so renaming a playlist or editing its comment
re-resolved the cover. The 2x2 grid samples albums with random(), so
that silently handed the playlist a different cover for an edit that
touched no tracks -- and refetched remote artwork to do it.

It now happens where the track set actually changes: addTracks (which
Put-with-tracks and updatePlaylist both funnel through) and renumber
(reached from removeOrphans). Creation still enqueues even with no
tracks, since an imported m3u can carry an ExternalImageURL.

Reported by Codex on #5847.

* style(artwork): trim verbose comments to the 1-2 line budget

Comments only; no executable code changed. Verified by comparing the Go
token stream of every touched file before and after: identical.

Removes 375 of the 1104 comment lines this branch added, targeting content
that belongs in a commit message or PR body rather than in the code:
rejected alternatives ("DeleteIfUnchanged, not Delete", "Waking all beats
routing by kind"), refactor history ("as the legacy reader did"), issue
references (#5798, #5597, #5376), benchmark numbers (~400ms, ~16k allocs),
and four persistence doc comments that duplicated the interface godoc in
model/artwork.go verbatim.

Comments predating this branch are left untouched.

The ASCII fixture trees in the e2e suites are deliberately kept above the
line budget: they diagram the fixture layout with its expected outcomes,
and every pre-existing block in those files carries one.

* test(artwork): make the artists-first backfill assertion non-vacuous

The follow-up loop could never fail: once the first "ar" index is asserted
to be 0, every non-"ar" element is necessarily at an index greater than 0.
A sequence like ["ar", "al", "ar"] passed both assertions, which is exactly
the interleaving the check exists to forbid.

Assert the partition directly instead: nothing after the first non-artist
call may be an artist. Verified by mutation — enqueueing artists a second
time after albums now fails the spec.

* refactor: use stdlib slices/maps and utils helpers in artwork code

Mechanical cleanups, no behavior change:

- 15 copies of the same id-extraction loop collapse to slice.Map (5 repo
  mocks, the scanner's track sweep, 4 wantIDs assertions) and slice.ToMap
  (6 index-by-id loops in the hydration specs).
- disc.go built a map[string]bool purely to dedup folder ids and then
  walked it back into a slice; slice.Unique says that directly.
- folders_artist.go's image filter is slice.Filter over model.IsImageFile.
- mock_artwork_repo deleted from a map while ranging it; maps.DeleteFunc
  states the intent.
- sort.Slice -> slices.SortFunc + cmp.Or; math.Min/Max -> builtin min/max;
  make+copy -> bytes.Clone; strings.Split -> SplitSeq on a per-request
  path; three-clause pixel loops -> for range.
- Reuse utils.BaseName where a stem was recomputed by hand. Not at
  playlist_cover.go:27: that path is a full OS path and utils.BaseName
  uses path.Base, which does not split backslashes.
- Drop a dead nil-guard in agents.go: getAgent returns a bare nil
  interface, and a type assertion on nil already yields ok == false.

cmp.Or was rejected for the gate fallback (func types are not comparable,
does not compile) and for ItemArtwork.AttemptedAt (cmp.Or compares
time.Time with ==, which includes loc; IsZero does not).

* refactor(persistence): collapse the four hydrateArtwork copies into one generic

album/artist/playlist/radio each carried the same eight lines, differing
only in element type and model.Kind. hydrateItems takes a ref callback
yielding an item's id and the ItemImage to fill, which is all that varied.

The len()==0 guards drop out: hydrateItemImages already short-circuits an
empty id list, and both loops are no-ops on an empty slice. applyItemImage
stays as-is; hydrateMediaFileArtwork and its own specs still use it.

* perf(scanner): stop reprocessing album and artist artwork on every full scan

A full scan re-imports every track, so the per-entity artwork enqueue in
persistChanges fired for every album and artist in the library — measured as
100% of both on a live instance, and ~8.5k artists / ~16.7k Deezer fetches on a
96k-file library. Re-importing a track is no evidence the art changed: artist
art has no track-content source at all, and the albums re-derived to identical
hashes across three consecutive scans.

Enqueue through EnqueueIfMissing on a full scan, which anti-joins item_artwork
so only entities that never resolved are queued. Incremental scans keep the
unconditional Enqueue, where a re-import does mean the file changed. Doing this
at the enqueue site rather than skipping it wholesale keeps a first scan filling
in covers as it walks, instead of stalling every cover until the scan ends.

EnqueueMissing grows a priority argument and runs once at end of scan, so an
entity phase 1 never saw still resolves, at Scan priority rather than dropping
to Recheck behind the backfill.

* refactor(artwork): derive blurhash components inside Encode

Components had a single caller, which only ever fed it the bounds of the image
it then passed to Encode. Exporting it gave callers two ways to get it wrong —
components mismatched with the image, or out of the 1..9 range — in exchange for
a knob nobody turned.

Derive them from img.Bounds() at the top of Encode and unexport the helper. The
counts must come from the pre-downscale bounds: downscale's integer rounding can
shift the ratio across a component boundary, and the hash is a client-side cache
key. Verified byte-identical over 18 hashes spanning 9 aspect ratios.

The out-of-range validation goes with it, being unreachable once the counts are
always derived. The aspect-ratio table now asserts through Encode's size flag,
which encodes (x-1)+(y-1)*9.

* refactor(ui): replace the blurhash package with a local decoder

The UI pulled in the `blurhash` dependency for one function, `decode`, called
from a single component. The decoder is ~80 lines of well-specified arithmetic,
so carrying a dependency for it costs more in supply chain and bundle than it
saves.

Equivalence was proven against the package before removing it: 84 hashes — three
real ones plus every component count from 1x1 to 9x9 — decoded at six sizes,
compared byte for byte, plus parity on which malformed inputs throw. Those pixel
values are now pinned in the spec, so drift from the reference algorithm fails.

The punch parameter is dropped rather than reproduced: no caller passes one, and
the package applies `punch | 1`, which silently turns a punch of 2 into 3.

* refactor: simplify the artwork enqueue and blurhash paths

Cleanup pass over the three preceding commits.

Tabulate the cosine terms in the UI blurhash decoder instead of calling Math.cos
per pixel per component: 248us -> 75us for a 32x32 decode, and an album grid
mounts one decoder per tile. Output is unchanged, which the pinned pixel specs
enforce. The Go encoder already tabulated the same terms.

Drop the dead paths that deriving components inside Encode left behind: the
zero-size guard in components, the post-downscale empty check, and the
no-AC-factor branch, which cannot be reached now that the counts are always at
least 1x9. The empty-image check moves ahead of the derivation, where it belongs.

In the queue mock, look up item_artwork by its existing iaKey rather than
scanning the map, and hold the lock across EnqueueIfMissing through a shared
unlocked helper instead of releasing it mid-operation. Extract the duplicated
drain-and-resolve block in the scanner specs into one helper.

* fix(artwork): refresh songs when their album's artwork changes

A track with no art of its own is served its album's, so hydration copies the
album's hash onto the track record. When an album resolution changed, the worker
broadcast only an `album` refresh, leaving song and now-playing surfaces holding
the previous hash-suffixed URL until something else refetched them.

Pair the album refresh with a song one. The dependent id list is unbounded — an
album has arbitrarily many tracks and a drained batch arbitrarily many albums —
so this refreshes the resource as a whole via the protocol's existing wildcard
rather than enumerating ids.

Reported by Codex on #5847.

* feat(persistence): log SQLite result codes on failed statements

SQLite reuses one message for errors that need different responses: "database
is locked" is both SQLITE_BUSY, which busy_timeout retries, and
SQLITE_BUSY_SNAPSHOT, which it can never retry because the transaction's read
snapshot is already stale. Reading only the message, the two are
indistinguishable, and a lock error seen in the wild could not be diagnosed
without guessing which one it was.

Add db.ErrorCodes to unwrap a sqlite3.Error and report its result and extended
result codes, and include them in the SQL error log. The helper lives in db
because that package already owns the driver, so persistence does not need to
import it. Constraint, readonly and disk-full errors share messages the same
way, so this applies to every failed statement, not just locks.

* fix(ui): keep the Random grid blank while a refresh re-rolls

Refresh bumps the list version, which changes the random seed and remounts the
grid. useRollChanged tracked the seed on screen in a ref inside the grid, so the
remount started it empty and adopted the new seed on the first render, while the
refetch had not begun and the store still held the previous roll. The grid
painted the old albums for the length of the request and swapped when the new
roll arrived.

Move the ref up to AlbumList, which a refresh does not remount, and pass it to
the grid and the pagination. The seed on screen then survives the remount, so a
refresh reads as a re-roll and blanks until the new roll lands. A search
keystroke keeps the seed and still leaves the grid in place.

* fix(ui): keep the album grid working outside the Random list

Hoisting the shown-seed ref into AlbumList made the prop mandatory in practice:
ArtistShow renders the same grid through ReferenceManyField and passes no seed
tracking, so useRollChanged dereferenced undefined and the artist page died with
"Cannot read properties of undefined (reading 'current')".

Own a ref in the grid when none is passed. A caller with no roll to track then
behaves as it did before, while the Random list keeps the ref that has to outlive
the refresh remount.

* refactor(config): make the artwork tuning options dev flags

ArtworkWorkerConcurrency and ArtworkExternalMaxRPS become
DevArtworkWorkerConcurrency and DevArtworkExternalMaxRPS, joining the
other DevArtwork* flags. Their defaults should not need tuning, so they
do not belong in the documented, user-facing option set.

* refactor(artwork): name the hashed image store folder for how it is addressed

The content-addressed store sat in artwork/store/, which did not
distinguish it from the artist/, playlist/ and radio/ upload folders
beside it — those hold artwork too. It is now artwork/hashed/, naming the
one property that sets it apart, and the path comes from a consts entry
rather than a bare literal, matching how the sibling folders are built.

Deliberately not under cache/: that folder holds resizes that rebuild
offline from a local source, while this one holds the only local copy of
externally fetched images, whose re-fetch depends on a third party still
serving them and whose bytes back the stored blurhash and dimensions.

No migration: anything left in the old artwork/store/ is orphaned and
re-resolved into the new location.

* refactor(artwork): call the album e2e helpers by their real names

album_test.go aliased expectAlbumFolderCover and expectAlbumAbsent to
shorter local names, which cost a lookup to resolve and hid the prefix
that distinguishes them from the artist and playlist helpers.

* test(artwork): cover the album-root and artist-folder path arithmetic

The unit specs for these helpers lived in the readers #5856 patched, both
deleted here, leaving the album-root promotion and the artist-folder climb
covered only end-to-end. A layout can show which image won but not why, so
these pin the parts behind it: that the parent is fetched only when it could
qualify as an album root, that a failed fetch propagates or degrades, and
that commonDir keeps a shared name fragment from reading as a shared folder.

Each spec was checked against a mutant: removing the library-root guard, the
other-album audio check, the single-folder short circuit, the single-root
climb, or commonDir's separator all turn one red.

Master's remaining specs were dropped as redundant — they cover sources this
branch already exercises under different names.

* fix(ui): stop artwork refreshes reloading the whole page

Resolving an album broadcast song:["*"], because a track with no art of its
own is served its album's and the dependent ids are unbounded server-side.
useResourceRefresh checked for that wildcard across every resource in the
payload, not just the ones a component shows, so the album grid called
refresh() — a full page reload — for every drained batch. Upgrading a large
library reloaded the grid thousands of times.

The client knows what the server cannot: which tracks are loaded, and their
albumId. So the fan-out moves there, the wildcard check is scoped to watched
resources, and the backend now names only what it resolved.

The playlist views watch playlistTrack too: their rows carry albumId but are
keyed by playlist entry, so a song refresh never reached them — previously
masked by the wildcard's page reload.

Signed-off-by: Deluan <deluan@navidrome.org>

* fix(ui): stop the album grid blanking its covers on refresh

Cover takes its height from react-measure, which reports nothing until it
re-measures. That was harmless while the cover class sat on the img itself,
which has intrinsic size; it now sits on the Artwork root, whose img fills it
absolutely and so lends no height. A refresh remounts the tiles, and for the
frame before measurement lands the box collapsed to zero and every cover
vanished.

Give the box its own aspect ratio as a floor. The measured height still wins
once it arrives.

* refactor(artwork): drop the unused Bump/wake path from the worker

Worker.Bump had no production callers. Every real bump writes the queue row
through the repository instead: artwork.Refresh (the refresh endpoint and the
uploader), service.enqueue (read-through and stale-absent views), and
radio_repository. None of them wake a pool.

Bump was also the only sender to drainPool.wake, so the select case it fed was
unreachable outside tests, and runPool read as if a bump were picked up
promptly when it always waited for the 5s poll.

The e2e and unit suites used Bump only as a driver, never as the subject, so
they now enqueue with EnqueueBump and exercise the path production takes.
EnqueueBump rather than Refresh because Refresh also clears the state row,
which would change semantics for the re-bump-after-state and dedup specs.

Both harnesses start Run after enqueueing, so a fresh pool drains on its first
iteration and the wake never affected them: core/artwork/e2e averaged 3.26s
before and 3.30s after over 5 runs, within noise.

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(artwork): unexport what nothing outside the package calls

PlaceholderFor had no callers at all. Its comment offered it to callers that
must not consult persisted state, but no such caller was ever written, so it
is removed rather than unexported.

entityExists and encode83 are only reached from inside their own packages;
their tests are package-internal (artwork) or never touch them (blurhash_test).

ImageStore stays exported: server/subsonic/e2e constructs one to wire up the
worker, and that suite cannot move into package artwork.

Signed-off-by: Deluan <deluan@navidrome.org>

* refactor(persistence): name the backoff-preserving enqueue for what it does

EnqueueBump was named for a priority, but its behaviour is preserving an
existing row's retry_at; the priority comes from the item. Its one caller
passes ArtworkPriorityScan, which read like a bug at the call site and is not.

The three DO NOTHING inserts each repeated the INSERT prefix, the column list
and the conflict clause. They now share insertIfNotQueued, with the CTE that
EnqueueIfMissing needs passed as a prefix, and the column list lives in one
slice used by both squirrel and the raw SQL.

EnqueueIfMissing had no test against real SQL, only a mock mirroring the
anti-join by hand, so the rewritten statement had nothing verifying it. Two
specs now cover it: items with a state row are skipped, and an already-queued
row keeps its priority.

Signed-off-by: Deluan <deluan@navidrome.org>

* test(thumbhash): vendor the reference and generate golden vectors

* test(thumbhash): add a faithful reference port as the differential oracle

* fix(thumbhash): re-condition alpha fixture and assert solid.png header

alpha.png varied only alpha over a constant color, so compositing atop the
average canceled L/P/Q exactly like solid.png, leaving it just as float-noise
unstable and silently dropping alpha-path coverage. Vary R/G/B with position
too so alpha.png carries real signal and reproduces byte-exactly, then
replace the blanket solid.png skip with a precise assertion on its
well-conditioned header bytes and quantized-zero scales.

Also apply a range-over-int modernizer hint in reference_test.go.

* test(thumbhash): dither the fixtures so no DCT coefficient is degenerate

The gradient fixtures are smooth analytic ramps, and alpha.png's alpha channel varied
along x only. Both make whole families of DCT coefficients mathematically zero: 13 of
alpha.png's 38 AC nibbles, and at least one in every other ramp fixture.

A zero coefficient normalizes to exactly the 0.5 midpoint, i.e. 15*f = 7.5, so which of
nibble 7 or 8 it quantizes to is decided by ~1e-16 of float rounding noise. Those nibbles
are therefore unstable across any two summation orders -- the vendored JS and the Go port
already disagreed on solid.png for this reason -- and they carry no signal, so a bug that
transposed two of them would be invisible.

A deterministic +/-4 dither, plus an alpha ramp that varies in x and y, leaves every
coefficient at least 4.8e-5 from the tie boundary: ~1e9 times the observed inter-
implementation noise. solid.png and tiny.png regenerate byte-identical and keep their
existing carve-outs.

* feat(thumbhash): add a two-pass separable ThumbHash encoder

Encode replaces the reference's four w*h scratch arrays (~320 KB at 100x100) and its 40
re-reads of every pixel with a single pixel pass that folds each row into per-frequency
sums, then a second fold over rows. The transform drops from O(terms * pixels) to
O(nx * pixels + terms * h), nx <= 7.

Verified against the vendored JS goldens and, differentially, against the literal Go port
on 500 randomized images. On the fixtures the two implementations' AC coefficients agree
to 8e-15; the separable inner loop reassociates the additions, so exact agreement holds
only where a coefficient is not sitting on a quantization tie, which is why the fixtures
are now dithered.

* test(thumbhash): fuzz the opaque path and drop an ill-conditioned golden

The 500-image randomized differential filled every byte randomly, so hasAlpha
(avgA < w*h) was true for all 500 images: the 7x7 no-alpha layout, terms(7,7),
nx=7 and the `if hasAlpha` false branch were never fuzzed. Force full opacity on
alternating iterations, which splits the run 250/250 with the seed and iteration
count unchanged. All 500 still match the reference port.

tiny.png is 1x1, so it has no non-zero AC content: 12 of its 37 AC coefficients
sit exactly on the round(15*f) = .5 tie and 24 are within 1e-12. It passed only
because a single pixel admits no summation reassociation. Give it the same
header-only carve-out solid.png already had, in both test files. The four
well-conditioned fixtures keep strict full byte equality.

Also document the divergence class on Encode itself rather than only in test
comments, add a sub-image regression spec, and use the max builtin over
math.Max. The toNRGBA Rect.Min gate turns out to protect nothing — SubImage
re-slices Pix so Pix[0] is the Rect.Min pixel and the loops read it correctly
either way — so its comment, which claimed the opposite, is corrected. The gate
is kept for now; removing it is a separate call.

* test(thumbhash): benchmark against blurhash at the pipeline input size

* feat(artwork): persist a thumbhash alongside the blurhash

The artwork table is content-addressed, so this costs one row per unique image
rather than per entity. Measured on a 25k-image library: +0.6MB on a 727MB DB.

The column is added to the existing add_artwork_tables migration rather than a
new one, since #5847 has not been released and the table it extends ships in
that same PR.

* feat(artwork): hydrate and expose thumbHash on every entity

ItemArtworkInfo.Image() is the single projection every hydration branch goes
through, so adding the field there covers albums, artists, playlists and both
the own-art and inherited media-file branches.

* feat(artwork): encode blurhash and thumbhash from one 100px thumbnail

thumbnailSize drops 128 -> 100 so a single CatmullRom scale feeds both encoders;
thumbhash hard-rejects anything larger and a second downscale would cost more
than shrinking the shared one.

decodeArtwork on a 1000x1000 JPEG, before -> after:
  15.53ms -> 15.45ms/op, 5878122 -> 5014796 B/op, 37 -> 75 allocs/op

Time is a wash because the JPEG decode dominates; the 863KB drop is the smaller
thumbnail more than paying for thumbhash's added work.

This rewrites every blurhash value, so it must land before #5847 reaches a
release: Finamp keys its cover cache and download dedup on that value.

* feat(ui): use thumbhash for the cover loading placeholder

Adds a local decoder rather than the thumbhash npm package, matching the local
blurhash decoder it replaces. Pixels are pinned against evanw/thumbhash's
reference decoder via the vendored copy already in the encoder's testdata.

Unlike a blurhash, a thumbhash carries its own approximate aspect, so a record
with no dimensions now falls back to that instead of to a square.

The blurHash API field stays: Jellyfin clients and third-party native clients
still consume it.

* perf(artwork): hand both hash encoders one NRGBA thumbnail

makeThumbnail emitted a premultiplied *image.RGBA, so thumbhash allocated and
un-premultiplied a full copy on every image while blurhash paid nothing. It now
emits *image.NRGBA, which thumbhash wants as-is, and blurhash reads that type
directly, premultiplying per pixel to keep its output identical.

thumbhash.Encode at the pipeline's 100x100 input:
  134200 -> 95300 ns/op, 56188 -> 15163 B/op, 37 -> 35 allocs/op
decodeArtwork on a 1000x1000 JPEG:
  5014796 -> 4973800 B/op, exactly the conversion that is gone

The scaler costs the same into either destination (7.33ms vs 7.34ms measured),
so no time is traded for this.

* test(artwork): drop the decodeArtwork benchmark

It existed to capture the before/after baseline for the 128->100 thumbnail
change, which it has served. As an ongoing guard it is misleading: a 1000x1000
JPEG decode is ~97% of the 15ms it measures, so the two encoders it would be
reached for are ~2.6% of the signal. It reported a phantom 2.8% regression for
the NRGBA thumbnail change that isolating the scaler disproved.

The per-encoder benchmarks in blurhash/ and thumbhash/ cover the part that
actually changes.

* test(artwork): benchmark both hash encoders from one file

benchImage and BenchmarkEncodeAtInputSize existed in both encoder packages, and
blurhash's copy had drifted into a third inline duplicate once both benches
moved to NRGBA input.

The head-to-head now lives in core/artwork, which already imports both encoders
and can pin the input to the real thumbnailSize constant. The gradient builder
moves to tests, which both packages already import via their suite bootstrap.

thumbhash keeps a shipped-vs-reference benchmark, since referenceEncode is
test-only and cannot be reached from core/artwork.

* test(thumbhash): drop the shipped-vs-reference benchmark

The two-pass rewrite's advantage over the naive port is already recorded in its
commit message; carrying the benchmark to re-derive it has no ongoing use.

reference_test.go stays: besides the benchmark baseline it holds the
differential oracle the golden-vector and randomised specs assert against.

* test(thumbhash): assert against reference goldens, drop the Go port

The reference port existed to be a differential oracle, but its packing half was
a verbatim copy of production pack(), so it was not as independent as it looked.
Only the 500-image randomised spec needed it; the six PNG fixtures cannot reach
random sizes, aspects, or both coefficient layouts.

gen_generated.mjs now emits 300 vectors from evanw's actual JS. Their pixels are
a pure function of their index, so Go rebuilds them byte-for-byte and only the
hashes are committed (16KB). The oracle is now the reference itself rather than
a hand transcription of it.

Also from the cleanup pass:
- maxCX/maxCY scanned every term to recover a bound that is just the widest
  coefficient region
- tests.GradientImage duplicated generateGradientImage three files away
- BenchmarkHashEncodersAtInputSize was also BenchmarkHashEncoders/*/100x100
- processor had two internal test files with no rule for which gets a new spec
- three blurhash specs differing only by alpha became a DescribeTable
- the shared mock's GetInfoForItems projection had drifted from the real query

* refactor(model): keep the blurhash off native JSON and fold its specs

Nothing on the native API consumes blurHash: the web UI reads thumbHash, and
Jellyfin's mappers take the Go field directly rather than through this
serialization. It was shipping ~40 unused bytes on every row of every list
response, on a surface that accretes clients once published.

The JSON specs were five marshal-and-check-keys blocks over the same struct;
they collapse to one populated case, one bare case, and a guard that the
blurhash stays off the wire.

* refactor(persistence): simplify the artwork dangling-row purge helper

purgeDangling took a bound executeSQL method value and a table name only because
its two callers live on unrelated types. Neither parameter was load-bearing:
executeSQL is a value receiver on sqlRepository that never reads tableName, and
both callers already hold an sqlRepository whose tableName is the table being
purged. Taking that struct collapses both parameters into the receiver.

itemArtworkSQL wrapped sqlRepository without adding a single method, so the items
field becomes a plain sqlRepository.

danglingItemArtworkKinds is also read by EnqueueAllMissing, which enqueues
entities that have no artwork row yet - neither a purge nor anything specific to
item_artwork. Renamed to artworkOwnerTables to describe both of its uses.

* fix(artwork): keep sweeping past a store file that cannot be removed

Sweep returned the os.Remove error straight out of WalkDir, so a single
unremovable file abandoned the rest of the walk. Every later orphan, stale mime
variant and abandoned temp file then survived until the next prune, which would
abort at the same place.

Warn and carry on instead. The orphan-file loop in prune already had this
resilience; Sweep is where it belongs, since it is the only step that reaches
stray files and superseded variants.

* refactor(artwork): let the sweep reclaim orphan files instead of prune

Deleting unreferenced artwork rows took five round trips: snapshot the orphan
hashes, fetch their mimes, delete, re-fetch to see which rows actually went, then
remove each file. The last four exist only to work out which files to delete -
but the sweep that runs moments later already derives exactly that from the
database, since GetAllMimes is read after the delete and Sweep removes any file
whose hash has no row, under the same mtime guard. The sweep is also the more
thorough of the two: it reclaims stale mime variants of an orphan hash, which the
per-hash removal never looked at.

Delete the rows in one predicate-only statement and let the sweep follow. The
orphan predicate now runs once per prune instead of once for the snapshot plus
once per 200-hash delete chunk, and with no hash list to bind there is nothing
left to chunk.

GetOrphanHashes and GetImages had no other caller and are gone. Dropping them
also removes the mock's OrphanHashes lever, which let a spec declare a hash
orphaned while item_artwork still referenced it - a state the SQL repository
could never produce, since both predicates were always identical.

* refactor(model): name the artwork mime lookup for what it is keyed by

GetAllMimes reads as a collection of mime types; it returns a hash -> mime index
over every stored artwork. GetMimeByHash names the key, matching the convention
the other map-returning repository methods already follow (CountBySuffix,
CountByClient).

* refactor(artwork): split the repository's deletes from its purges by name

Six removal methods across the two artwork repositories used Delete and Purge
interchangeably, so neither prefix told you anything. There is a real distinction
underneath: Delete methods are caller-directed and take the rows to remove, while
Purge methods are garbage collection - the repository finds rows whose referent
is gone by joining against the owning table, and returns a count because the
caller cannot know one. The signatures already followed that split; only the
names did not.

DeleteOrphans was the odd one out, taking a grace cutoff rather than a target and
returning a count, so it becomes PurgeOrphans. PurgeDanglingItemArtwork loses the
Artwork it repeats from its own interface and keeps the Items that says which of
that interface's two tables it means.

DeleteForItem was DeleteForItems with one id - squirrel emits = for a scalar and
IN for a slice against the same predicate - so its one caller passes a slice
instead. Dangling and Orphan stay distinct: dangling is a row whose entity is
gone, orphan is an image no state row references.

* refactor(artwork): drop the orphaned store remover, aggregate sweep failures

Review follow-ups to the prune rework.

ImageStore.Remove lost its only production caller when the sweep took over
orphan-file reclamation. It carried its own copy of the mtime guard that now
lives solely in Sweep, so the two could drift, and it stood as an invitation to
grow a second reclaim path. Its specs either duplicated Sweep's own coverage or
tested nothing else, so they go with it; the one unrelated test that used it to
delete a file calls os.Remove directly.

Sweep warned once per file it could not remove, which is fine for a stray
permission bit and useless for a store mounted read-only - a large library would
emit one line per aged file on every prune, and prune would still report success.
Count the failures instead and warn once, with the count and the last error, so a
systemic failure is legible without drowning the log.

Also: the orphan log line counts rows, not files, and now says so; and the
blocked-removal spec asserts its two fixtures really do land in different shards,
since the assertion is vacuous if they collide.

* fix(ui): show the placeholder when a refresh swaps in an uncached cover

A cover whose hash changed under a mounted grid went blank for the whole fetch,
instead of falling back to its thumbhash. Artwork decided 'this blob was already
cached, skip the placeholder' once at mount and never revisited it, so every
later url for that record inherited the answer.

The fix has to live in useImageUrl. imgUrl is state cleared in an effect, so on
the render where url changes it still holds the previous url's blob - any caller
inspecting it reads the new url as already cached. Only the hook can see
cache.get(url) for the url actually being rendered, so it now reports fromCache
and resyncs its state during render rather than one render later.

Two shapes were tried and rejected against a live server before this one: a ref
recomputed per url, which a render-phase resync discards without rolling back the
ref, and the same tracking in Artwork state, which still samples imgUrl before
React re-runs the component. Verified on a running instance with cover-art
responses held open: the thumbhash now covers the whole window and stays under
the image until the fade ends.

* fix(ui): keep the placeholder for a cover whose fetch failed

useImageUrl caches a failed fetch as an entry with no blob, so treating every
cached entry as instantly painted suppressed the placeholder on remount: the
cover became an empty box instead of falling back to its thumbhash. Only a
cached blob counts as instant.

Caught by Codex on the previous commit, which introduced fromCache with the
looser predicate.

* feat(artwork): capture each image's dominant colour

A flat colour is the one placeholder a client can paint with no decoding at all,
so it can cover the frames before a thumbhash canvas even renders. Extract it
from the same 100px thumbnail the two hash encoders already share, and expose it
as dominantColor on the native API.

Dominant means presence, not salience: the largest cluster wins, so a white
sleeve reports white. That is what a placeholder needs. An accent colour is the
opposite question and is deliberately not answered here - it depends on the
client's theme, and by the time a client needs one it has the cover pixels and
can compute whatever suits it.

Bins at 4 bits per channel, then merges perceptually-near bins in Oklab before
picking the winner: a gradient splits across adjacent bins and would otherwise
lose to a smaller flat region. Measured at 246us per image on the weakest target
hardware we care about (Celeron N5105), against ~15.8 images/s for the pipeline
around it.

The column goes into the feature's original migration rather than a new one:
computing it later would mean re-decoding every image in the library.

* fix(artwork): ignore image candidates that cannot be fetched

bestImageURL only rejected URLs that url.Parse itself refuses, which is almost
nothing: relative paths and any scheme parse cleanly. A candidate like
images/big.jpg or ftp://host/big.jpg therefore won on size, and since the
function returns a single URL whose failure ends that agent's turn, the agent's
valid smaller images were never tried.

Two details made it easy to hit rather than theoretical. Size is frequently 0 for
every candidate, and only a strictly larger one replaces the first, so an
unfetchable entry in first position sticks. And these strings come straight from
plugins, where a relative path is an ordinary mistake.

Accept only absolute http/https URLs with a host.

* revert(ui): move detail-page scroll handling to its own branch

Reverts 40153bd43. Scroll position carrying over between pages is stock React
Router behaviour rather than something this branch introduced, so the fix does
not belong in an artwork PR that is otherwise ready for review.

The work continues on fix/scroll-restoration, off master, where it grew into
per-route restoration: a new page starts at the top and going back returns to
where you were, which the scroll-to-top could not do.

* fix(ui): fade cover art consistently, and shorten the fade to 150ms

The <img> mounts with its blob URL already set, so onLoad often fires in the
same frame the element is inserted. The opacity:0 start state never gets
painted, the transition has no value to animate from, and the cover pops in
instead of fading. Only tiles whose decode happened to straddle a paint
boundary actually faded, which made a grid load look ragged: 4 to 6 of 18
covers faded, varying between runs.

Deferring the decoded flag by two animation frames guarantees the hidden state
is painted first. Measured on a live grid afterwards, 17 of 18 covers fade, the
18th having a cached blob and taking the intentional instant path, and the tail
after the last byte arrives drops from ~440ms to ~163ms.

The duration also drops from 500ms to 150ms. That 500ms mirrored master's fade,
but master paints no placeholder behind the image and needs a slow blend to
cover a blank tile. Here a thumbhash already fills the gap, so a long crossfade
only delays the grid settling, measured at 145-190ms slower to full opacity
than master.

---------

Signed-off-by: Deluan <deluan@navidrome.org>
2026-08-09 15:03:27 -04:00
Deluan Quintão
5c5b849a4e
docs(plugins): sync plugins README with the implementation (#5912)
* docs(plugins): document the Matcher host service

The Matcher host service (matcher_matchsongs, permission 'matcher') was
missing from the README entirely. Add its section with permission example,
the matcher-requires-library rule, result ordering/scoping semantics, and
a Go usage example.

* docs(plugins): add missing nd_scrobbler_playback_report to Scrobbler

The Scrobbler capability has four required methods, but the README said
three and omitted nd_scrobbler_playback_report from the function table.
Add the table row and document the PlaybackReport input payload and its
possible playback states.

* docs(plugins): remove stale coverartarchive-as example row

The AssemblyScript coverartarchive-as example no longer exists in
plugins/examples/ (and no AssemblyScript code remains in the repo), so
drop its row from the examples table.

* docs(plugins): add Command Line Interface section

The 'navidrome plugin' CLI (list, info, validate, enable, disable, edit,
rescan) was undocumented; the README's only mention was a single inline
'plugin edit --write-access' reference, and it claimed plugins could only
be enabled/disabled via the UI. Add a CLI section with all subcommands
and the 'plugin edit' flags, and link it from Runtime Management.

* docs(plugins): add pdk and types packages to Go PDK table

The Go PDK package table was missing two of the packages that ship under
plugins/pdk/go/: 'types' (shared DTOs used across capabilities and host
services) and 'pdk' (the extism/go-pdk wrapper the README's own examples
already import).

* docs(plugins): correct capabilities and host services in examples table

Several example rows understated what the plugins implement: the
scheduler/websocket callback capabilities were omitted for nowplaying-py,
library-inspector-rs, crypto-ticker, and discord-rich-presence-rs, and
the Discord example also uses the Config host service.

* docs(plugins): state that scheduler/taskqueue permissions require callbacks

Manifest validation rejects a plugin that declares the scheduler or
taskqueue permission without exporting nd_scheduler_callback or
nd_task_execute, but the README worded both callbacks as soft
suggestions (TaskWorker was even labeled optional). Make the load-time
failure explicit in both capability sections.

* docs(plugins): document HTTP, WebSocket, and Task limits and defaults

Add the runtime limits plugins actually hit: HTTP default 10s timeout,
5-redirect cap with per-hop host re-validation, and 10MB response cap;
the 30s timeout on WebSocket callbacks; and the full task_createqueue
parameter list (delayMs, retentionMs) with queue defaults, retention
bounds, the 1MB payload cap, and task persistence across restarts.

* docs(plugins): include scrobbleRetriever in user-scoped authorization note

The ScrobbleRetriever host service added in #5795 is user-scoped like
subsonicapi and scrobbler, but the Security section's user-scoped
authorization item didn't list it.

* docs(plugins): clarify matcher user scoping requires the users permission

The Matcher usage example set opts.Username while the section's manifest
example declares only matcher+library; without the users permission no
users can be assigned to the plugin, so userAccess.resolve rejects the
call at runtime. Make the example unscoped and state that user scoping
requires the users permission with users assigned. Raised by Codex
review on PR #5912.
2026-08-08 22:25:48 -04:00
Kendall Garner
b0c6d2e444
feat(plugins): add scrobbles access to PDK (#5795)
* initial scrobble api

* feat: add scrobble retrieval api

* address feedback (1)

* fix spelling

* be explicit about get

* add primary key field, update index, remove rowid references

* use unix timestamp for input and output

* initial api, some testing

* add tests, add count retrieval

* add docs, test for rejected user

* add permission validation for scrobble retriever

* chore(plugins): fix typos in scrobble retriever

Rename newScrobbleRetreverService, and fix FromTImestamp/nonero in the
ScrobbleRetriever doc comments, which generate into the Go and Rust PDKs.
Also corrects two mislabelled test entries.

* fix(plugins): make scrobble pagination order deterministic

Sorting only by submission_time left the order of equal timestamps up to the
query planner, but the cursor skips ties by offset, so an unstable order can
repeat or drop scrobbles between pages. Break ties on scrobbles.id, which the
existing scrobbles_user_time index already yields for free.

Descending is now honoured for every combination of From/To rather than only
when both or neither is set. This changes the default for a lone ToTimestamp
from newest-first to oldest-first.

* refactor(plugins): return the next page's options from GetScrobbles

Paging previously meant reading NextTimestamp and Cursor off the response and
deciding where each belonged: NextTimestamp into FromTimestamp when ascending
or ToTimestamp when descending, and Cursor copied every time, including when 0.
Both are silent data-loss bugs when a plugin gets them wrong.

GetScrobbles now returns the options for the following page, or nil when the
range is exhausted, so a plugin passes the value straight back and repeats.
ScrobbleCursor and ScrobbleList are gone; the query itself is unchanged.

* docs(plugins): warn against setting ScrobbleOptions.Offset manually

The all-ties carry rule assumes Offset counts already-returned rows at the
boundary timestamp, which only holds for the options GetScrobbles returns.
A hand-built From+Offset combination can silently skip scrobbles, so document
the field as managed pagination state instead of a generic skip.

* docs(plugins): document the ScrobbleRetriever host service in the README

Covers the manifest permissions (including the users requirement), the four
host functions, the options/ref field tables, and the pagination loop with
its two gotchas: the host-managed offset and the adjusted range on the
returned next options.

* chore(plugins): regenerate scrobble retriever stub with nil-safe accessors

---------

Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-08-08 22:13:29 -04:00
Deluan Quintão
5a5311a9c0
fix(plugins): make generated mock stubs nil-safe for nilable returns (#5909)
The ndpgen mock accessors asserted return types unconditionally, so a plugin
test using Return(nil, ...) — the natural way to model an empty result or a
pagination terminal page — panicked on the untyped-nil type assertion instead
of returning the zero value. Guard pointer, slice, map and any returns in both
the host-service client stubs and the PDK stub, and regenerate.
2026-08-08 21:57:44 -04:00
ant
a0bf78cdea
fix(contrib): added missing hyphen in OpenRC script that caused crashes on startup (#5906)
Signed-off-by: Ant <marxguey@proton.me>
2026-08-08 15:40:05 -04:00
Deluan Quintão
0f4c9b8212
fix(ui): don't start playback when closing the disc cover lightbox (#5901)
The Lightbox renders through a React portal (react-modal), and React
propagates synthetic events up the React tree rather than the DOM tree, so
clicking its close button or backdrop bubbled into the ancestor TableRow and
triggered playSubset.

The existing timestamp guard could not catch this: react-image-lightbox defers
onCloseRequest by animationDuration via setTimeout, so lightboxClosedAt was
only stamped 200ms after the click had already propagated. The guard is kept
because it still covers the separate mobile ghost-click path, where the
synthesized click lands on the row after the overlay unmounts.

Stopping propagation in onCloseRequest — the approach used by ContextMenus,
whose MUI onClose fires synchronously — does not work for the same reason.
Instead, wrap the Lightbox in an element that stops propagation at the React
tree boundary the portal bubbles through, which also covers the lightbox
controls we don't own (zoom buttons, caption, image drag).
2026-08-07 09:36:52 -04:00
Deluan Quintão
dce48ff650
feat(smartplaylist): add album-level fields for sorting and filtering (#5899)
Smart playlists could only sort by the track-level `dateadded`, which scatters
an album's tracks because every track has its own timestamp. There was no way
to express "newest albums first, tracks in album order".

Adds five fields backed by the album table: albumdateadded, albumdatemodified,
albumduration, albumsongcount and albumsize, so `"sort": "-albumdateadded,
tracknumber"` now works. They filter as well as sort, which also enables rules
like "everything from albums added this month" or "skip singles and EPs".

These need the album table rather than the album_annotation table the existing
album* fields join, so they get their own bit in the join mask. The bitmask
already unions joins from both the expression and the sort fields, so a
sort-only reference pulls in the join for the main query while correctly
staying out of the percentage-limit count query.

No COALESCE default is used. That mechanism exists because an album_annotation
row is genuinely often absent; the album row always exists and song_count,
duration and size are NOT NULL, so leaving the columns bare keeps filters
index-friendly.

albumdatemodified follows the existing track-level `datemodified` naming rather
than the `albumdateupdated` spelling used in the request.

albumreleasedate was considered and rejected: album.release_date is
allOrNothing() over the tracks, so it equals the track-level releasedate when
they agree and collapses to empty when they disagree.

Closes https://github.com/navidrome/navidrome/discussions/5347
2026-08-06 10:59:50 -04:00
Deluan
d764a1e9d7 fix(log): change debug log level to trace to reduce log noise from cron
Signed-off-by: Deluan <deluan@navidrome.org>
2026-08-06 00:40:58 -04:00
Deluan Quintão
50633f839d
fix(ui): restore each page's scroll position when navigating back (#5892)
* fix(ui): anchor detail pages to the top when opened from a list

React Router keeps the previous page's scroll offset, so opening an album from
a scrolled list started the detail page mid-song-list. Artist pages had the
same bug; it just shows less because the artist list is rarely long enough to
scroll far.

Keyed on the record id rather than mount, so detail-to-detail navigation (an
album's artist link) resets too, and so the scroll waits for the record instead
of firing against an empty page.

* feat(ui): remember each route's scroll offset

A hook that saves window.scrollY per history entry and, on navigation, tops a
pushed route or returns a popped one to where it was. Keyed on location.key so
back and forward each restore their own offset, and bounded because history
entries are not.

Callers pass their own readiness: restoring before the rows render leaves the
document too short, so the browser clamps to the top and the offset is lost with
no error to show for it.

* refactor(ui): fold scroll-to-top into route scroll restoration

useScrollToTop only ever forced the top, so it fixed opening a detail page from a
scrolled list and did nothing for the return trip: coming back to the list landed
wherever it happened to be. The new hook covers both, and its readiness argument
carries over the reason the old one keyed on the record id - waiting for the
record rather than firing against an empty page.

* feat(ui): restore the album list's position when returning to it

The list is the page worth remembering: scrolling a long way to find an album and
landing back at the top is the annoyance the detail-page scroll fix could not
reach.

Mounted as a pass-through around the List's child rather than beside it, because
React Admin calls Children.only on List children and clones that one child with
the list props - which is also how this reads loaded/total to wait for rows.

* fix(ui): key scroll restoration on the route, not location.key

Hash history never assigns location.key - history.js calls createLocation with an
undefined key and warns that it cannot carry state - so every route collapsed
into one slot. The detail page's own scroll listener then overwrote the list's
saved offset with 0, and going back restored that 0. Only the scroll-to-top half
worked, which is what made it look fine.

Keyed on pathname+search instead. The spec that would have caught this asserts
two routes keep separate offsets; the previous ones mocked the router and so
only ever confirmed the assumption.

* refactor(ui): tidy up scroll restoration after review

Four cleanups, none changing behaviour:

ScrollRestorer read loaded/total off whatever props React Admin happened to clone
in. useListContext is the contract for those values and is already used three
times elsewhere, including further down this same file; the clone payload is an
implementation detail that would fail silently if it ever changed.

The restore runs in a layout effect now. A passive effect is flushed after paint,
so an image-heavy grid was painted at the old offset and then jumped.

MAX_ENTRIES matches the naming every other module-level cap in common/ uses.

The per-instance guard against re-restoring was deletable with a green suite, so
it now has a spec: readiness flickering on one route must not scroll twice.

* fix(ui): resolve media queries on the first render

MUI defaults useMediaQuery and withWidth to SSR-safe two-pass rendering: the first
render reports the wrong breakpoint and a layout effect corrects it. Navidrome is
client-only, so every mount paints a layout it immediately reflows. Album tiles
render without their artist line and grow 14px when it arrives, and react-admin's
own buttons paint labelled before collapsing to icons, which together grew the
album list 79px right after a scroll restore and dragged the position with it.

Setting noSsr on the theme reaches react-admin's internals too. withWidth needs its
own option because it gates on a mount flag rather than on the media query.

* fix(ui): keep restoring the scroll offset until it sticks

A single scrollTo assumes the page is already at its final height. It often is not:
the artist page reports ready as soon as its cached header record renders, while the
albums below are still loading, so the browser clamps the offset to the top of a
viewport-tall document and it is lost with no error.

The restore now retries until the offset lands, yielding as soon as the position moves
somewhere we did not put it. Keying that on input events instead breaks the trackpad
back-swipe, whose wheel momentum keeps firing through the restore window.

Offsets are also committed when leaving the page rather than on every scroll. Tearing
the page down collapses the document and snaps to the top, and a live listener recorded
that clamp over the offset being left behind.

* refactor(ui): tidy up scroll restoration after review

Folds the offset commit into the scroll tracker's own cleanup now that the tracker
ignores the collapse snap, so one effect does what two did. Skips scheduling the retry
loop when the first scrollTo already landed, and only pays for the scrollHeight read on
scroll events that reach the top, since that is the only case the guard can fire.

The theme hook's own prefers-color-scheme query runs above the ThemeProvider carrying
the new prop, so it needs noSsr passed directly or the auto theme still renders dark
first and flips.

Also lifts the repeated fake-timer fixture in the specs into one helper and restores
real timers from afterEach, so a failing assertion no longer leaves them installed for
every later spec.

* fix(ui): bank the scroll offset before the next page tops itself

Committing the offset from the scroll listener's passive cleanup ran too late. The
incoming page scrolls to the top in its own layout effect, and the outgoing page's
listener is still attached at that moment, so it recorded that 0 over the offset being
left behind. Whether it did depended on when the browser dispatched the scroll event
relative to React's passive flush, which made returning to a detail page lose its
position intermittently.

Moving the commit back into a layout cleanup makes it deterministic: React runs those
in the mutation phase, before the incoming page's layout effects. The scrollHeight
guard in the listener went with it, since it only covered the case where the incoming
page was shorter than the viewport and the ordering covers all of them.
2026-08-04 22:07:16 -04:00
Deluan
e1b89050df chore: exclude .worktrees from golangci-lint checks 2026-08-03 14:34:53 -04:00
Kendall Garner
54fe6c254e
feat(plugins): implement plugin specific storage (#5839)
* implement storage api/hooks

* fine. if the error messages are different, just match error

* rename storageMount

* add independent plugin test

* round 2

* .-.

* one more copypasta fail

* docs(plugins): document the Storage host service

The README is the plugin author reference and every other host service has a
section there, but Storage had none, so the /storage guest path contract only
existed in code.

Documents the mount point and its backing directory, the manifest permission,
the host function, and the two behaviours an author would otherwise discover
the hard way: there is no size limit, and the directory outlives an uninstall.

* docs(plugins): correct the library filesystem security notes

The README stated in three places that library filesystem access is read-only,
which stopped being true when AllowWriteAccess was added: an administrator can
grant a plugin write access to libraries.

Corrects those and gives the library and storage mounts the same wording for
what the sandbox guarantees, since both now go through the same jail.

* docs(plugins): describe symlink handling in mounts accurately

The security notes claimed paths resolving outside a mount are rejected, which
overstates the jail. Only lexical escapes are: '..' and absolute paths. Creating
symlinks is denied, but symlinks already present are followed and do reach
outside the mount, which is what lets music libraries link folders in from
elsewhere. Both behaviours are pinned by tests in the plugins package.

---------

Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-08-03 14:23:42 -04:00
Deluan Quintão
77726af59c
fix(plugins): reject plugin IDs that are unusable as directory names (#5886)
The plugin ID is derived from the package filename and used verbatim as a
directory name under DataFolder/plugins by the kvstore and taskqueue host
services. A package installed as '..ndp' yields the ID '.', whose data
directory resolves to the parent of every other plugin's directory, so it
overlaps their private data. On Windows, trailing dots and spaces are dropped
during path normalization, so 'foo..ndp' and 'foo.ndp' yield distinct IDs that
resolve to the same directory and would share the same SQLite files.

Discovery and the file watcher now derive the ID through pluginIDFromPath,
which rejects '.', '..', empty names, separators, trailing dots or spaces, and
anything filepath.IsLocal refuses (Windows reserved names, drive-relative
paths). The loader repeats the check, since a sync failure is non-fatal and
could otherwise leave a stale row reaching the host services.
2026-08-03 13:09:53 -04:00
Deluan Quintão
279ff98e0d
fix(ui): stop precaching index.html so logins can't show the wrong user (#5882)
* fix(ui): stop precaching index.html so logins can't show the wrong user

index.html is rendered per-user by the server: it carries __APP_CONFIG__,
including the auth payload (user id, name, role, Subsonic token) when
authentication comes from a reverse-proxy header. Workbox precached it, and
because precacheAndRoute registers its route before the NetworkOnly
NavigationRoute, every navigation to /app/ was answered from Cache Storage
with a frozen copy of whoever installed the service worker.

With ExtAuth, signing out and back in as a different user therefore kept
showing the previous user, along with their Subsonic token. Cache Storage
ignores the no-store header serve_index.go already sets, and ignores the
browser's "disable cache", so only clearing site data recovered.

Excluding index.html from the precache manifest lets the NetworkOnly
navigation strategy do the job it was written for. Existing poisoned caches
heal themselves: the entry is dropped when the new manifest activates.

The same stale document caused the create-admin dialog to reappear (#3613),
patched then by calling removeHomeCache() after login. That helper only ran
on password login and token refresh, so it never covered the ExtAuth path,
and a refetch re-poisoned the cache anyway. Fixing the cause makes it dead
code, so it is removed.

Also serve the offline page on 5xx: it arrives as a normal response, so the
existing catch never saw it, and without a precached shell a restarting
server would surface a raw gateway error. The offline copy is reworded to
fit both causes.

* test(ui): cover the service worker navigation fallback rules

The handler lived inside sw.js, which only loads in a service worker where
workbox arrives via importScripts, so none of it was reachable from vitest.
Moving the decision into its own module pins the rules that matter: a 5xx
falls back to the offline page like a thrown network error does, while 4xx
and 304 still pass through to the app.
2026-08-02 19:46:05 -04:00
Deluan Quintão
f853ca604a
refactor(db): migrate all ids to a uniform canonical 128-bit base62 encoding (#5824)
* refactor(model): extract canonical 128-bit base62 id codec

* feat(model): generate random ids as canonical 128-bit base62 values

* feat(scanner): emit legacy PIDs in canonical base62 encoding

* feat(db): add id canonicalization transform for the uniform-ids migration

* feat(db): migrate all ids to canonical 128-bit base62 encoding

* fix(db): canonicalize ids in junction tables and JSON columns

* chore(jellyfin): update id-family notes for uniform canonical ids

* test(ids): harden codec input contract and migration edge coverage

* refactor(model): use log.Fatal for Encode128 contract guard per project convention

* fix(db): force full rescan after id migration for legacy PID configs

* test(db): guard id-column inventory against schema drift

* refactor(ids): compile-time Encode128 contract and unified column rewrite helper

* refactor(db): apply review feedback to id migration

Filter empty strings in collectColumn's SQL, reuse a prepared statement
for rewriteColumn updates, and clarify the legacy ID functions' comment
now that they emit the canonical encoding.

* feat(auth): split session and public-link JWT secrets, rotating sessions on id migration

* test(subsonic): initialize public token secret in helpers suite

The suite sets auth.TokenAuth directly instead of calling auth.Init, so the
new PublicTokenAuth was nil whenever Ginkgo's spec order ran a helpers spec
before any spec that calls auth.Init, panicking in publicurl.ImageURL.

* refactor(db): inline canonicalID into its only consumer, the uniform-ids migration

* refactor(model): rename Encode128/Decode128 to Encode/Decode

With every id now exactly 128 bits, the width suffix is redundant; the
package-qualified id.Encode/id.Decode carries the same information.

* test(db): make the id-columns guard classify JSON columns too

The guard only inspected columns named id/pid/*_id, so it could not see ids
embedded in JSON. Widen it to *_ids and to every JSON column, and drive the
"covered" set from a new embeddedIDColumns list instead of the inline calls
in the migration.

Every JSON column the schema has now carries a verdict. The four denormalized
caches -- media_file/album.participants, media_file/album.tags,
album.folder_ids and artist.similar_artists -- hold only artist, tag and
folder ids. Those all come from id.NewHash, whose 22-char base62 encoding of
a 128-bit MD5 is already in canonical range, so canonicalID is the identity
on them and the migration correctly leaves them alone. A new codec test pins
that invariant, since the exemptions depend on it.

Verified on a copy of a 727MB/96k-track production database: canonicalizing
those four columns changed zero rows, and artist, tag and folder ids were
themselves unchanged by the migration (only media_file ids moved, 95108 of
96666).
2026-08-02 12:58:53 -04:00
Kendall Garner
b40b41584a
feat(subsonic): Implement OpenSubsonic topSongsByArtistId extension (#5853)
* implement topSongsByArtistId extension

* do not look up by artist name if empty

---------

Co-authored-by: Deluan Quintão <deluan@navidrome.org>
2026-08-02 12:39:51 -04:00
Deluan Quintão
810b14ed57
fix(plugins): confine plugin filesystem mounts to their root (#5881)
* fix(plugins): confine plugin filesystem mounts to their root

A plugin granted read-write filesystem access could escape its mount by
creating a relative symlink inside it and then writing through that link,
reaching any path the server process can write, including navidrome.db.

wazero resolves guest paths by concatenating them onto the host root. Its
WASI layer validates every path argument except the symlink target, which
path_symlink forwards unvalidated by design, and fs.ValidPath splits on
"/" only, so on Windows a "..\" path escapes the mount as well.

Mounts now go through a jailedFS wrapper that denies symlink creation and
rejects any path that is not filepath.IsLocal. That requires bypassing
extism's AllowedPaths, which discards any FSConfig passed alongside it, so
the mounts are built directly and applied per instance instead. Following
symlinks that already exist in a mount is unchanged: music libraries rely
on it, and read-only mounts already reject creating new ones.

* test(plugins): guard against setting extism AllowedPaths

Extracts the extism manifest construction so a test can assert AllowedPaths
is never set. Setting it makes extism build its own FSConfig and discard the
jailed mounts, silently restoring the symlink escape.

Verified by simulating the regression: with AllowedPaths populated for plugins
holding the filesystem permission, the new spec fails, as do two of the
end-to-end sandbox specs.
2026-08-02 12:27:08 -04:00
Mateusz Piotrowski
d23b68a438
fix: typo in description of --prometheus.enabled (#5878)
Remove a stray back tick.
2026-07-31 08:54:29 -04:00
fxj368
600ea5482c fix(ui): update Chinese (Simplified) translation (#5873)
Signed-off-by: Deluan <deluan@navidrome.org>
2026-07-30 12:38:35 -04:00
Kendall Garner
4f29465d27
fix(artwork): do not promote artist folder to album folder (#5856)
* fix(artwork): do not promote artist folder to album folder

* use filesystem join for path instead

* fix(artwork): resolve artist folder for albums with disc subfolders

Dropping the promoted album root from the artist reader's paths fixed the
flat-album case but broke albums whose tracks live in disc subfolders: the
promoted root was what kept the byte-wise longest common prefix on a
directory boundary. Without it, CD1/CD2 siblings share the fragment
"Album/CD", so the artist folder resolved one level too deep and
album/artist.* won over artist.*.

loadAlbumFoldersPaths now collapses each album to its own root before the
paths are compared across albums, so a disc-split album contributes its
album folder rather than each disc folder. Folders no album claims (the
promoted parent) are still returned unchanged, keeping the album, disc and
mediafile readers unaffected. The prefix math moves into commonDir, which
appends a trailing separator so the comparison lands on segment boundaries
- this also fixes sibling folders sharing a name prefix (Album/Album2).

Adds e2e coverage for the case the branch fixes (artist.* with no album/
fallback, which failed before this branch), the disc-subfolder regression,
and a multi-album guard that pins the scope boundary.

* test(artwork): cover artist whose albums are all disc-split

The existing specs cover a single disc-split album and a disc-split album
alongside a flat one, but not an artist where every album is split into
disc subfolders. That layout resolves correctly because the albums diverge
one level above the disc folders, which re-anchors the common prefix - a
property worth pinning so a future change to the path math can't silently
break it.

* fix(artwork): resolve artist folder when albums share a folder

loadArtistFolder decided whether to climb above the common directory by
comparing len(paths) against 2. That count stands in for "how many distinct
album roots are there", and the two diverge when an artist has two albums in
the same folder: the slice holds two identical entries, the climb is skipped,
and the artist folder resolves to the album folder. Deduplicate the roots so
the branch tests the property it means to test.

Replace the includeParent flag with two functions split by audience. The flag
was a caller-identity switch - constant true at the album, disc and mediafile
readers, all of which discard the returned paths, and constant false at the
only caller that reads them. The artist path now has loadArtistAlbumRoots,
which collapses each album to its own root and never consults albumRootParent;
loadAlbumFoldersPaths goes back to taking a single album and always promoting
the parent. Both share the folder load and image aggregation.

This also makes albumRootParent's contract structural. Its guard only rejects
an artist folder when it can find audio outside the album being resolved, so
passing every album of an artist at once made the check meaningless; taking a
single album means it can no longer be called that way.

Drops the per-album grouping and unclaimed-folder reconciliation from the
album path, where the result was discarded, and removes 15 mechanical true
arguments from the tests.

---------

Co-authored-by: Deluan <deluan@navidrome.org>
2026-07-29 21:48:42 -04:00
Deluan Quintão
add0a6dc9b
feat(config): warn about unrecognized options in the config file (#5870)
* feat(config): warn about unrecognized options in the config file

Options that don't match any known name were silently discarded, so a typo
or an option written outside its section looked like it was applied.

In #5869 the user set `ArtistSplitExceptions` at the root level instead of
under `Scanner`, and got no feedback that the option was being ignored.

The known names are derived by reflection over configOptions, so the check
stays in sync with the struct. Free-form maps (Tags, DevLogLevels) accept any
subkey. When an unknown key matches the last segment of a known one, the
warning suggests it. Keys are reported as spelled in the config file,
recovered by scanning it, since viper lowercases every key it loads.

Also fixes two gaps this surfaced:

- remapEnvVarKeysFromConfig accepted any ND_-prefixed key and advised a
  canonical name built by string substitution, so `ND_SCANNER_WATCHERENABLED`
  (not an option) suggested `Scanner.Watcherenabled` (not an option either).
  It now only advises names that exist, with their documented spelling, and
  leaves the rest to the unrecognized-option warning.

- The deprecated option list drove only the warnings, while the value
  migration kept a second hardcoded list. They had drifted: SearchFullString
  warned about `Search.FullString` but never migrated to it. Both now come
  from deprecatedOptions.

* fix(config): address Codex review on the unrecognized-option warning

- Values computed during Load (ConfigFile, LastFM.Languages, Deezer.Languages)
  were accepted as valid keys, so setting them in the config file stayed silent
  even though Load overwrites them. They are now marked `conf:"-"` at the
  declaration, so the exclusion can't drift from the struct.

- Removed options are in the known-key set only so they get their own warning,
  but suggestOptions drew from the same set, so an unknown `ID` advised
  `Spotify.ID`, a key Navidrome explicitly ignores. They are now filtered out
  of suggestions.

- mapDeprecatedOption uses viper.Set, which outranks the config file, so a
  deprecated value overrode an explicitly configured replacement. It now skips
  the migration when the replacement was provided. viper.IsSet counts defaults
  as set, so the check is InConfig plus the env var.

envVarName also returns "" for an empty option, so a deprecated option with no
replacement no longer advises "Please use the new 'ND_'".

* fix(config): cover the ND_ spelling of a replacement, and the warning output

- explicitlySet missed the case where the replacement is given in the config
  file under its ND_ spelling: remapEnvVarKeysFromConfig moves it to the
  override layer, out of InConfig's reach, so the deprecated value still won.
  It now also checks the ND_-prefixed config key.

- The tests asserted only the helpers' return values, so removing the
  logUnknownOptions call from Load left them green. Added a spec that captures
  the logger and checks the emitted warning and suggestion text; verified it
  fails when the call is removed.
2026-07-29 13:44:42 -04:00
Deluan Quintão
23548f40a0
fix(share): give visual feedback when downloading from a share (#5865)
* fix(share): give visual feedback when downloading a share

The share page handed the download URL to navidrome-music-player, which fell
through to downloadjs and buffered the whole ZIP into memory via XHR before
saving it. Nothing was handed to the browser until the last byte arrived, so a
large share produced a long silent window with no player feedback and no
browser download UI, inviting repeat clicks that each spawn another server-side
zip+transcode.

Use the player's customDownloader prop to trigger a synthetic anchor instead,
so the browser performs the download and reports its own progress. An anchor
rather than assigning window.location.href: the share page's service worker
registers a NavigationRoute over all navigations, which intercepts the streamed
archive and fails it into the offline fallback (observed as HTTP 503 in Chrome).

handleDownloads now loads the share before streaming so it can set
Content-Disposition and Content-Type. This also fixes error reporting: ZipShare
previously wrote to the ResponseWriter before checkShareError ran, locking the
status at 200, so expired, missing and non-downloadable shares all returned 200.
They now correctly return 410, 404 and 403.

* feat(share): acknowledge the download click in the player

The browser's download UI is the real progress indicator, but nothing in the
page itself reacted to the click, so the moment before the browser catches up
still read as unresponsive. Dim the download button and make it unclickable for
two seconds after a download starts, reusing the JSS function-value pattern the
existing single-track styling already uses.

A repeat download restarts the window instead of extending the original, and
the timer is cleared on unmount. This also blunts repeat clicking, where every
extra click costs another server-side zip and transcode.

Add SharePlayer tests covering the download mechanism and this state machine.
The dimming itself is verified in a browser rather than jsdom: JSS function
values are not evaluated there, so the rule is never emitted and a CSS
assertion would pass or fail for the wrong reason.

Signed-off-by: Deluan <deluan@navidrome.org>

* test(share): assert render counts in SharePlayer feedback tests

The two acknowledgement tests compared the props object across renders, which
React may reuse, so they passed without proving anything and then failed once
the surrounding assertions changed. Count renders instead, and let the pending
timer run out rather than advancing exactly to its deadline, which does not
cross it.

The repeat-download test now also asserts that no render happens at the
original deadline, proving the timer was replaced rather than merely that one
eventually fired.

* fix(share): count one visit per share download

The preflight share load added in this branch made every download record two
visits: handleDownloads called Share.Load, and ZipShare then loaded the share
again internally. Share.Load increments and persists VisitCount, so the counter
advanced twice per download and the repository work was duplicated.

Pass the already-loaded share into ZipShare instead of its id. handleDownloads
is its only production caller, and it now has the share in hand for the
Content-Disposition header anyway.

The archiver test asserts Load is not called, so the double-load cannot come
back unnoticed. Verified against a running server: the counter now advances by
one per download.

* test(share): derive feedback-window timings from the constant

The acknowledgement tests hardcoded clock advances tuned to a 2000ms window.
Raising DOWNLOAD_FEEDBACK_MS to 5000 left them advancing 1500ms and 1001ms,
which no longer reach the deadline they are meant to cross, so the repeat-
download test passed without proving the timer had been replaced.

Export the constant and derive the advances from it, and let the pending timer
run out in the unmount test rather than advancing a fixed amount. Changing the
duration can no longer silently strand a test short of its deadline.

---------

Signed-off-by: Deluan <deluan@navidrome.org>
2026-07-28 16:13:44 -04:00
Marco Ciotola
ecf606e523
fix(ui): update Italian translation (#5848) 2026-07-25 13:23:32 -04:00
Deluan
93f6afb684 chore: add OpenCollective funding option
Signed-off-by: Deluan <deluan@navidrome.org>
2026-07-22 12:19:50 -04:00
Deluan Quintão
62257527d7
fix(subsonic): avoid double brackets when appending subtitle or version (#5832)
When AppendSubtitle or AppendAlbumVersion is enabled, the subtitle/version
tag was always wrapped in parentheses and appended to the title/album name.
If the tag value already came wrapped in brackets (e.g. "(non-explicit
version)"), the result was doubled: "Title ((non-explicit version))".

Append the tag as-is when it is already wrapped in a matching bracket pair
- (), [], {} or <> - and trim surrounding whitespace first. The shared
appendSuffix helper is used by MediaFile.FullTitle, MediaFile.FullAlbumName
and Album.FullName so all consumers behave consistently.
2026-07-20 21:49:14 -04:00
Deluan
c35b14dd74 chore(deps): update go-taglib to v2.3.1
Signed-off-by: Deluan <deluan@navidrome.org>
2026-07-20 09:49:48 -04:00
Deluan Quintão
6c2644d208
feat(ui): remember 'items per page' selection across sessions (#5819)
* feat(ui): add perPageStore helper for items-per-page persistence

* feat(ui): persist items-per-page selection in localStorage

* feat(ui): enable per-page persistence on album grid, missing files and playlist tracks

* feat(ui): restore saved album grid page size on fresh load

* feat(ui): restore saved items-per-page on list load

* fix(ui): move defaultRowsPerPageOptions to perPageStore to satisfy react-refresh lint

* fix(ui): correct defaultRowsPerPageOptions import in List and add render test

* refactor(ui): default getStoredPerPage fallback to the first option

The fallback equalled options[0] at three of four call sites; default it so
those sites stop restating it. SongList and useAlbumsPerPage still pass an
explicit fallback where it legitimately differs from the first option.

* fix(ui): persist only user-selected page sizes, validate album size against width

Persisting on every pagination context value let a URL-injected perPage (e.g.
the perPage=15 album link in NowPlayingPanel) or a forced single-option mobile
grid overwrite the saved preference. Persist only a value that is an actual
option in a multi-option selector. Also validate the album grid's redux session
value against the current width so a size chosen at a wider breakpoint can't
leave an out-of-range selector.

* fix(ui): restore saved items-per-page on the radio list

RadioList passed a hard-coded perPage that overrode List's stored seed via the
props spread, so a radio-list page size was persisted but never restored. Seed
it from storage like the other list views.

* fix(ui): persist page size only on an actual selector change

Watching the pagination context value meant any valid value persisted itself:
loading a list at a breakpoint where the saved size is invalid stored the
responsive fallback, and opening a URL with a valid ?perPage= stored that too,
either way discarding the user's real preference. Inject a wrapped setPerPage
instead, so only the rows-per-page selector writes. This also drops the
option-validation heuristics, which the new trigger makes unnecessary.
2026-07-19 18:59:37 -04:00
Deluan Quintão
bf79d2f3a2
refactor(plugins): remove non-functional experimental manifest option (#5821)
The `experimental.threads` manifest option never actually worked, so drop
it from the schema, the generated types, the loader and the docs.
2026-07-19 18:52:30 -04:00
Deluan Quintão
fed9665060
fix(streaming): surface why a transcode decision failed (#5820)
* fix(subsonic): surface the reason a transcode decision failed

getTranscodeDecision returned a bare "failed to make transcode decision"
with no clue why, and the probe command ran ffprobe with -v quiet, so even
the server log bottomed out at "exit status 1". A user whose files had been
moved by an external tool only saw the opaque error.

ProbeAudioStream now returns a typed ProbeError that separates the file path
from the reason: ffprobe runs with -v error so its stderr diagnostic is
captured, and a missing or unreadable file is reported as "file not found"
rather than ffprobe's misleading "Invalid data found". The handler logs the
full detail (including the path) and returns the reason to the client with
the server path stripped out.

Reported-by: Tolriq (Symfonium)

* refactor(ffmpeg): use errors.AsType for ExitError match

probeErrorReason used the older var+errors.As form while the rest of the
codebase (and its sibling transcodeFailureReason) uses the generic
errors.AsType. Switch to it for consistency; behavior is unchanged.

* fix(subsonic): return error 70 when the source file is missing

A getTranscodeDecision probe failure was always reported as generic error 0.
When the source file is gone (moved or deleted out from under the DB), that is
a not-found condition, so return the standard Subsonic error 70 ("data not
found") instead — matching what the endpoint already returns for an unknown
mediaId. Files that exist but are corrupt or unreadable stay error 0.

ProbeError now wraps the underlying cause and implements Unwrap, so the handler
detects the case with errors.Is(err, fs.ErrNotExist).

* fix(ffmpeg): keep probe error paths out of client-facing reasons

Addresses review feedback on the ProbeError type: the Reason field doubled as
both the log detail and the client message, so an ffprobe launch failure (a
*os.PathError from fork/exec) could leak the ffprobe binary path to clients,
and an unexpected stat error was reduced to "file not accessible" in the log.

Split the two concerns: Reason now holds only a path-free, client-safe string
(built at construction), while Error() logs the full underlying cause. Launch
failures return a generic "could not read file" instead of the raw exec error.
SafeReason no longer does substring path-stripping (removing the empty-Path
edge case); the stripping happens once, against ffprobe's stderr.

* fix(subsonic): don't report a broken ffprobe as a missing media file

Two issues from review of the previous commit:

Code 70 was selected with errors.Is(err, fs.ErrNotExist), but a launch failure
of a deleted ffprobe binary is an *os.PathError that also wraps fs.ErrNotExist.
A server-side ffprobe problem was therefore reported to clients as a missing
media file. ProbeError now carries an explicit NotFound flag, set only on the
file-access branch, and the handler keys the code off that instead of the chain.

ffprobe can also exit 0 while yielding no audio stream (an audio-suffixed
container holding only video). That parse failure was returned unwrapped, so
clients got "internal error"; it is now wrapped in a ProbeError too.
2026-07-19 18:51:32 -04:00
Deluan Quintão
e6597398c2
feat(scrobbler): exponential backoff for scrobble retries during outages (#5818)
* feat(scrobbler): add exponential backoff delay helper

* feat(scrobbler): back off retries up to 4m during outages

* test(scrobbler): verify backoff schedule with synctest; clarify backoffDelay doc

Adds a testing/synctest-based test that drives the real run loop against a
failing service and asserts the exact 5s/10s/20s/40s retry schedule and the
drain-on-recovery reset, addressing the review note that the run loop's
behavior was untested. Also clarifies the backoffDelay doc comment: the
argument is a zero-based retry index.
2026-07-19 13:36:05 -04:00
Deluan Quintão
5927e693d1
feat(jellyfin): filter items by year and record label (#5817)
* feat(persistence): add AlbumRepository.GetYears for distinct album years

* test(persistence): verify GetYears de-duplicates repeated years

Regression test that adds two albums with the same non-zero max_year
(2005) and verifies that GetYears() returns that year exactly once,
ensuring the SQL DISTINCT clause is applied correctly. Catches any
future removal of DISTINCT from the GetYears query.

* feat(jellyfin): add legacy /Items/Filters endpoint (genres + years)

* feat(jellyfin): add /Studios endpoint from record label tags

* refactor(persistence): drop duplicate columns in tagRepository.GetAll

* fix(jellyfin): exclude missing albums from filter years

GetYears only filtered max_year > 0, so albums whose files were all removed
(missing=true, kept when Scanner.PurgeMissing=never) contributed stale years
to /Items/Filters. Filter them out like the normal album listings do. Also
return an empty slice from the MockAlbumRepo to match the real repository.

* feat(jellyfin): filter /Items by Years=

* feat(jellyfin): filter /Items by StudioIds= (record labels)

* feat(jellyfin): scope filter and studio lists to ParentId library

* refactor(jellyfin): extract parentIDScope and libraryScopeFilter helpers

Collapse the three inline resolveLibraryScope(dto.DecodeID(parentid)) call
sites and the duplicated empty-scope guard into two small helpers, so the
empty-scope=unrestricted contract lives in one place. Reuse the existing
names() helper in the Years= e2e test.

* feat(jellyfin): expose record labels as album Studios

Add a Studios field to the album BaseItemDto, populated from the record-label
tags and gated behind Fields=Studios (matching Jellyfin's ItemFields
convention). Studio ids reuse the record-label tag identity, so they round-trip
with the /Studios list and the StudioIds= filter. Real Jellyfin leaves Studios
empty for music; Feishin reads it as the album's record label.
2026-07-19 12:39:31 -04:00
Deluan
b27d6f61ae fix(db): make album ReplayGain backfill scale to large libraries
The windowed-CTE backfill was compiled as a correlated scalar subquery
re-evaluated once per album (a full media_file group-by + window sort each
time), which never finished on a large library. Stage the ReplayGain-bearing
rows into an indexed temp table once and update only the affected albums:
~14s on a 727MB / 6945-album library, vs. effectively never.
2026-07-18 22:59:53 -04:00
Deluan Quintão
4efd92cf83
feat(server): expose album-level ReplayGain in albums (#5816)
* feat(model): aggregate album ReplayGain in ToAlbum

* feat(db): add nullable album ReplayGain columns with backfill

* feat(persistence): persist album ReplayGain fields

* feat(jellyfin): expose album NormalizationGain from ReplayGain

* refactor(model): lazy-init mostFrequentPtr map; clean up RG test rows

* fix(db): backfill album ReplayGain with most-frequent value, not max

A plain max() picked a minority outlier that diverged from MediaFiles.ToAlbum
(which uses the most-frequent value), and GetTouchedAlbums never re-derives an
unchanged album, so the wrong value would persist. Reproduce the modal
aggregation via grouped CTEs, which also groups media_file once instead of a
per-album correlated scan.

* refactor(model): return an owned pointer from mostFrequentPtr

Avoid aliasing a MediaFile field so the resulting Album is independent of the
source slice.
2026-07-18 22:19:29 -04:00
Deluan Quintão
7234ea23b7
feat(jellyfin): expose NormalizationGain from ReplayGain tags (#5815)
* feat(jellyfin): expose NormalizationGain from ReplayGain tags

Adds NormalizationGain and AlbumNormalizationGain to Audio BaseItemDtos,
sourced from the scanner's ReplayGain values (REPLAYGAIN_* tags, with R128_*
already converted to the same -18 LUFS reference). Same wire contract as real
Jellyfin: PascalCase keys, omitted when absent, no Fields gating. Album items
intentionally omit the field: model.Album has no gain column and Feishin reads
gain from song DTOs.

* test(jellyfin): e2e coverage for NormalizationGain fields

* test(jellyfin): drop redundant NormalizationGain passthrough spec

The JSON-casing spec already proves the mapped values (the substring
"NormalizationGain":-3.5 can only appear if the passthrough worked), so the
direct-struct spec added no coverage.

* style(jellyfin): use ASCII punctuation in gain comment
2026-07-18 20:26:14 -04:00
Deluan Quintão
59f1b4206c
fix(jellyfin): serve playlist covers regardless of visibility (#5813)
The image endpoint only served a private playlist's cover when the request
carried a token identifying its owner or an admin. But clients fetch cover
URLs without credentials — real Jellyfin's image routes are anonymous — so
every private playlist rendered the generic placeholder in Jellyfin clients
(observed in production), while the same covers displayed fine through the
always-authenticated Subsonic/native APIs.

Drop the gate and serve playlist covers like album/artist/track artwork:
playlist ids are unguessable without credentials, so anonymous access does
not meaningfully expose private playlist contents.
2026-07-18 19:36:12 -04:00
Deluan Quintão
3158451b8d
refactor(server): drop redundant error return from req.Strings parsing (#5812)
* refactor(req): drop redundant error return from Strings

The error from Strings carried no information beyond emptiness — it fired
exactly when the param was absent — and nearly every caller discarded it with
a blank identifier. Strings now just returns the values (empty when absent),
making the common optional-list reads one clean expression.

The few required-param callers (scrobble, createShare) check for emptiness and
return the same Subsonic error code 10 as before; their e2e tests now pin that
code. Ints and Times keep their contracts by synthesizing ErrMissingParam
themselves, so selectedMusicFolderIds is untouched. The jellyfin parseFields
helper is inlined away, since ParseFields(p.Strings("fields")...) now
compiles directly.

* docs(req): clarify Strings returns nil when param is absent
2026-07-18 19:30:04 -04:00
Deluan Quintão
1e82f515c4
fix(jellyfin): honor repeated Fields query params (#5811)
The Fields param was read with StringOr, which keeps only one value, so a
request sending it as repeated params (Fields=Genres&Fields=MediaSources) — as
Finamp and Feishin do — lost all but the first. Field-gated data like
MediaSources was then omitted for Audio items even though the client asked for
it; the comma-separated form happened to work because ParseFields splits on
commas. Real Jellyfin accepts both forms.

ParseFields is now variadic and a parseFields helper reads every repeated value
via req.Values.Strings, applied to the item list, single-item, and playlist
endpoints.
2026-07-18 18:59:08 -04:00
Deluan Quintão
09ac342f5a
fix(jellyfin): split Artists/ArtistItems per track artist (#5810)
* fix(jellyfin): split Artists/ArtistItems per track artist

The Jellyfin API returned a single ArtistItems entry built from the flattened
display artist, so a multi-artist track (e.g. "De La Soul feat. Redman") lost
its individual artists and dropped every artist id but the first — while the
same track's OpenSubsonic response correctly split them. Real Jellyfin splits
Artists/ArtistItems one entry per track artist.

Build both from Participants[RoleArtist], which is already loaded on the search
and browse paths, falling back to the flattened display fields when absent.
AlbumArtists stays a single credit, matching real Jellyfin.

* fix(jellyfin): omit empty Artists in the fallback path

When a track has no participants and no display artist, the fallback set
Artists to a single-element slice holding an empty string. Only populate it
when the display artist is non-empty, so untagged tracks omit the field
instead of sending [""].
2026-07-18 18:16:52 -04:00
Kendall Garner
9c7cf7d734
feat(jellyfin): expose genreitems for song/album (#5809)
* feat(jellyfin): expose genreitems for song/album

* use encode id instead
2026-07-18 17:46:11 -04:00
Deluan
e4a423db11 feat(jellyfin): emit refreshResource events on favorite/rating changes
Like Subsonic's setStar/setRating, the Jellyfin favorite and rating
endpoints now broadcast a refreshResource event, so the web UI updates
immediately when a Jellyfin client changes an annotation.

Also fixes model.GetEntityByID to propagate unexpected repository errors
instead of reporting them as not-found, preserving the 500-vs-404
distinction for all its callers.
2026-07-18 16:50:23 -04:00
Deluan Quintão
f61b4eee21
fix(deezer): pick most-popular artist among same-name matches (#5808)
* fix(deezer): pick most-popular artist among same-name matches

The Deezer agent searched with order=RANKING and always took the
top-ranked result (artists[0]) as long as its name matched. Deezer's
RANKING order isn't reliable for homonyms, so for names shared by
several artists (e.g. "Queen") it locked onto a low-popularity artist
whose Top Tracks are empty, leaving getTopSongs empty.

Among the exact-name matches, select the one with the highest fan
count instead. This resolves "Queen" to the real band (Deezer ID 412)
and preserves the existing ErrNotFound behavior when nothing matches
the name exactly.

Fixes #5802

* fix(deezer): improve artist disambiguation by ranking exact-case names

Signed-off-by: Deluan <deluan@navidrome.org>

---------

Signed-off-by: Deluan <deluan@navidrome.org>
2026-07-18 16:40:10 -04:00
Deluan Quintão
deaa5e6c02
feat(ui): playlist favourites (heart, list filter, sidebar favourites-only toggle) (#5805)
* feat(playlists): register starred REST filter on playlist repository

* feat(ui): add persisted sidebarPlaylistsOnlyFavourites setting

* feat(ui): playlist favourites heart column and list filter

* feat(ui): favourite heart on playlist details header

* feat(ui): sidebar favourites-only playlist toggle with live refresh

* fix(playlists): qualify id in REST filter to avoid ambiguous column

The annotation join in selectPlaylist made a bare id filter ambiguous, so
GET /api/playlist?id=X (react-admin getMany, used by the sidebar refetch and
useResourceRefresh) failed with 'ambiguous column name: id'. Register
idFilter("playlist") like the album/artist/mediafile repos.

* fix(ui): refresh favourites sidebar on local star toggle

The SSE broker skips the client that originated a star, so the acting client
never got the refreshResource echo and its favourites-only sidebar went stale.
Key the sidebar query on a fingerprint of locally-known starred playlists so a
star/unstar on this client refetches; SSE still covers other clients.

* style(ui): prettier-format PlaylistsSubMenu test

* feat(ui): refine playlist favourites layout

- Move the favourite heart column to just before the edit button
- Space the Playlists sidebar header text from its action icons
- Use a list icon instead of a cog for the playlist-management action

* feat(ui): make the playlist Favourite column toggleable

Move the heart into the toggleable fields map so users can show/hide it
from the column selector like the other optional columns, keeping it last
so it stays just before the edit button.

* refactor(ui): memoize sidebar star fingerprint and gate it on favourites-only

- Derive starFingerprint via useMemo on the playlist data reference instead
  of recomputing sort/join inside useSelector on every app-wide dispatch.
- Only include the fingerprint in the query payload when favourites-only is
  on, so a star toggle no longer refetches the sidebar when it shows all
  playlists.

* fix(ui): don't refetch favourites sidebar on SSE events when showing all

When favourites-only is off the sidebar shows every playlist, so a star
event from another client changes nothing visible. Gate the SSE-driven
refresh counter (and its payload key) on onlyFavourites so the sidebar no
longer redraws on unrelated playlist star events.

* fix(ui): address automated review feedback on playlist favourites

- Ignore a persisted favourites-only preference when EnableFavourites is off,
  so disabling the feature later can't strand a filtered sidebar (Codex P2).
- Make PlaylistLove's datagrid header props explicit (source/sortable via
  defaultProps, className forwarded) instead of relying on prop pass-through.
- Add aria-label to the SubMenu secondary action button.
- Cover the PlaylistLove list column with tests (Codex P1).
2026-07-18 14:45:47 -04:00
Deluan Quintão
64430af9ce
feat(ui): add Radio to Default View options (#5801) 2026-07-17 21:53:17 -04:00
Deluan Quintão
85132240e0
feat(smartplaylist): per-playlist refreshDelay for stable daily/weekly playlists (#5790)
* feat(utils): add ParseDuration/FormatDuration with day and week units

* feat(criteria): add per-playlist refreshDelay to smart playlist rules

* feat(smartplaylist): honor per-playlist refreshDelay in refresh gate

* feat(subsonic): compute smart playlist validUntil from effective refresh delay

* fix(playlists): reset smart playlist evaluation window when rules change via API

* refactor(utils): flatten FormatDuration recursion, single-pass duration regex

* fix(playlists): address PR review feedback

- Reset EvaluatedAt to nil instead of zero-time on rules change and NSP
  re-import, so getPlaylist(s) never reports year-1 Changed/validUntil in
  the window between an edit and the next owner read
- Parse negative d/w durations so they are rejected with the consistent
  "negative duration" error instead of "unknown unit"
- Quote input in the negative-duration error, matching the parse error
- Gate per-playlist RefreshDelay behind IsSmartPlaylist, matching its doc
2026-07-16 22:20:35 -04:00
Deluan
ae7e81e33f docs(jellyfin): sync README with current implementation
Update the Jellyfin API README to cover changes that landed after it was
written: add the Lyrics and AudioMuse-AI endpoints to the implemented-endpoints
table, document the AlbumIds filter (Feishin), Recursive=false handling, and
the Jellyfin.MaxConcurrentStreams config option. Mention Symfonium as a client
of the AudioMuse-AI endpoints. Update the lyrics limitation for the
singleflighted cache loader shipped in #5792. Drop two stale known-limitation
entries: sonic similarity (plugin metadata agents already feed
InstantMix/Similar) and MD5-hash ids (the codec round-trip is symmetric, and
with the API unreleased no client can hold a raw un-encoded id).
2026-07-16 20:48:56 -04:00
Deluan Quintão
27f0210392
fix(scrobbler): tolerate out-of-order playback reports (#5793)
* fix(scrobbler): tolerate out-of-order playback reports

Clients may fire reportPlayback requests concurrently (Feishin sends
'starting' and 'playing' in parallel, and the previous track's 'stopped'
races the next track's start), so reports can be processed out of order.
Two cases corrupted the now-playing session: a late 'starting' for the
track already playing downgraded the session state, freezing position
estimation at 0:00 until the next report; and a late 'stopped' for the
previous track removed the new track's session and dispatched a playback
report mislabeled with the new track's metadata, causing presence-style
plugins (e.g. Discord Rich Presence) to clear or show stale state.

ReportPlayback now ignores a 'starting' report when the session already
has the same track in playing state, and ignores a 'stopped' report for
a track other than the current session's - skipping both the session
removal and the plugin dispatch, while still counting the play and
dispatching external scrobbles for the stopped track.

Reported in https://github.com/jeffvli/feishin/issues/2131

* fix(scrobbler): serialize session writes to close starting/playing race

The out-of-order 'starting' guard checked the session cache before the
media-file load, leaving a window where a concurrent 'playing' report on a
fresh session could write between the check and the write, and still be
overwritten back to 'starting'. Session check-then-write sections are now
serialized by a mutex, with the guard re-checked after the load. Also
tightens the guard comment to say 'playing session', matching the condition.

Found by Codex review on #5793.

* fix(scrobbler): fully exit ReportPlayback when ignoring out-of-order reports

The out-of-order guards used 'break', which only exits the switch, so the
post-switch NowPlaying block still ran for an ignored 'starting' report and
enqueued a NowPlaying dispatch with the stale report's position - potentially
overwriting a pending correct-position entry, since the queue is keyed by
client. Return nil instead, so ignored reports have no side effects.

Found by Gemini review on #5793.
2026-07-16 20:47:47 -04:00
Deluan Quintão
756df9decf
fix: dedupe and cap concurrent lyrics plugin fetches (#5792)
* fix: dedupe and cap concurrent lyrics plugin fetches

Clients like Finamp prefetch lyrics for several queue tracks at once. The
resulting burst of concurrent plugin calls can rate-limit the primary
lyrics provider into a timeout, making the plugin fall back to a lower
quality source and cache the bad result.

SimpleCache.GetWithLoader now deduplicates concurrent loads of the same
key via singleflight, with every waiter receiving the winner's result or
error. The Jellyfin lyrics loader is detached from the request context so
one cancelled request cannot fail the load for all waiters, and the
lyrics adapter caps in-flight plugin calls at 2 per plugin, queueing the
rest. As a side effect, the cached HTTP client used by the Last.fm,
Deezer and ListenBrainz agents also collapses identical concurrent
requests into a single upstream call.

* fix: harden lyrics concurrency fixes per review

Replace the stringified singleflight keys with a per-cache flight map
keyed by the cache key type itself, eliminating potential key collisions
for non-string keys, the nil-interface assertion panic, and the
stringification overhead. Release the lyrics semaphore slot via defer so
a panicking plugin call cannot leak it, and bound the detached lyrics
load with a one-minute timeout so a hung plugin cannot pin its
singleflight and semaphore slot indefinitely.
2026-07-16 20:10:35 -04:00
Deluan Quintão
29f481cd7b
feat(jellyfin): lyrics endpoint and Lyric stream advertising (#5791)
* feat(jellyfin): add LyricDto and lyrics mapper

* feat(jellyfin): advertise Lyric media stream for embedded lyrics

* feat(jellyfin): implement GET /Audio/{itemId}/Lyrics

* feat(jellyfin): advertise pipeline-resolved lyrics in PlaybackInfo

* feat(jellyfin): advertise server version 10.9.11 for client lyrics gates

* test(jellyfin): e2e coverage for lyrics endpoint and advertising

Seeds "Stairway To Heaven" with an embedded LRC lyric tag (lyrics:eng)
and covers PlaybackInfo's Lyric MediaStream, GET /Audio/{id}/Lyrics,
and the HasLyrics badge end to end.

Fixes a bug the new seed exposed: HasLyrics and the Lyric MediaStream
gate compared mf.Lyrics against "", but the persistence layer never
stores an empty string post-scan (it normalizes to the JSON sentinel
"[]"), so every track was reporting HasLyrics=true. Both call sites
now parse the column via StructuredLyrics()/LyricList.Main() instead.

* fix(jellyfin): cheap sentinel check for embedded lyrics advertising

* chore(jellyfin): trim over-budget comments in lyrics code

* test(jellyfin): cover lyrics pipeline error and nil-start cue skip

* docs(jellyfin): document lyrics support and follow-ups in README

* refactor(jellyfin): promote embedded-lyrics sentinel check to MediaFile

The "[]" no-lyrics sentinel is persistence-layer knowledge; expose it as
model.MediaFile.HasEmbeddedLyrics() instead of a dto-local helper. Also
dedupe the test lyrics-cache construction and pre-size the media stream
slice.

* refactor(jellyfin): consolidate tick conversions around one constant

ticksPerMillis is now the single source of the 100ns-tick unit; the
scrobble handlers' three inline /10_000 divisions become
dto.MillisFromTicks.

* fix(jellyfin): align lyric advertising with the serving predicate

PlaybackInfo advertised on any non-empty LyricList while the endpoint
404s when the main lyric has no lines; both now share servableLyric.
Handler tests also send hex-encoded ids to match real traffic.

* chore(jellyfin): drop unneeded lyrics package alias in e2e suite
2026-07-16 14:39:11 -04:00
Deluan
c582ed31fa feat(jellyfin): add authenticated System/Info endpoint
Wire up GET /System/Info returning the previously unused dto.SystemInfo,
available to any authenticated user, matching real Jellyfin's authorization
(FirstTimeSetupOrIgnoreParentalControl, not admin-only). Feishin calls this
endpoint on connect and reads Version to feature-gate; it previously got the
unhandled-route 404.

The advertised version stays 10.8.13: Feishin unlocks structured lyrics and
public-playlist share permissions at >=10.9.0, and this API serves neither
(no lyrics endpoint; playlist user permissions are stubs), so a higher
version would falsely advertise capabilities.
2026-07-16 08:53:44 -04:00
Deluan
caa0043030 fix(jellyfin): honor AlbumIds filter on /Items
Feishin fetches an album's tracks with AlbumIds=<id>&IncludeItemTypes=Audio&Recursive=true, but the /Items handler never read the AlbumIds parameter, so the request degenerated into the entire library sorted by album: every track (with MediaSources, when requested) was counted and streamed for what should be one album's worth of songs — very slow on large libraries, and wrong results. Parse AlbumIds like GenreIds (comma-separated and repeated spellings, hex-decoded) and filter songs through a new filter.ByAlbumID helper, keeping the album_id column knowledge in the filter package.
2026-07-15 23:29:59 -04:00
Deluan
1d5efdd5a0 fix(jellyfin): don't truncate InstantMix to the Similar ceiling
Finamp's Radio Mix requests /Items/{id}/InstantMix?limit=250, but getInstantMix
clamped the limit to maxSimilarLimit (100), so the queue was cut to 100 tracks.

A mix is a playback queue, not a "related items" list, so it gets its own
ceiling instead of sharing the Similar one. The Similar handlers keep 100.

Verified against a live library: the sonic provider supplies all 250 tracks for
a seed that previously returned 100.
2026-07-15 21:21:26 -04:00