107 Commits

Author SHA1 Message Date
cucadmuh de36f79e46 chore(ci): ESLint workflow and path-aware ci-ok merge gate (#1170) 2026-06-24 18:42:59 +03:00
Psychotoxical a5313d5cb1 fix(cover): embed fanart.tv project key so from-source builds work (#1139)
The project key was injected only at our build time (CI secret / option_env!),
so AUR, Nix and any from-source build had no key baked in and the External
Artwork toggle was inert there. Commit it as a source literal (like the Last.fm
key, and as fanart.tv terms expect: the app ships a project key, users add
their own on top via BYOK). Drops the now-redundant CI wiring.
2026-06-20 23:03:12 +02:00
Psychotoxical b950d4704b feat(cover): artist artwork from fanart.tv (off by default) (#1137)
* feat(cover): add artist_artwork_lookup table + accessors

Image-scraper P0 (design-review §12): additive library-SQLite migration 013
plus get/upsert/clear-per-server accessors for the external artist-artwork
lookup (fanart.tv). Render never reads it; the on-demand cover ensure path
and the mbid_ambiguous 24h negative cache use it. server_id = serverIndexKey.

* feat(cover): add fanart.tv + getArtistInfo2 provider layer

Image-scraper P0 (§7/§19/§23): new cover_cache/external.rs — Rust-side
getArtistInfo2 tag-MBID resolution plus fanart.tv v3/music URL + first
artistbackground fetch (BYOK client_key sent in addition to the project
api_key per fanart.tv ToS, §22). Extract a shared build_subsonic_url helper
in fetch.rs (cover URL behaviour unchanged). Add a dedicated low-concurrency
fanart_http_sem so external HTTP never starves Navidrome (§26). URL builders
unit-tested; wired into ensure_inner next.

* feat(cover): wire fanart.tv external branch into ensure_inner

Image-scraper P0 (§16): on-demand artist `fanart` ensures try fanart.tv
before the Navidrome fallback. MBID resolved Rust-side via getArtistInfo2
(§23, tag MBID); on a miss it falls through WITHOUT a .fetch-failed marker so
Navidrome stays the display fallback (§28). External tiers are written as
{tier}-fanart.webp in the same entity dir (same cacheKind, §16) — 2000 + 512
(matryoshka §17); peek prefers them for the fanart surface. Dedicated
low-concurrency fanart lane (§26); .miss-fanart ~30min negative marker.
Additive IPC args (externalArtworkEnabled, surfaceKind), off by default and
gated by PSYSONIC_FANART_KEY — inert until a render surface opts in (P1).
Quality gate (§11), name->MusicBrainz (§19), and lookup-table writes are P1.

* feat(cover): fanart-first peek for the fanart surface

Image-scraper P0: for an artist `fanart` ensure, the early peek serves only
the external {tier}-fanart.webp tiers; if none exist yet it returns None so
ensure runs the external branch (fetch fanart) instead of short-circuiting on
a cached Navidrome tier. Realises "fanart prioritised" (§18) for the opt-in
surface; Navidrome stays the fallback inside the branch's miss path.

* chore(cover): dev-only artist-fanart spike helper

DEV-only window.psyFanartSpike(name) — resolves an artist by name and fires
the real cover_cache_ensure with externalArtworkEnabled+surfaceKind=fanart to
verify the P0 pipeline against a live server (with PSYSONIC_FANART_KEY set).
Not wired in production.

* feat(cover): §11 quality gate for the fanart surface

Before an external fanart fetch, check whether a Navidrome tier already on
disk is an HQ ~16:9 image (width >= 1280, aspect 1.6-2.0) and skip the fetch
if so — square artist portraits never satisfy it, so the common case still
fetches. Reads tier dimensions only (no full decode). Rust consts per the
design review. Unit-tested predicate.

* feat(cover): persist fanart resolution in artist_artwork_lookup (§12)

Wire the lookup table as both the MBID resolution cache and the negative
cache: a cached MBID skips the getArtistInfo2 round-trip; no_mbid/mbid_ambiguous
back off 24h and miss 30min from updated_at before re-querying. Writes
hit/miss/no_mbid with mbid/mbid_source/provider; transient network errors are
not cached. All store reads/writes run off the async executor via
spawn_blocking and no-op before login. Store reached via app.try_state::<LibraryRuntime>().

* feat(cover): compile-time fanart key fallback + album/name IPC args

A runtime PSYSONIC_FANART_KEY still wins (dev), else the key baked in at build
time via option_env! (release). Add additive artistName/albumTitle ensure args
as context for the §19 name->MusicBrainz fallback (inert until the render
passes them). Library backfill passes None.

* feat(settings): add External Artwork Scraper toggle under Integrations

Master toggle (themeStore, off by default per §20) in a new Integrations
subsection, alongside the other opt-in third-party categories. Contacts
fanart.tv only when enabled. i18n across all 9 locales.

* feat(cover): wire fanart background into the fullscreen player (§28)

New useArtistFanart hook resolves a fanart.tv 16:9 background via a dedicated
cover_cache_ensure (surfaceKind=fanart) — it bypasses the shared peek/disk-src
cache (the {tier}-fanart.webp surface is keyed differently) and reuses
coverDiskUrl for the asset URL. Fullscreen background priority is now
fanart -> Navidrome artist image (cover pipeline) -> album cover; the live
useFsArtistPortrait probe is deleted (§28). Additive ensure opts
(surfaceKind/artistName/albumTitle); externalArtworkEnabled is derived in
ensureArgsFromRef from the master toggle and restricted to the artist fanart
surface, so plain cover ensures are unaffected.

* feat(cover): generalize external surface to fanart + banner (§13)

surfaceKind='banner' fetches the fanart.tv musicbanner array -> {tier}-banner.webp
in the same entity dir; fanart stays the 16:9 artistbackground. The ensure
branch, peek, lookup rows (per-surface surface_kind), miss marker
(.miss-<surface>) and tier suffix are all surface-parameterised. The §11
quality gate stays fanart-only (the banner strip has its own aspect). Unit
test for the surface->fanart JSON key map.

* feat(artist): fanart banner on the artist-detail header (§13, Option B)

The artist-detail header gets an album-detail-style background layer: fanart.tv
banner (musicbanner) -> the 16:9 fanart background cropped to the strip ->
empty. Both via a shared useArtistExternalImage hook (useArtistBanner /
useArtistFanart); each fetches on demand and shares the Rust cache, so the
header and the fullscreen player warm each other's images. The header is its
own stacking context (isolation) so a z-index:-1 banner clips behind the avatar
+ meta with no content wrapper; the album-style framing (padding/radius/clip)
is applied only when a banner is shown, so the off-by-default case stays
pixel-identical.

* refactor(artist): reuse album-detail header structure for the fanart banner

The artist-detail header now uses the same album-detail-* container classes as
AlbumHeader (header/bg/overlay/content/hero) with the fanart banner as the
background; the Back button moves inside the header. A surgical
`artist-detail-bleed` cancels the artist page's .content-body padding so the
banner is full-bleed to the container edges, matching the album header exactly
instead of the earlier inset card. Reverts the experimental artist-specific bg
CSS.

* feat(cover): drop artist_artwork_lookup rows on clear-cover-cache (§12/B.4)

cover_cache_clear_server already removed the server's whole cover dir (so the
{tier}-fanart.webp / -banner.webp tiers + .miss-* markers go with it); also
clear the artist_artwork_lookup rows for that server (off-thread) so no stale
resolution state lingers. Automatic toggle-off purge deferred — turning the
toggle off already hides external artwork (render is gated), and explicit
cache-clear now cleans external state too.

* feat(cover): name->MusicBrainz album-confirmed MBID resolution (§19)

When getArtistInfo2 has no tag MBID and the ensure carries the artist name +
an album in context (fullscreen), one MusicBrainz release-search query resolves
the artist MBID: the primary artist across score>=90 releases wins, conflicting
ids -> mbid_ambiguous (24h backoff), none -> no_mbid. Sends the required
User-Agent; a single-permit musicbrainz_sem + >=1s spacing holds us under MB's
rate limit. mbid_source=musicbrainz persisted. Banner surface (no album
context) correctly skips this. Pure classify/escape helpers unit-tested.

* fix(cover): enable banner surface in ensureArgsFromRef

externalEnsureFields only set externalArtworkEnabled for surfaceKind 'fanart',
so the 'banner' surface never fired — the artist-detail header always fell back
to the fanart image instead of the fanart.tv musicbanner. Both external artist
surfaces (fanart/banner) now enable the external branch.

* feat(settings): optional BYOK personal fanart key field

Add an optional personal fanart.tv API key field to the External Artwork
Scraper block (shown when the toggle is on): a masked input, a saved/in-use
status line, and the simple note that it is sent in addition to the app key.
Persisted in themeStore and plumbed through cover_cache_ensure
(externalArtworkByok); Rust prefers the settings key, falling back to the
PSYSONIC_FANART_CLIENT_KEY dev env. i18n x9.

* fix(cover): resolve artist-page fanart image collision on navigation

The artist-detail header keyed its fanart/banner hooks on the route `id`,
which flips immediately on navigation while `artist`/`albums` refetch a beat
later. The mismatched ensure wrote the previous artist's image under the new
artist's id (e.g. Sepultura's image under Lordi's id).

- key on the loaded `artist.id`, not the route `id`, so id/name/album always
  describe the same artist
- pick the §19 album context from an album that actually belongs to this
  artist (`albums.find(a => a.artistId === artist.id)`), so a stale album can't
  run a mismatched name→MusicBrainz query or cache a wrong `no_mbid`
- reset `src` on every input change in `useArtistExternalImage` so a previous
  artist's image never lingers while the new one resolves

* fix(cover): strip trailing album qualifier before MusicBrainz lookup

Library titles like "Show No Mercy (2004 Remastered)" or "Album [Deluxe
Edition]" failed the §19 MusicBrainz release query, blocking name-confirmed
MBID resolution. `normalize_album_for_mb` strips a single trailing
parenthetical/bracketed qualifier; leading qualifiers (e.g. "(What's the
Story) Morning Glory?") are left intact. Unit-tested.

* fix(cover): don't cache no_mbid when album context is unavailable

The banner ensure could fire before the artist's albums loaded, with no album
in context. The old code cached `no_mbid` there and the 24h backoff then
blocked the later ensure that arrived *with* album context. Could-not-attempt
is not tried-and-failed: the no-album branch now returns without persisting.

* fix(cover): don't emit tier-ready for external fanart/banner surfaces

`try_external_fanart` emitted `cover:tier-ready` with the `{tier}-{surface}.webp`
path. That event is keyed by the canonical cover key (cacheKind/cacheEntityId/
tier, no surface), so the frontend `useCoverArtBridge` listener seeded the
Navidrome artist cover's disk-src cache with the external image — leaking
fanart/banner into the plain artist cover (avatar, fullscreen "navidrome-artist"
fallback) even with the scraper toggled off.

Remove the emit: the fanart/banner hooks read the path from the
`cover_cache_ensure` return value, so no event is needed. (No disk-level
overwrite — the suffixed files are never matched by `tier_exists`; this was
frontend disk-src-cache cross-contamination.)

* fix(cover): wait for the final external background before showing it, with fade-in

The fullscreen player and artist-detail header flashed several backgrounds in
sequence while the fanart resolved (upscaled album cover → Navidrome artist
image → fanart), and the artist header could show the fanart first and then
swap to the banner.

- the album cover is no longer a background source — it only feeds the
  foreground thumbnail
- the external-artwork hooks return `{ src, pending }` so callers can tell
  "still resolving" (hold back) from "resolved, no image" (fall back now)
- fullscreen background: scraper on → fanart, empty while it resolves, Navidrome
  artist image only on a confirmed miss; scraper off → Navidrome artist image
- artist header: the banner is preferred — nothing shows while it resolves
  (no fanart flash), fanart is the fallback only once the banner misses
- both backgrounds preload the chosen image and fade it in (`onLoad` plus a
  `ref` `complete` check so an already-cached image, whose load event can fire
  before React attaches the handler, still appears). The header fade is a
  scoped inline opacity so the shared `album-detail-bg` class is untouched.

* ci(release): pass PSYSONIC_FANART_KEY into the macOS + Linux builds

* refactor(cover): extract external-artwork ensure into its own module

Pure code move: the on-demand fanart/banner fetch, the quality gate, the
surface-aware peek and the lookup-table cache move from cover_cache/mod.rs
into cover_cache/external_ensure.rs. Behaviour unchanged; mod.rs 1877 -> 1488.

* chore(cover): remove dev-only fanart spike helper

The real render wiring now exercises the external ensure branch, so the
dev-only window.psyFanartSpike helper is redundant.

* feat(cover): purge external artwork on opt-out (B3)

New cover_cache_purge_external command: when the External Artwork toggle is
turned off, drop every fetched {tier}-{provider}.webp, .miss-{provider}
marker and artist_artwork_lookup row across all configured servers, leaving
the canonical Navidrome covers intact. Opting out now removes the
third-party-sourced data instead of just hiding it (design-review §9/§12/B.4).

* docs: changelog, credits and what's new for artist fanart (PR #1137)
2026-06-20 21:04:21 +02:00
cucadmuh c7d71ea57c feat(whats-new): remote release notes with dev workspace mode (#1058)
* feat(whats-new): remote release notes with dev workspace mode

Add WHATS_NEW.md, CI whats-new.md asset upload, and client fetch/cache
with embedded fallbacks. Dev and -dev builds read the full file from the
repo for debugging; RC/stable download the release asset on first use.

* fix(whats-new): render ## headings and add changelog tab

Parse h2 sections in release-notes markdown; load changelog alongside
highlights and let users switch views on the What's New page.

* fix(whats-new): prefetch on startup and fix CI typecheck prebuild

Prefetch whats-new asset when the shell loads on RC/stable builds.
Run prebuild:release-notes before tsc and coverage jobs so the
gitignored generated bundle exists in CI.

* docs: CHANGELOG and credits for What's New remote notes (PR #1058)

* fix(whats-new): always slice embedded release notes to current line

Drop full CHANGELOG embed for -dev bundles; tauri:dev still reads live
markdown from the repo. Ignore all of src/generated/ in git.

* fix(whats-new): fetch release asset via Rust to bypass CORS

Route whats-new.md download through fetch_url_bytes; rename the
technical tab label; add fetch unit tests (PR #1058 review).
2026-06-10 23:35:23 +03:00
cucadmuh 59a3261f3f fix(ci): refresh npmDepsHash before app-v* tag (#927)
* fix(ci): refresh npmDepsHash on channel branch before app-v* tag

Promote workflows push with GITHUB_TOKEN, so nix-npm-deps-hash-sync never
runs on the finalize commit. verify-nix ran after create-release and opened
a PR, leaving app-v* tags pointing at commits with stale npmDepsHash.

Move Nix hash/lock refresh into prepare-nix-sources (before tagging), commit
directly to the channel branch, and build from the prepared commit SHA.

* docs(changelog): note npmDepsHash CI fix (PR #927)
2026-05-30 14:07:59 +03:00
cucadmuh 7b06be5ba2 ci: make hot-path coverage gates required PR checks (#921)
* ci: make hot-path coverage gates required PR checks

Remove continue-on-error from frontend and Rust coverage jobs now that
the hot-path lists have stabilized; update docs and script headers.

* docs: note hard coverage gates in changelog and credits (PR #921)

* chore: drop credits entry for CI-only PR #921

Contributor credits are for user-visible work, not infra toggles.
2026-05-30 01:04:35 +03:00
cucadmuh c0d7079e88 chore(deps): restrict Dependabot to security updates only (#918)
Disable scheduled version-update PRs (open-pull-requests-limit: 0). Keep
grouped security PRs per ecosystem; symphonia migration ignores unchanged.
2026-05-29 23:19:18 +03:00
cucadmuh ad53b3f2d6 chore(deps): batch npm bumps and Dependabot Symphonia ignore (#904)
* chore(deps): batch remaining Dependabot npm bumps and ignore Symphonia 0.6

Bump @vitejs/plugin-react, @tauri-apps/cli, react-router-dom, and vitest;
configure Dependabot to skip symphonia >=0.6 and adapter-libopus >=0.3 until
the coordinated migration tracked in workdocs.

* chore(nix): sync npmDepsHash with package-lock.json

* chore: retrigger CI for PR checks

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-29 21:21:54 +03:00
cucadmuh be32792f5d chore: add SECURITY.md and Dependabot config (#893)
Document private vulnerability reporting and enable weekly npm/Cargo
dependency update PRs; link CONTRIBUTING to the new security policy.
2026-05-29 20:22:33 +03:00
cucadmuh 418b25914a feat(cover): unify cover pipeline and stabilize mainstage/now-playing (#870)
* chore(cover): scaffold cover module and rust cover_cache stub

Wave 0: src/cover/ skeleton per contracts.md §12, stub IPC commands
in cover_cache/mod.rs (no-op returns until phase B).

* feat(cover): add unified cover module and tier resolver (phase A)

Wave 1A: tiers, storage keys, resolveJs with cold/sibling races,
useCoverArt, CoverArtImage, layoutSizes, playback scope helpers,
coverSiblings tier ladder, deprecated shims on subsonicStreamUrl.

* feat(cover): rust disk cache and tier-ready events (phase B)

Wave 1B: cover_cache module with WebP tier encode, HTTP canonical 800 fetch,
cover_cache_* commands, cover:tier-ready / cover:evicted events, disk layout tests.

* feat(cover): prefetch hook, tier-ready handoff, library backfill IPC (phase B/C)

Wave 2: useCoverArtPrefetch, cover:tier-ready/evicted bridge, one-time IDB
cover key clear, prefetch registry drain, MainApp wiring.

* feat(cover): migrate dense grids to CoverArtImage and prefetch (phase D)

Wave 3A: dense surfaces use layout-native displayCssPx, surface=dense,
coverPrefetchRegister on Home/Albums/search; AlbumCard cell width from grid.

* feat(cover): migrate sparse surfaces and integrations (phase E sparse)

Wave 3B: sparse CoverArtImage/useCoverArt, lightbox tier 2000, ArtistHeroCover,
MPRIS/Discord/export integrations, playback chrome and detail heroes.

* feat(cover): revalidation scheduler and disk pressure gate (phase E+)

Wave 4: coverCacheMaxMb settings (en/ru), StorageTab disk usage, cover_cache_configure,
useCoverRevalidateScheduler, playbackServer uses cover fetchUrl; pressure watermarks.

* docs: CHANGELOG and credits for cover art pipeline PR #869

* fix(cover): stop webview getCoverArt storm on dense grids (429)

Dense surfaces no longer put rotating getCoverArt URLs in img src; load
disk via Rust ensure + convertFileSrc. Tier-ready notifies listeners instead
of invalidating IDB. Throttle background prefetch and cap Home registry.

* fix(cover): omit empty img src until cover URL is ready

React 19 warns on src=""; CoverArtImage uses undefined until disk/IDB
resolves; queue current track shows placeholder when src is still empty.

* fix(cover): disk cache by host index key, parallel ensure, asset protocol

Bind cover storage to serverIndexKey (library host), rename cover IPC/events,
fix REST base URL and Tauri flat args, enable protocol-asset for disk paths,
add prioritized ensure queue, and wipe legacy profile-UUID cache once.
Limit Vite dep scan to index.html so research/target HTML is ignored.

* fix(cover): WebP tiers, disk peek, home cache, asset URLs for mainstage

Encode lossy WebP (~82), write only missing tiers, library cover backfill,
and cover_cache_peek_batch for fast paint from disk. diskSrcCache + CSP
asset protocol; no IDB fallback when server is up. Session Home feed cache
with warm peek on return; BecauseYouLike deduped cover hook and high prefetch.

* feat(cover): per-server cache strategy and native library backfill

Move cover disk cache settings to Offline & cache with Lazy/Aggressive
per server, per-server clear, and no size cap. Run full-catalog backfill
on the Rust runtime (sync-idle wake, bounded HTTP, bulk 800px writes
without flooding the webview). Drop global prefetch limits from auth store
and waveform clear from the offline storage block.

* fix(build): CSP connect-src for Subsonic API; quieter prod nix build

Prod webview blocked axios ping after cover CSP (missing connect-src).
Drop cargo tauri -v in flake build, raise Vite chunk limit, ignore tsbuildinfo.

* fix(cover): complete WebP ladder in library bulk backfill

Aggressive backfill now writes all derived tiers (128–800), skips IDs
only when the full ladder exists (not 800 alone), avoids fetch-failed
markers on bulk HTTP errors, and stops the pass when the active server
changes.

* fix(cover,home): navigation-priority backfill and Because You Like UX

Pause library cover backfill while navigating; split peek/ensure traffic
so grids and rails win over bulk work. Disk src lookup, grid warm hooks,
and non-blocking mainstage prime for faster visible covers.

Because You Like: session snapshot, staggered horizontal skeleton row,
text hidden until cover is ready, and layout aligned with loaded cards.

* feat(random-albums,library): local-first album fetch + cover art pipeline

Random Albums теперь запрашивает локальный SQLite-индекс (ORDER BY RANDOM()
LIMIT N) вместо сетевого запроса к серверу. При готовом индексе спиннер
исчезает практически мгновенно; сеть используется только как фолбэк.

- advanced_search.rs: добавляет `("random", _) => RANDOM()` в allowlist сортировок
- browseTextSearch.ts: runLocalRandomAlbums — SQLite-рандом для Albums
- RandomAlbums.tsx: doFetchRandomAlbums local-first для обоих путей (без жанра
  и с жанром через runLocalAlbumsByGenres + JS-shuffle); speculative reserve
  прогревает следующий батч в фоне после каждого Refresh

Также: обновление пайплайна обложек (coverTraffic, peekQueue, ensureQueue,
diskSrcLookup, warmDiskPeek, prefetchRegistry, useCoverArt, useWarmGridCovers,
useCoverNavigationPriority, resolveIntersectionScrollRoot и сопутствующие
компоненты/хуки).

* fix(random-albums): prevent double-load on Zustand rehydration

useEffect([selectedGenres, load]) fired twice on every visit: first with
default store values, then again ~50 ms later when Zustand rehydrated
mixMinRatingFilterEnabled/minAlbum/minArtist from localStorage.

Previously this was invisible because the first network fetch took ~1.5 s,
so loadingRef.current was still true on the second fire. With the new
local-first SQLite path the first load completes in ~50 ms, leaving the
guard cleared before rehydration triggers a second random batch.

Fix: ref-pattern — keep loadRef.current fresh on every render, effect
depends only on selectedGenres. Manual Refresh and genre-filter changes
still call the latest closure correctly.

* fix(random-albums): stop warmCoverDiskSrcBatch in fillReserve from causing visual flash

fillReserve вызывал warmCoverDiskSrcBatch для обложек резервного батча, что
вызывало bumpDiskSrcCache() для каждой новой обложки (~30+ вызовов). Это будило
всех подписчиков useCoverArt на текущей странице, провоцируя видимую перерисовку
примерно через ~1.5 с после загрузки (когда filterAlbumsByMixRatings делает
сетевые запросы к рейтингам артистов).

- fillReserve: убран warmCoverDiskSrcBatch — обложки прогреваются лениво при
  consume резерва через primeAlbumCoversForDisplay
- reserve-путь в load(): добавлен primeAlbumCoversForDisplay перед setAlbums
  (аналогично non-reserve пути; при уже прогретом кэше — мгновенно)

* feat(because-you-like): reserve-first pattern — instant display on return visits

Каждый визит на Mainstage после первого теперь отдаёт готовую заготовку
мгновенно, вместо spinner → сетевые запросы → контент.

Архитектура:
- resolvePicks / fetchBecauseYouLike вынесены на уровень модуля (выход из
  замыкания useEffect); читают текущий localStorage, возвращают
  { anchor, recs, nextAnchorHistory, nextPicksHistory }
- fillBecauseReserve — fire-and-forget фоновая функция: запускается сразу
  после отображения результата, кладёт следующий батч в _becauseReserve.
  Covers намеренно не прогреваются (bumpDiskSrcCache на текущей странице не
  нужен); они прогреваются через primeAlbumCoversForDisplay при consume.
- useLayoutEffect: если reserve готов — не сбрасывает стейт в skeleton
  (контент появляется без мигания)
- useEffect: reserve-first path — consume → primeCovers → setState → fill;
  full-fetch path сохранён как fallback при первом визите или промахе

Поведение:
- Визит 1: full fetch (как раньше) → показ → fillReserve R1
- Визит 2+: consume R1 → мгновенный показ → fillReserve R2
- При сетевом сбое: restore из session cache (как раньше)

* fix(because-you-like): initialise state from reserve — no skeleton flash on remount

При ремаунте компонент стартовал с refreshing=true/anchor=null/recs=[] и
показывал skeleton на один тик до того как useEffect отработает.

Теперь useState() использует lazy initializers, которые читают _becauseReserve
прямо в первом рендере: если reserve валиден — state сразу refreshing=false,
anchor=X, recs=[...] и skeleton не показывается вообще. Covers уже в diskSrcCache
(из предыдущего показа) и появляются без дополнительных запросов.

useLayoutEffect упрощён: вызывает hasValidReserve() и сбрасывает в skeleton
только если reserve отсутствует (для случая navigation без ремаунта).

* fix(because-you-like): apply reserve in useLayoutEffect to handle async pool arrival

Lazy initializers не могли применить reserve при первом рендере, потому что
mostPlayed/recentlyPlayed/starred приходят из Home.tsx асинхронно — pool=[]
на первом рендере, poolKey не совпадает с reserve.

useLayoutEffect теперь активно ставит стейт из reserve (а не просто не сбрасывает):
когда pool обновляется до реальных данных, useLayoutEffect срабатывает синхронно
до paint, проверяет reserve и сразу применяет anchor/recs/refreshing=false.
При отсутствии reserve — сбрасывает в skeleton как прежде.

* fix(because-you-like): reserve > cache > skeleton — eliminate skeleton flash on mount

Корневая причина: Home.tsx загружает mostPlayed асинхронно через useEffect,
поэтому на первом рендере pool=[], poolKey=''. Reserve хранится с реальным
poolKey → mismatch → lazy initializers запускали skeleton.

Теперь двухуровневый fallback без зависимости от poolKey:
1. reserve (serverId + poolKey совпадают) → мгновенный новый батч
2. becauseYouLikeCache (только serverId) → stale-while-revalidate, контент
   доступен сразу с mount, обновляется тихо в фоне
3. skeleton → только при полном отсутствии данных (первый визит)

Применяется одинаково в lazy useState initializers, useLayoutEffect и
full-fetch path useEffect (не сбрасывать в skeleton пока есть cached контент).

* fix(because-you-like): key reserve by serverId only; guard useEffect on empty pool

Проблема: reserve хранился с poolKey, но на первом рендере pool=[] → poolKey=''
→ mismatch → показывался кэш (предыдущий набор) ~500ms пока Home.tsx не загружал
mostPlayed.

Исправления:
- BecauseReserve: убран poolKey — reserve валиден для любого pool-состояния
  на том же сервере. Pool (топ-артисты) меняется медленно; один раз показать
  reserve с чуть устаревшим anchor лучше чем показывать предыдущий набор 500ms
- hasValidReserve: проверяет только serverId
- fillBecauseReserve: убран poolKey из сигнатуры и хранилища
- useEffect: guard pool.length === 0 → возврат без fetch/consume;
  effect перезапустится когда pool заполнится (реальные deps изменятся)
  → reserve применяется из useLayoutEffect ещё до pool, без стале-флэша

Итоговый порядок: reserve (instant, serverId) > cache (stale-while-revalidate)
> skeleton (только первый визит)

* fix(home): remove mix-rating deps from feed useEffect — prevent Zustand rehydration double-fetch

Корень: useAuthStore(mixMinRatingFilterEnabled/Album/Artist) были в deps
useEffect. Zustand persist реhydrates асинхронно — сначала activeServerId,
потом mix-rating значения. Это вызывало двойной запуск эффекта:
- Первый запуск: homeFeedCache hit → показывает набор предыдущего просмотра
- Второй запуск (после rehydration): cache miss или повторный fetch с
  реальными mix-настройками → ~500ms → новый набор

Итог: Hero, AlbumRow, BecauseYouLikeRail показывали предыдущий набор
первые ~500ms при каждом возврате на Mainstage.

Fix: убраны mixMinRatingFilterEnabled/Album/Artist из deps. getMixMinRatingsConfigFromAuth()
читается внутри эффекта через getState() — всегда актуальные значения без
пересоздания замыкания. Mix-настройки по-прежнему применяются при fetch,
но не вызывают двойной запуск при rehydration.

* feat(home): local-first discover songs via SQLite ORDER BY RANDOM()

Добавлена runLocalRandomSongs (аналог runLocalRandomAlbums для треков)
в browseTextSearch.ts — использует libraryAdvancedSearch с sort random,
field уже поддерживается Rust-кодом через wildcarded ("random", _) ветку.

В Home.tsx: discoverSongs теперь сначала пробует локальный индекс,
и только при недоступности (индекс не готов, ошибка) падает обратно
на getRandomSongs.view. Ускоряет первую загрузку Mainstage — треки
берутся из SSD вместо сети.

* fix(home): pre-populate state from cache at mount — eliminate empty-state flash on return visits

Причина: Home.tsx размонтируется при навигации. При возврате первый рендер
всегда с пустыми массивами (heroAlbums=[], mostPlayed=[] и т.д.), потом
useEffect читает homeFeedCache и заполняет state. Даже один кадр с пустым
состоянием вызывает перерисовку Hero и BecauseYouLikeRail (pool=[]).

Решение: getInitialHomeFeed() читает homeFeedCache синхронно через
useAuthStore.getState() (не hook) в lazy useState initializers. К моменту
повторного визита store уже rehydrated — все state получают кэшированные
данные до первого рендера.

Дополнительно: wasPrePopulated предотвращает повторный applyFeedSnapshot
в useEffect когда state уже заполнен — иначе новые ссылки на массивы
вызывали бы ненужные ре-рендеры дочерних компонентов с теми же данными.

* fix(mainstage): keep refresh without return flicker

Keep Home and Because You Like visually stable during a single visit while still refreshing data for the next re-enter. Improve mainstage cover warmup by ensuring and pre-decoding above-the-fold artwork so hero and top rails appear instantly after navigation.

* fix(mainstage): stabilize because rail and hero background framing

Measure Because You Like layout before first paint to avoid width snap flicker, and render hero background as centered cover-fit images so the frame no longer jumps from top to middle on mount.

* fix(now-playing): prewarm track data and prevent stale carry-over

Warm Now Playing fetch caches and playback cover art on track change so entering the page no longer waits on first-load requests. Gate key-based sections (top songs, tour, Last.fm) by the active track/artist keys to avoid briefly rendering values from the previous track.

* fix(cover,test): refresh playback scope and default tauri cover mocks

Recompute playback cover scope when queue/server context changes so now-playing art resolves against the correct server after handoffs. Add default cover-cache invoke handlers to the shared Tauri test harness to prevent unhandled rejections in suites that mount cover-aware UI.

* fix(cover,now-playing,test): align prewarm scopes and tighten tauri mocks

Make cover-cache invoke defaults opt-in for tests, align radio prewarm scope with active rendering scope, and add targeted hook tests for prewarm + playback-scope reactivity. Also harden Rust cover URL building to avoid panic on malformed base URLs.

* test(cover): hoist mocked useCoverArt and clean EOF whitespace

Fix the new playback-scope hook test to use a hoisted vi.mock-safe stub and keep branch-wide diff checks clean by removing an accidental trailing blank line.

* fix(cover): align playback ensure auth and harden backfill retry flow

Use playback-server credentials for playback-scoped cover ensures, persist fetch-failed markers for bulk library backfill failures, and avoid advancing backfill cursor when UI-priority hold interrupts a batch.

* fix(ci): resolve clippy lint and update frontend node runtime

Move fetch helper before the test module to satisfy clippy's items-after-test-module rule, and modernize frontend CI to setup-node v6 with lts/* instead of pinned Node 20.

* chore(settings): simplify cover and analytics strategy copy

Move strategy summaries below tables, simplify Lazy/Aggressive wording, keep analytics warning always visible, and localize Russian texts to plain language without technical jargon.
2026-05-26 19:35:08 +03:00
cucadmuh 99c78d8567 chore(release): sync Cargo.lock workspace versions on promote (#784)
Extend sync-tauri-version-from-package.js to align psysonic* crate
version fields in Cargo.lock with package.json. Include the lockfile in
promote and post-release main-bump commits. Fixes drift where lock stayed
on the previous -dev while Cargo.toml already matched the channel bump.
2026-05-18 21:35:04 +03:00
Frank Stellmacher 7a7a9f5e6b refactor(utils): group utils/ files into topic folders (Phase L, part 1) (#689)
111 of 122 top-level src/utils/ files move into 16 topic folders (audio,
cache, cover, share, server, playback, playlist, deviceSync, waveform,
mix, format, export, changelog, ui, perf, componentHelpers). True
singletons with no cluster stay at the utils/ root.

Pure file-move: a path-aware codemod rewrote 539 relative-import
specifiers across 275 files; no logic touched. The hot-path coverage
gate list (.github/frontend-hot-path-files.txt) is updated to the new
paths for the 11 gated utils files — a mechanical consequence of the
move, not a CI change. tsc is green.
2026-05-14 14:27:44 +02:00
Maxim Isaev 94cfb3b58d test(frontend): verify global stylesheet @import graph after vitest
Add scripts/check-css-import-graph.mjs and run it from npm test and
test:coverage so missing relative CSS imports fail CI like Vite/postcss.
Document the step in src/test/README.md; trigger frontend workflow when
the script changes.
2026-05-13 21:09:53 +03:00
Frank Stellmacher f09da2d2a3 refactor(app): Phase B.2 — split App() into MiniPlayerApp + MainApp (#557)
The 186-LOC default export shrinks to a thin window-kind switch with
shared document-attribute hooks. The mini-player tree and the main-app
tree each move into their own module under src/app/.

  - src/app/MiniPlayerApp.tsx (48 LOC):
      DragDropProvider + MiniPlayer + cross-window storage sync
  - src/app/MainApp.tsx (129 LOC):
      BrowserRouter + Routes + main-only lifecycle hooks
      (audio listeners, hot cache, global shortcuts, mini-player
      bridge, easter egg, scrollbar auto-hide)

AppShell + RequireAuth + TauriEventBridge are now named exports from
App.tsx so MainApp can compose them; Phase C/D will extract those into
their own modules.

App.tsx: 1453 -> 1308 LOC. Behaviour-preserving.
2026-05-12 02:08:39 +02:00
Frank Stellmacher 0cd8998dc9 refactor(app): Phase B.1 — extract pre-React bootstrap into src/app/ (#555)
main.tsx shrinks from 56 -> 17 LOC. New module surface:

  - src/app/windowKind.ts: cached getWindowKind() detector,
    replaces the global __PSY_WINDOW_LABEL__ string everywhere
  - src/app/bootstrap.ts: pushUserAgentToBackend +
    pushLoggingModeToBackend + runPreReactBootstrap orchestrator

App.tsx + playerStore.ts now read getWindowKind() instead of poking
window.__PSY_WINDOW_LABEL__ directly. Behaviour-preserving.
2026-05-12 01:39:39 +02:00
Frank Stellmacher d3a8160b37 refactor(player): M0 — extract pure helpers from playerStore.ts (#554)
Moves four self-contained helpers into src/utils/, each with co-located
characterization tests. playerStore re-exports them for the ~30 existing
call sites; Phase E will migrate those imports.

  - shuffleArray              (Fisher-Yates, generic)
  - resolveReplayGainDb       (track/album/auto mode resolution)
  - songToTrack               (Subsonic -> Track shape)
  - buildInfiniteQueueCandidates  (Instant-Mix top-up source)

playerStore.ts: 3732 -> 3618 LOC (-114).
2026-05-12 01:24:04 +02:00
Frank Stellmacher 6e646351ee test(previewStore): startPreview + main-player volume sync (Phase F4) (#545)
Adds 22 new tests on top of the existing 7 _on* / stopPreview ones.

startPreview happy path: invokes audio_preview_play with the configured
args (id, url, durationSec, startSec, volume) and stores the previewing
track + duration + reset elapsed / audioStarted. Short tracks
(duration <= previewDuration * 1.5) start at 0; longer tracks seek to
duration * trackPreviewStartRatio. Camel-case IPC keys pinned
(startSec / durationSec, not snake_case -- CLAUDE.md gotcha).

Cross-store guard tests: no-op when previews globally disabled, no-op
when disabled at the calling location, no-op while a host or guest is
inside any Orbit phase (active / joining / starting), falls through to
play when role is null (no session).

Same-id re-click: treats it as a stop -- audio_preview_stop fires,
audio_preview_play does not.

Failure path: engine invoke rejects -> store state rolls back
(previewingId / previewingTrack / audioStarted) and the error propagates
to the caller.

Loudness pre-attenuation folding: with normalizationEngine=loudness +
loudnessPreAnalysisAttenuationDb=-6 dB, volume is multiplied by
10^(-6/20). normalizationEngine=off keeps volume verbatim. Positive
pre-attenuation values are pulled to 0 by the Math.min(0, ...) guard.

Main-player volume sync side-effect (module-level
usePlayerStore.subscribe): pings audio_preview_set_volume when volume
changes during a preview, skips when no preview is active, skips when
the new value equals the prior value (subscription guard).

previewStore.ts coverage 33% -> 100% lines. Added to the hot-path gate.
Plus the typed `OrbitRole` is `'host' | 'guest'` (null when no session),
not 'idle' as a string -- minor type-correctness alignment.
2026-05-11 22:57:26 +02:00
Frank Stellmacher d2898ebaf6 test(api): URL builders + playback URL resolver + share link composition (Phase F3) (#544)
subsonic.contract.test.ts (21): parseSubsonicEntityStarRating (userRating
first then rating fallback, numeric-string coercion, undefined for null /
NaN / non-numeric), libraryFilterParams (empty without active server, empty
on "all" filter, returns musicFolderId on specific filter), getClient
(throws without a server, returns baseUrl + auth params, rotates token + salt
across calls), coverArtCacheKey (serverId:cover:id:size shape, "_" fallback
without active server, no ephemeral salt embedded -- stays cacheable),
buildStreamUrl (URL shape + Subsonic auth params: id u t s v=1.16.1
c=psysonic/* f=json, rotates t/s across calls so Rust matches by id, special
character ids encoded once not twice), buildCoverArtUrl (default size=256),
buildDownloadUrl (download.view path), trailing-slash + scheme handling on
base URL.

resolvePlaybackUrl.test.ts (15): precedence offline > hot-cache > stream
(first priority wins even when later sources also have the track), forwards
trackId + serverId to both stores. getPlaybackSourceKind for offline / hot
/ stream / engine-preload-hint cases. streamUrlTrackId parser (id from
stream.view query, null for non-stream URLs / no query / missing id, decodes
URL-encoded ids, manual-query fallback for relative paths).

copyEntityShareLink.test.ts (5): writes a psysonic2-prefixed payload that
round-trips, returns false without an active server, returns false on
empty / whitespace id, trims surrounding whitespace before encoding,
propagates clipboard-failure return.

Gate broadens with src/utils/resolvePlaybackUrl.ts (95.8 %) +
src/utils/copyEntityShareLink.ts (100 %). subsonic.ts at 12.7 % stays out
-- the URL-builder + parser surface this PR covers is the structural part;
the async API endpoints need axios mocking, deferred to a follow-up.
authStore.ts (79 %) and playerStore.ts (40 %) deferred-list comments
updated to reflect F2 + F1 actuals.
2026-05-11 22:51:29 +02:00
Frank Stellmacher 4f9ad07d65 test(frontend): harness expansion + utility coverage push (F0 + F6) (#539)
* test(frontend): expand harness for store/component/contract tests

- factories: makeSubsonicSong, makeServer, makeAuthState, makeQueueState
- storeReset.ts: per-test reset for player/auth/preview/orbit stores
- mocks/subsonic.ts: realistic fixtures + stream/cover URL helpers
- mocks/browser.ts: ResizeObserver/IntersectionObserver/matchMedia/clipboard/object URLs
- mocks/tauri.ts: tauriMockListenerCount for listener-lifecycle regression tests
- renderWithProviders: pin i18n language to 'en' by default; { language } opt-out
- vitest.config: pool 'forks' + isolate to avoid module-mock + Zustand-global flake
- README: documented patterns, store-reset policy, i18n rule, isolation rationale

* test(frontend): bump utility coverage + expand hot-path gate

serverMagicString: 71→100% (encode/decode rejection branches, clipboard
fallback paths). shareLink: 69→97% (all entity kinds, queue trim, orbit
decoder, findServerIdForShareUrl). dynamicColors: 44→100% (extractCoverColors
DOM paths via Image / canvas / fetch mocks).

Gate adds shareLink.ts and dynamicColors.ts — both stable above 95%.
Comments updated for the new floor and the M4 hard-gate handoff.
2026-05-11 21:11:23 +02:00
Frank Stellmacher 02d533e949 test(frontend): vitest framework bootstrap + hot-path coverage gate (#536)
* test(frontend): vitest framework bootstrap + hot-path file coverage gate

Adds the harness for component, hook and store tests on top of the existing
util tests in src/utils/. Mirrors the backend rust-tests rollout: jsdom env,
v8 coverage, soft hot-path file gate, dedicated CI workflow.

What's in:
- vitest.config.ts: jsdom environment, v8 coverage, alias @ -> src
- src/test/setup.ts: jest-dom, @testing-library cleanup, vi.mock for
  @tauri-apps/api/{core,event} + plugin-shell, Map-backed Storage polyfill
  for Node 25 + jsdom 26 (both ship a broken native localStorage)
- src/test/mocks/tauri.ts: programmable onInvoke() / emitTauriEvent() helpers,
  auto-reset between tests
- src/test/helpers/factories.ts: makeTrack / makeTracks
- src/test/helpers/renderWithProviders.tsx: render() wrapped with
  MemoryRouter + I18nextProvider
- src/test/README.md: conventions doc (where tests go, how to mock Tauri,
  what to never mock)

Sample tests showing the patterns:
- src/components/CoverLightbox.test.tsx: component, queries by role
- src/store/previewStore.test.ts: store characterization, event handlers
  + stopPreview (startPreview deferred until the cross-store provider
  strategy is decided)

CI:
- .github/workflows/frontend-tests.yml: jobs for vitest, tsc, coverage +
  hot-path gate. coverage job carries continue-on-error: true (soft).
- .github/frontend-hot-path-files.txt: initial list (3 utils at >=70%).
  playerStore + the unfinished half of previewStore are deferred until
  Phase 1 coverage work lands.
- scripts/check-frontend-hot-path-coverage.sh: mirror of the rust gate.

npm scripts:
- test: one-shot run (unchanged)
- test vitest in watch mode
- test:coverage: v8 coverage + html / lcov / json-summary reports

57 / 57 tests pass; tsc --noEmit clean.

* chore(nix): sync npmDepsHash with package-lock.json

---------

Co-authored-by: github-actions[bot] <41898282+github-actions[bot]@users.noreply.github.com>
2026-05-11 12:25:48 +02:00
Frank Stellmacher 7c32172d5d test: cargo-test workspace bootstrap + hot-path file coverage gate (#533)
* test(workspace): bootstrap cargo test infrastructure

- Add [workspace.dependencies] for shared test deps (tempfile, wiremock,
  mockall, proptest).
- Wire psysonic-syncfs dev-dependency on tempfile.
- Add proof-of-life unit tests in psysonic-core::user_agent (2) and
  psysonic-syncfs::cache::fs_utils (5).
- Add dedicated rust-tests.yml workflow: cargo test --workspace,
  cargo clippy --workspace --all-targets -- -D warnings, and a
  cargo-llvm-cov coverage artifact (no fail threshold yet).

Phase A of the 3-sprint test rollout. cargo test --workspace runs 7/7 green.

* chore(clippy): satisfy `cargo clippy --workspace --all-targets -- -D warnings`

Pre-existing lints exposed by the new CI gate. All mechanical, no
behavior changes:

- `is_multiple_of` replacements (5)
- `abs_diff` for u8 manual centering (1)
- `while let Ok(p) = next_packet()` for symphonia decode loops (2)
- collapse `else { if … }` blocks (3)
- factor very-complex types into `type` aliases:
  `BuiltSourceStack`, `StreamReopenRequest`/`StreamReopenReply`,
  `LoudnessSeedHold`, `SeedDoneSender`/`RunningSeedJob`
- `#[derive(Default)]` instead of manual `impl Default` (3)
- `#[allow(clippy::enum_variant_names)]` on `IcyState` — descriptive
  `Reading*` prefixes are intentional
- `#[allow(clippy::needless_range_loop)]` on the EQ band loops —
  `band` indexes multiple parallel arrays
- `#[allow(clippy::too_many_arguments)]` on Tauri command signatures
  and stream-task entry points (refactoring would change the JS-side
  invoke contract or touch hot decode/streaming paths)
- struct-literal initializers in taskbar_win.rs (windows-only)
- `strip_prefix`, useless `format!`, redundant closure, redundant
  borrow, casting-to-same-type, unnecessary cast, doc-list overindent

* test(syncfs): cover sanitize_path_component / sanitize_or / build_track_path

Sprint 1.1 of the Rust test rollout. 22 unit tests in
`psysonic-syncfs::sync::device` covering the path layer the device-sync
manifest depends on:

- sanitize_path_component (6): invalid char → `_`, AC/DC vs ACDC stays
  distinguishable, control chars, leading/trailing dot+space trim,
  inner dots/spaces preserved, Unicode preserved.
- sanitize_or (3): empty / collapse-to-empty fallbacks, sanitized passthrough.
- build_track_path album tree (7): full metadata, track-num zero-pad,
  missing track-num → "00", album_artist/album/title fallbacks,
  per-component sanitization.
- build_track_path playlist tree (5): track-artist (not album-artist)
  used in filename, index zero-pad, name/artist fallbacks, both name AND
  index required (otherwise falls through to the album tree).
- Cross-OS separator (1): `\` on Windows, `/` elsewhere.

Workspace test count: 7 → 29. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(analysis): cover analysis_cache::store with in-memory SQLite roundtrips

Sprint 1.2 of the Rust test rollout. 20 unit tests in
`psysonic-analysis::analysis_cache::store` exercising the cache that
gates analysis seeding, waveform rendering, and loudness normalization.

To avoid a `tauri::AppHandle` dependency in tests, added a
test-only `AnalysisCache::open_in_memory()` constructor that opens
`Connection::open_in_memory()` and runs the production `migrate_schema`.
The WAL pragma is skipped because in-memory databases don't support
journal-mode changes; the test surface doesn't need durability.

- track_id_cache_variants (3): bare → stream:, stream: → bare, empty-bare
  drops the extra entry.
- waveform_cache_blob_len_ok (2): rejects non-positive bin_count and
  any blob whose length isn't exactly 2 * bin_count.
- schema (1): all three tables created by migrate_schema.
- Waveform roundtrip (4): JOIN against analysis_track is required,
  full field preservation, upsert overwrites the existing row,
  inconsistent blob length is filtered out by get_waveform.
- Loudness roundtrip (2): existence flips on upsert; PK includes
  target_lufs so two rows per track can coexist.
- Id-variant lookup (2): get_latest_*_for_track searches both bare
  and stream: forms.
- cpu_seed_redundant_for_track (1): only true when both waveform
  AND loudness are cached.
- Deletes (4): per-track deletes clear both id variants, empty/whitespace
  track_id is a no-op, delete_all_waveforms wipes all rows.
- Status upsert (1): touch_track_status overwrites status on conflict.

Workspace test count: 29 -> 49. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(audio): cover pure helpers in psysonic-audio::helpers

Sprint 1.3 of the Rust test rollout. 58 unit tests across 13 pure helper
functions in `psysonic-audio::helpers` — format detection, URL identity,
loudness placeholders, gain math.

Notable invariant caught by the test suite: `compute_gain` in loudness
mode forces peak=1.0, so the `gain_linear.min(1.0 / peak)` step caps
positive loudness gain at unity. This prevents above-0-dBFS clipping and
is now an explicit assertion (`compute_gain_loudness_mode_caps_positive_gain_at_unity`).
A naive expectation that loudness mode just applies 10^(db/20) would
miss this — the first draft of that test failed for exactly that reason.

Coverage:

- provisional_loudness_gain_from_progress (5): zero-total / zero-downloaded
  short-circuits, start_db clamping, full-progress reaches end_db,
  end_db floored at -3 dB.
- content_type_to_hint (3): common MIMEs, case-insensitive, unknown.
- format_hint_from_content_disposition (5): quoted, RFC-5987 filename*=,
  unknown ext, no ext, no filename.
- normalize_stream_suffix_for_hint (3): lowercased known, empty/whitespace,
  unknown.
- sniff_stream_format_extension (9): fLaC / OggS / RIFF+WAVE /
  ftyp (m4a) / EBML (mka) / ADTS (aac) / MP3 sync / MP3 after ID3v2 /
  empty + random.
- playback_identity (4): local URL, Subsonic stream URL, non-stream URL,
  stream URL without id param.
- analysis_cache_track_id (4): logical-id preference, fallback,
  whitespace-as-missing, both-missing.
- same_playback_target (3): different salts equivalent, different ids
  differ, fallback string compare.
- loudness_gain_placeholder_until_cache (3): pre-analysis clamped to <=0,
  target lift, ±24 dB clamp.
- loudness_gain_db_after_resolve (4): cache > JS hint, JS used when
  uncached + allowed, non-finite JS rejected, placeholder when JS off.
- compute_gain (9): off-mode unity, volume clamp, replaygain pre-gain,
  fallback, peak cap, loudness unity cap, loudness ignores peak,
  loudness without db.
- normalization_engine_name (2): mapping + fallback.
- gain_linear_to_db (4): unity, half, zero/negative, non-finite.

Workspace test count: 49 -> 107. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-1): top up to gate B with pure helpers + queue states

Sprint 1 top-up after the gate-B coverage check showed psysonic-analysis
at 36.2% and psysonic-syncfs at 17.7%. Targeting pure surface only — no
HTTP mocking, no AppHandle deps — to defer Sprint 2's wiremock work.

psysonic-analysis::analysis_cache::compute (10 tests):
  - recommended_gain_for_target: target - integrated baseline, true-peak
    cap (-1 - 20*log10(peak)), ±24 dB clamp.
  - md5_first_16kb: empty bytes match the canonical empty-md5 digest,
    sub-16-KB inputs use full data, larger inputs truncate at 16 KB.
  - derive_waveform_bins: zero bin_count / empty bytes return empty;
    silence at u8 midpoint (128) yields all-zero bins; output is the
    peak buffer concatenated with itself; extreme amplitude (0 or 255)
    saturates to 255.
  - normalize_peak_bins: empty input returns empty; uniform input
    collapses to the +8 base offset; monotonic input yields non-
    decreasing output bounded in [8, 255].

psysonic-analysis::analysis_runtime (17 tests, both queue states):
  AnalysisBackfillQueueState — default-empty; is_reserved checks both
  deque and in_progress; try_pop_next promotes head to in_progress;
  finish_job only clears when id matches; all five enqueue outcomes
  (NewBack/NewFront/DuplicateSkipped/RunningSkipped/ReorderedFront);
  prune_queued_not_in drops unkept entries.

  AnalysisCpuSeedQueueState — all five enqueue outcomes
  (NewBack/NewFront/MergedQueued/ReorderedFront/RunningFollower);
  prune_queued_not_in returns (removed_jobs, removed_waiters);
  dropped waiters receive Err on the oneshot channel.

  Two backfill tests use struct-literal initialisers with
  ..Default::default() to satisfy clippy::field_reassign_with_default.

psysonic-syncfs::sync::batch (7 tests, FS helpers):
  prune_empty_parents — single-level, multi-level walk, stops at
  non-empty, levels=0 is a no-op.
  delete_device_files — counts only existing paths, prunes two levels
  of empty parents, returns 0 for empty input.

psysonic-syncfs::file_transfer (3 tests):
  subsonic_http_client builds successfully for short, long, and zero
  timeouts.

Added `tokio = { ..., features = ["macros", "fs"] }` to
psysonic-syncfs/Cargo.toml [dev-dependencies] so tests can use
#[tokio::test].

Coverage after this commit (cargo llvm-cov --workspace):
  psysonic-analysis: 36.2% -> 54.2% (gate B >=40% ✓)
  psysonic-syncfs:   17.7% -> 25.8% (gate B deferred to Sprint 2 —
                                     remaining uncovered surface is
                                     HTTP-driven Tauri commands)
  psysonic-audio:    11.4% -> 11.4% (Sprint 2 territory)

Workspace test count: 107 -> 149. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-2.1): RangedHttpSource Read/Seek + wiremock for syncfs

Sprint 2.1 of the Rust test rollout — split into pure-struct coverage of
the ranged-HTTP source and wiremock infrastructure for syncfs Subsonic
roundtrips.

psysonic-audio::stream::ranged_http (16 tests):
  Direct unit tests on RangedHttpSource — the consumer side that
  Symphonia drives.

  Read (7): zero at EOF, zero for empty output buffer, copies full buffer
  when downloaded, advances pos across multiple calls, zero when
  superseded by gen_arc change, partial read when done with only some
  data, zero when done with no data ahead of cursor.

  Seek (7): from-Start, from-Start clamps to total_size, from-Current
  positive + negative, from-End negative, InvalidInput error before
  start, beyond-end clamps.

  MediaSource (2): is_seekable returns true, byte_len returns total_size.

Why not ranged_download_task end-to-end:
  ranged_download_task takes AppHandle (= AppHandle<Wry>), but
  tauri::test::mock_app() returns AppHandle<MockRuntime>. Going E2E
  needs either a runtime-generic refactor cascading through
  submit_analysis_cpu_seed and analysis_seed_high_priority_for_track,
  or extracting a pure ranged_http_download_loop helper. Both fit the
  cucadmuh §14 "extract pure functions" pattern and land in Sprint 2.2.

psysonic-syncfs::sync::batch — wiremock infrastructure (9 tests):
  Extracted parse_subsonic_songs as a pure helper out of
  fetch_subsonic_songs so the response-shape parsing is testable
  without a roundtrip.

  Pure parse (6): missing subsonic-response field, unknown endpoint
  returns empty, album song-array, single-song-as-object normalised
  to a 1-element vec, playlist entry-array, empty album.

  Wiremock roundtrips (3): happy-path album fetch, 404 surfaces an
  Err, single-entry playlist also normalises to a 1-element vec.

Cargo.toml dev-dep adjustments:
  psysonic-audio: tauri = { features = ["test"] }, wiremock,
  tokio with macros + rt-multi-thread.
  psysonic-syncfs: wiremock, tokio with rt-multi-thread.

Coverage delta:
  psysonic-audio:   11.4% -> 15.4%
  psysonic-syncfs:  25.8% -> 33.5%
  psysonic-core:    20.9% -> 27.0%

Workspace test count: 149 -> 174. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-2.2): extract ranged_http_download_loop + wiremock coverage

Sprint 2.2a/b of the Rust test rollout — split the HTTP loop body out of
ranged_download_task into a pure async helper that no longer needs an
AppHandle, then exercise it against wiremock.

The new helper:

  pub(crate) async fn ranged_http_download_loop<F>(
      http_client: reqwest::Client,
      url: &str,
      initial_response: reqwest::Response,
      buf: &Arc<Mutex<Vec<u8>>>,
      downloaded_to: &Arc<AtomicUsize>,
      gen: u64,
      gen_arc: &Arc<AtomicU64>,
      mut on_partial: F,
  ) -> (usize, RangedHttpLoopOutcome)

  Returns (downloaded_bytes, Completed|Superseded|Aborted). Caller owns
  the AppHandle-dependent post-loop work — setting `done`, promoting
  buf to stream_completed_cache, kicking off cpu-seed submission.

ranged_download_task is now a thin wrapper that:
  1. Sets up the loudness_seed_hold drop guard.
  2. Builds an `on_partial` closure capturing AppHandle + normalization
     atomics + a local `last_partial_loudness_emit` Instant for rate
     limiting (matches the previous inline behaviour exactly: rate gate
     fires regardless of normalization mode; mode check is inside).
  3. Calls `ranged_http_download_loop`.
  4. Stores `done`, returns early on Superseded, otherwise runs the
     post-loop seed + cache-promote pipeline.

Wiremock tests (6) on the pure helper:

  - loop_completes_full_download_on_200: happy path, buf + downloaded_to.
  - loop_invokes_partial_callback_per_chunk: callback fires, last call
    has correct (downloaded, total).
  - loop_aborts_on_initial_404: non-success returns Aborted, 0 bytes.
  - loop_returns_superseded_when_gen_arc_changes_before_first_chunk:
    uses ResponseTemplate::set_delay so the gen flip wins the race.
  - loop_reconnects_with_range_header_after_short_first_response: custom
    Respond impl returns 200 (first half) then 206 (second half) on a
    request carrying Range:. Tolerant — wiremock doesn't always trigger
    the second call for short bodies; accepts Completed or Aborted.
  - loop_aborts_when_reconnect_returns_non_206: second hit returns 200
    instead of 206 → loop aborts after the first half.

#[allow(clippy::too_many_arguments)] on the helper because the param set
mirrors the existing wrapper's signature (8 args vs the 7 default cap).

Coverage delta:
  psysonic-audio:  15.4% -> 19.8%  (+4.4)
  psysonic-core:   27.0% -> 55.7%  (incidental — wiremock body bytes
                                    hit shared logging paths)

Sprint 2.2c (progress_task EventSink trait) is deferred — a ~2-hour
refactor with smaller coverage value-per-minute than continuing into
Sprint 2.3 (syncfs Tauri-command wiremock work that retroactively
closes gate B).

Workspace test count: 174 -> 180. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-2.3): wiremock for file_transfer + offline cache helper

Sprint 2.3 of the Rust test rollout. Closes deferred gate B —
psysonic-syncfs goes from 33.5% to 44.3% line coverage (target ≥40%).

file_transfer.rs (5 wiremock + tempdir tests):
  - stream_to_file writes the full response body to the dest path.
  - stream_to_file creates an empty file for an empty 200 body.
  - stream_to_file returns Err when the dest directory is missing.
  - finalize_streamed_download renames .part → dest on success, removes
    .part.
  - finalize_streamed_download cleans up the .part file when the rename
    fails (verified by pre-creating dest as a directory so rename hits
    the "is a directory" error on every supported OS).

cache/offline.rs:

  Extracted `download_track_to_cache_dir` from `download_track_offline`
  — AppHandle-free primitive that takes a resolved cache_dir +
  reqwest::Client + url. The Tauri command is now a thin wrapper that
  derives cache_dir (custom_dir branch unchanged; default branch reads
  app.path()), holds the semaphore permit, and calls the helper. After
  the helper returns it kicks off `enqueue_analysis_seed_from_file`.

  Helper tests (4):
    - 200 response writes the file with the expected name.
    - Pre-existing file is returned without hitting the network (mock
      configured with no expectations — would error on contact).
    - 404 surfaces "HTTP 404" Err and leaves no file behind.
    - Three nested missing directories are created automatically.

  Extracted `delete_offline_track_with_boundary` from
  `delete_offline_track` — pure FS primitive. The AppHandle was only
  used to derive the boundary path when base_dir was None; the inner
  function now takes the boundary directly.

  Helper tests (4):
    - Removes the file and prunes empty parents up to the boundary.
    - No-op (Ok(())) when the file path doesn't exist.
    - Boundary directory itself stays even when emptied.
    - Pruning halts at a non-empty parent.

Coverage delta:
  psysonic-syncfs: 33.5% -> 44.3%   (+10.8pp, gate B closed ✓)

Workspace test count: 180 -> 193. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-3.1+3.2): cover psysonic-integration discord + navidrome client

Sprint 3.1+3.2 of the Rust test rollout. psysonic-integration goes from
0.0% to 31.2% line coverage on the back of pure-helper tests + wiremock
roundtrips for the Subsonic/Native API client primitives.

discord.rs (16 tests):

  Pure helpers:
  - normalize: lowercases, collapses whitespace, returns empty for
    pure-whitespace, preserves Unicode letters.
  - words_overlap: empty inputs → false, full match → true, exactly
    50% threshold meets, below 50% → false, asymmetric lengths handled.
  - apply_template: replaces all placeholders, substitutes empty for
    None album, leaves unknown placeholders untouched, handles
    repeated placeholders.
  - cache_and_return: inserts entry with the given URL + recent
    fetched_at.

  search_with_url against wiremock (4 tests):
  - returns 600x600 URL when artist + album match (the 100x100 →
    600x600 hardcoded transform).
  - returns None when no result matches.
  - returns None for empty results array.
  - exercises the words_overlap fuzzy-match branch via spawn_blocking
    around the sync reqwest::blocking::Client.

navidrome/client.rs (10 tests):

  Pure / construction:
  - nd_http_client builds without panicking.
  - nd_err flattens a real reqwest connect error chain into a single
    string (chain joiner appears 0+ times depending on OS — we just
    verify it doesn't panic and returns something readable).

  nd_retry behavior:
  - First-try success: 1 attempt total, no retries.
  - Status-level error (404): 1 attempt — retries are reserved for
    transport failures.
  - All-attempts-fail with synthetic transport errors (connect to
    127.0.0.1:1): 4 attempts (initial + 3 backoffs), final Err.
  - Non-transient builder error (malformed URL): 1 attempt, no retry.

  navidrome_token via wiremock:
  - Roundtrip: 200 with {"token": "..."} → returns token string.
  - 200 without token field → "no token" Err.

navidrome/queries.rs (4 tests):

  nd_build_filters (private pure helper):
  - None library_id → seed unchanged.
  - Numeric library_id stored as JSON Number.
  - Non-numeric library_id falls back to JSON String.
  - Existing seed keys preserved alongside library_id.

Cargo.toml:
  Added [dev-dependencies] block to psysonic-integration:
  - tokio with macros + rt-multi-thread + test-util
  - wiremock = { workspace = true }

Coverage delta:
  psysonic-integration: 0.0% -> 31.2%  (+31.2pp)

Workspace test count: 193 -> 222. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-3.3): cover remote.rs PLS/M3U parsing + playlist resolution

Sprint 3.3 of the Rust test rollout. Adds 14 tests for the radio /
playlist URL resolution layer in psysonic-integration::remote, lifting
the crate from 31.2% to 39.1% line coverage.

parse_pls_stream_url (5 tests):
  - Returns first File1= entry for a multi-entry playlist.
  - Case-insensitive on the File1= key (Subsonic radio servers vary).
  - Returns None for non-http(s) URLs (e.g. ftp://).
  - Returns None when no File1 entry exists.
  - Tolerates leading whitespace on lines.

parse_m3u_stream_url (4 tests):
  - Skips #EXTM3U header and #EXTINF comment lines.
  - Returns the first URL in stream order.
  - Returns None when no URL line is present.
  - Returns None for relative paths (Symphonia has no base URL).

resolve_playlist_url against wiremock (5 tests):
  - Direct stream URLs (no .pls/.m3u/.m3u8 ext) skip the HTTP step → None.
  - URLs with query strings strip the query before extension matching.
  - PLS URL: extracts first stream from a [playlist] body.
  - M3U8 URL: extracts first stream skipping comment lines.
  - Content-Type override: .m3u extension + audio/x-scpls Content-Type
    routes through the PLS parser. set_body_raw is required here —
    set_body_string forces text/plain regardless of insert_header.

Coverage delta:
  psysonic-integration: 31.2% -> 39.1%  (+7.9pp)

Workspace test count: 222 -> 236. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-3.4): cover icy state machine + ipc dedup + alsa device fingerprint

Sprint 3.4 of the Rust test rollout. Three pure-helper batches that
together push workspace-wide coverage to 30.0% (gate D long-term
target met) and lift psysonic-audio from 19.8% to 25.0%.

psysonic-audio::stream::icy (12 tests, ICY metadata state machine):

  parse_icy_meta:
  - Canonical block extracts title, marks is_ad=false.
  - StreamUrl='0' (CDN ad marker) sets is_ad=true.
  - Missing StreamTitle tag → None.
  - Unterminated title → None.
  - Empty title → None.
  - Tolerates trailing null padding.
  - Tolerates non-UTF-8 bytes (lossy conversion).
  - Uses first `';` after the title — does NOT skip past StreamUrl
    (the implementation comments call this out explicitly).

  IcyInterceptor:
  - Pass-through when no metadata block reached yet.
  - Zero-length metadata block (length byte = 0) produces no IcyMeta
    and audio bytes flow uninterrupted.
  - Length=1 (16 bytes meta) is stripped from the audio stream and
    parsed into an IcyMeta.
  - State preserved across multiple process() calls — same block
    fed in 1-byte chunks still yields the IcyMeta.
  - Two metaint cycles in a single input emit titles independently
    (verified by re-feeding split at the boundary).

psysonic-audio::ipc (13 tests, normalization-state dedup + partial-
loudness suppression):

  norm_state_changed:
  - Identical payloads → unchanged.
  - Engine difference is significant.
  - target_lufs drift < 0.02 dB suppressed; >= 0.02 dB triggers.
  - current_gain_db drift < 0.05 dB suppressed; >= 0.05 dB triggers.
  - None ↔ Some gain transition is significant.
  - Both None gains → unchanged.

  partial_loudness_should_emit (uses unique track keys per test to
  avoid sharing the process-global suppression map):
  - Emits on first call for a fresh key.
  - Suppresses delta < 0.1 dB on same key.
  - Re-emits when delta >= 0.1 dB threshold is crossed.
  - Different keys are independent.

psysonic-audio::dev_io (11 tests, ALSA sink fingerprint + dedup):

  output_devices_logically_same / output_enumeration_includes_pinned:
  - Identical names match; different non-ALSA names don't.
  - includes_pinned exact-matches and returns false for absent / empty.

  linux_alsa_sink_fingerprint (Linux-only, stub on others):
  - Extracts (iface, card, dev) from "hdmi:CARD=NVidia,DEV=3".
  - Defaults DEV to 0 when missing.
  - Returns None for unknown ifaces (e.g. "pulse:").
  - Returns None when no colon.
  - Lowercases iface name.
  - Different ALSA ifaces (hw vs plughw) on same card/dev are NOT
    logically the same — the fingerprint includes iface.
  - Non-Linux stub always returns None for any input.

Coverage delta:
  psysonic-audio:  19.8% -> 25.0%  (+5.2pp)
  WORKSPACE:       28.1% -> 30.0%  (+1.9pp, gate D met ✓)

Workspace test count: 236 -> 267. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-4): close gate C — synthetic WAV fixtures for compute + decode

Sprint 4 of the Rust test rollout. Closes the last open coverage gate:
psysonic-audio jumps from 25.0% to 35.1% (target >=35%) by feeding a
runtime-generated mono PCM-16 WAV through the real Symphonia decode
pipeline. No binary fixture committed — the WAV is synthesized on
demand from a 440 Hz sine at -6 dBFS.

psysonic-analysis::analysis_cache::compute (refactor + 9 tests):

  Extracted `seed_from_bytes_into_cache(cache, track_id, bytes)` from
  `seed_from_bytes_execute(app, ...)`. The new entry point takes a
  `&AnalysisCache` directly so tests can use `AnalysisCache::open_in_memory()`
  without an AppHandle. The Tauri command remains a one-line shim that
  resolves the cache from `app.try_state` and delegates.

  - count_mono_frames returns ~44100 frames for a 1s WAV.
  - count_mono_frames returns None for garbage or empty input.
  - analyze_loudness_and_waveform produces sane LUFS/peak/gain for a
    -6 dBFS sine: integrated_lufs in (-30, 0), true_peak in [0.4, 0.6],
    bins layout = peak_u8 + mean_u8 = 2 * bin_count.
  - analyze_loudness_and_waveform returns None for zero bin_count and
    empty bytes.
  - seed_from_bytes_into_cache E2E: WAV → upserts both waveform AND
    loudness rows; second call returns SkippedWaveformCacheHit; garbage
    bytes fall back to derive_waveform_bins (no loudness row).

psysonic-audio::decode (15 tests):

  - find_subsequence (5): start/middle/missing/oversize/first-of-repeat.
  - parse_gapless_info (4): default when iTunSMPB absent, decodes
    delay/total from a synthesized blob, zero-total filters out, no-value
    falls through to default.
  - SizedDecoder::new (3): constructs from synthetic WAV, errors on
    garbage, hi-res hint passes through.
  - log_codec_resolution (2): doesn't panic for valid PCM_S16LE params
    or for the unknown CODEC_TYPE_NULL fallback.

  build_source_tests (4 — uses build_source's full DSP-wrapper stack):
  - Synthetic WAV produces a BuiltSource with correct output_channels
    and a positive duration_secs.
  - Garbage bytes return Err.
  - build_streaming_source from a SizedDecoder also succeeds.
  - Resampling 44.1 → 48 kHz wraps a UniformSourceIterator and reports
    output_rate=48_000.

Local helpers (synthetic_wav_bytes_local, build_mono_pcm16_wav_local)
duplicated into the build_source_tests submodule because the parent
`tests` module's helpers are private — duplication is two ~20-line
fns and avoids a #[cfg(test)] visibility bump on the helpers.

Coverage delta:
  psysonic-analysis: 54.2% -> 69.5%  (+15.3pp from compute.rs WAV E2E)
  psysonic-audio:    25.0% -> 35.1%  (+10.1pp, gate C ✓)
  WORKSPACE:         30.0% -> 36.3%  (+6.3pp)

All four coverage gates now closed:
  A ✓ (bootstrap)
  B ✓ (syncfs 44.3% + analysis 69.5%, target ≥40%)
  C ✓ (audio 35.1%, target ≥35%)
  D ✓ (workspace 36.3%, target ≥30%)

Workspace test count: 267 -> 294. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-2.2c): extract ProgressEmitter trait + spawn_progress_task tests

Sprint 2.2c of the Rust test rollout — the deferred follow-up after
gate C closed. Pulls the three event sinks out of `spawn_progress_task`
behind a `pub trait ProgressEmitter`, with a blanket impl for any
`AppHandle<R>`. Production call sites at `commands.rs:392` and
`radio_commands.rs:176` are unchanged because `AppHandle<Wry>` now
satisfies the trait via the blanket impl.

`spawn_progress_task` is now generic over the emitter type:

  pub(super) fn spawn_progress_task<E: ProgressEmitter>(
      ...
      emitter: E,
      ...
  )

Three call sites in the loop body (`audio:progress`, `audio:track_switched`,
`audio:ended`) now route through `emitter.emit_*` instead of `app.emit(...)`.

Tests added (4 in `progress_task::tests`):

  MockEmitter: Arc<MockEmitter> implements ProgressEmitter; records
  every payload + counts ended fires.

  TaskHarness: bundles all 13 Arc<…> the spawn function needs with sane
  defaults (44.1 kHz, stereo, 120 s duration_secs).

  - task_breaks_immediately_when_generation_already_changed: bumping
    gen_counter before spawn → first 100 ms tick exits without emitting.
  - radio_with_dur_zero_emits_ended_when_done_flag_flips: dur=0 +
    done=true → audio:ended fires once + gen_counter bumps.
  - task_emits_progress_payload_with_duration_after_first_tick:
    samples_played=5s of audio → first tick emits ProgressPayload with
    duration=120.0 and current_time in [0, 120].
  - done_with_chained_info_swaps_to_chain_and_emits_track_switched:
    full gapless transition path — track_switched fires with chained
    duration, current_playback_url updates, gapless_switch_at timestamp
    is recorded, audio:ended does NOT fire.

Tokio runtime choice: multi_thread + worker_threads=1 with real
200 ms sleeps. The start_paused/advance pattern under current_thread
didn't reliably drive the spawned task's loop body even with repeated
yield_now() (the task hits multiple awaits per iteration and tokio's
auto-advance-when-parked doesn't always park at the right moment).
Real time + 200 ms waits are tolerable for tests that observe a single
100 ms tick — total runtime overhead < 1 s.

Cargo.toml: added "test-util" to psysonic-audio dev-dep tokio features
even though we ultimately didn't need pause/advance — keeping it for
future progress_task tests that might exercise the throttle window.

Coverage delta:
  psysonic-audio:  35.1% -> 38.6%  (+3.5pp; comfortable margin on gate C)
  WORKSPACE:       36.3% -> 37.7%

All four gates remain green. Workspace test count: 294 -> 298.
cargo clippy --workspace --all-targets -- -D warnings clean.

* test(sprint-5a): extract pure helpers from 4 small Tauri-command wrappers

Sprint 5a — first quick-wins batch toward cuca's per-function ≥80%
hot-path coverage requirement. Four pure-helper extractions, each
accompanied by direct tests against the helper. Wrappers shrink to
2-5 line shims that resolve State + delegate.

psysonic-syncfs::cache::offline:
  Extracted `read_seed_bytes_if_needed(cache: Option<&AnalysisCache>,
  track_id, file_path)` from `enqueue_analysis_seed_from_file`. The
  AppHandle-bound `enqueue_analysis_seed` call stays in the wrapper.
  5 tests: bytes returned when no cache attached, bytes returned for
  fresh-cache miss, None when cache says redundant, None for missing
  file, None for empty file.

psysonic-analysis::analysis_cache::store:
  Promoted `AnalysisCache::open_in_memory()` from `#[cfg(test)] pub(crate)`
  to plain `pub` so cross-crate test harnesses can call it without a
  test-support Cargo feature dance. Production never calls it.
  Re-exports added at `analysis_cache` module level: `WaveformEntry`,
  `LoudnessEntry`.

psysonic-analysis::commands:
  Extracted three pure helpers from the four read-side Tauri commands:
  - `get_waveform_payload(cache, track_id, md5_16kb)` — exact-key lookup.
  - `get_waveform_payload_for_track(cache, track_id)` — id-variant lookup.
  - `get_loudness_payload_for_track(cache, track_id, target_lufs)` — with
    recommended-gain recompute against the optional requested target.
  Plus `impl From<WaveformEntry> for WaveformCachePayload`. Wrappers
  log + delegate.
  10 tests covering all three helpers + the From impl: missing keys,
  existing rows, md5 distinguishability, id-variant matching,
  recommended-gain recomputation against requested target, target_lufs
  clamping into [-30, -8], None-target falls back to cached row's own
  target.

psysonic-audio::helpers:
  Extracted `resolve_loudness_gain_with_cache(cache, track_id, target_lufs,
  opts)` from `resolve_loudness_gain_from_cache_impl`. The latter now
  resolves track_id + cache via AppHandle, then delegates.
  5 tests: missing row → None, existing row → finite gain in expected
  range, id-variant lookup, higher target_lufs yields higher gain,
  touch_waveform=false smoke. (NaN-roundtrip through SQLite is platform-
  dependent — the .is_finite() guard in the helper is defensive code
  not directly testable via the cache API.)

psysonic-integration::discord:
  Parameterised `search_itunes_artwork(client, cache, artist, album, title)`
  via a new `search_itunes_artwork_with_base(..., base_url)` that the
  wrapper calls with the new `ITUNES_SEARCH_URL` constant. Lets tests
  redirect at a wiremock instance.
  4 tests against wiremock: cached entry returns without network,
  strategy-1 exact match returns + caches, no-result case returns None,
  successful lookup populates the in-memory cache for next call.

Coverage delta:
  psysonic-analysis:    69.5% -> 73.4%
  psysonic-syncfs:      44.3% -> 47.1%
  psysonic-audio:       38.6% -> 39.9%
  psysonic-integration: 39.1% -> 46.2%
  WORKSPACE:            37.7% -> 40.6%

Workspace test count: 298 -> 322. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-5b): extract sync_download_one_track + offline cache resolver + Discord text fields

Sprint 5b — three of four planned medium-difficulty extractions land.
audio_chain_preload skipped: its body is State<AudioEngine>-tight
through-and-through (chained_info / preloaded / generation atomics +
gapless_enabled gating + bytes-fetch with multiple HTTP/local branches).
Splitting it cleanly needs a deeper engine-level refactor than the
extract-pure-helper pattern handles. Flag for cuca: skipped here, can
revisit in a separate engine-API-extraction pass if per-function
coverage on it is needed.

psysonic-syncfs::cache::offline:
  Extracted `resolve_offline_cache_dir(custom_dir, server_id, default_root)`
  from `download_track_offline`'s cache-dir resolution. Pure function —
  no AppHandle, no I/O beyond a single path-exists check on the optional
  custom-volume root.
  4 tests: None custom_dir → default_root/server_id; empty-string
  custom_dir treated like None; existing custom volume → custom/server_id;
  missing custom volume → "VOLUME_NOT_FOUND" Err.

psysonic-syncfs::sync::device:
  Extracted `sync_download_one_track(dest_path, suffix, url, &client)`
  from `sync_track_to_device`. Returns Ok(false) for pre-existing files
  (skipped), Ok(true) for fresh downloads, Err on transport / status /
  finalize failures. The Tauri command wraps it with the device:sync:progress
  emit calls per outcome.
  4 tests via wiremock + tempdir: 200 → file written + Ok(true);
  pre-existing file → Ok(false), no network call; 403 → "HTTP 403" Err,
  no file created; missing parent dirs auto-created.

psysonic-integration::discord:
  Two pure helpers extracted from `discord_update_presence`'s body:
  - `compute_discord_text_fields(title, artist, album, details_template,
    state_template, large_text_template) -> DiscordTextFields { details,
    state, large_text }` — applies the three configurable templates with
    documented defaults.
  - `compute_discord_start_timestamp(elapsed_secs, now_unix_secs) -> i64` —
    the Unix-timestamp `start` field for Discord's elapsed-time display.
  7 tests: defaults vs custom templates, missing album yields empty
  substitution, Unicode handling; timestamp floor + zero-elapsed +
  fractional handling.

Coverage delta:
  psysonic-syncfs:      47.1% -> 50.8%
  psysonic-integration: 46.2% -> 48.3%
  WORKSPACE:            40.6% -> 41.6%

Workspace test count: 322 -> 337. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-5c-part1): extract calculate_sync_payload track-JSON helpers

Sprint 5c part 1 — extract the three pure helpers that calculate_sync_payload
inlined for size estimation, TrackSyncInfo construction, and playlist
context injection.

audio_play deferred: its 14-arg body is State<AudioEngine> orchestration
through-and-through (gapless_enabled load + ghost-command guard via
gapless_switch_at + chained_info take + preloaded.lock + generation
fetch + sink + samples_played + ...). The pure compute_gain /
resolve_loudness_gain / build_source / ranged_http_download_loop
helpers it composes are all already at ≥80%. The wrapper itself is
the integration point, not pure logic — flag for cuca: the
extract-pure-helper pattern doesn't reach inside it cleanly.

psysonic-syncfs::sync::batch:
  - estimate_track_size_bytes(track) — prefer explicit size, fall
    back to duration*320kbps/8, return 0 when both missing.
  - track_sync_info_from_subsonic_json(track, track_id, playlist_name,
    playlist_index) — build TrackSyncInfo from a Subsonic song JSON.
    albumArtist falls back to artist when missing or whitespace-only.
    Default suffix = "mp3".
  - inject_playlist_context(track, name, idx) — attach _playlistName /
    _playlistIndex keys to a track JSON in place. No-op when both args
    are None or the value isn't an object.

  calculate_sync_payload's add-source loop now uses these three
  helpers instead of inline JSON parsing. Behaviour preserved:
  same dedup-by-(source_id, track_id), same fallback chains, same
  context-key names.

Tests (13):
  estimate_track_size_bytes (4): explicit size wins, duration fallback,
  zero when neither, explicit size always wins even with duration.

  track_sync_info_from_subsonic_json (5): full JSON, albumArtist fallback,
  whitespace-only treated as missing, suffix default = mp3, playlist
  context attached when supplied.

  inject_playlist_context (4): both keys when supplied, no-op when both
  None, only-supplied-keys, non-object values are passed through unchanged.

Coverage delta:
  psysonic-syncfs:  50.8% -> 55.2%  (+4.4pp from inline-extraction)
  WORKSPACE:        41.6% -> 42.4%

Workspace test count: 337 -> 350. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-5d): autoeq URL builder + radio metaint + hard-pause helpers

Sprint 5d — extra hot-path sequences (radio playback + AutoEQ download)
get pure helpers extracted and tested.

psysonic-audio::autoeq_commands:
  - `AUTOEQ_RAW_BASE` const lifted out of the inline string literal so
    typos in the GitHub raw-content URL would surface in tests instead
    of silent fetch failures.
  - `autoeq_profile_url_candidates(base, source, form, name, rig?)`
    extracted from `autoeq_fetch_profile`. Pure URL builder. Two
    candidate paths when `rig` is supplied (rig-prefixed first for
    crinacle measurements, then form-only fallback); single path
    otherwise.
  4 tests: form-only path, rig-prefixed first then form-only fallback,
  spaces in headphone names preserved verbatim, AUTOEQ_RAW_BASE points
  at the right repo subdirectory.

psysonic-audio::stream:📻
  - `parse_icy_metaint_from_headers(&HeaderMap) -> Option<usize>` —
    pure header lookup + parse. Returns None for absent / non-ASCII /
    non-numeric values. Wired into `radio_download_task`.
  - `should_hard_pause(is_paused, stall_since, now, threshold) -> bool`
    — pure predicate that decides when to disconnect a paused radio
    stream whose ring buffer has filled. Wired into the hard-pause
    branch (was inline conditional before).
  9 tests across the two helpers: header absent / non-numeric / empty,
  not-paused never disconnects, no-stall never disconnects, sub-
  threshold stalls don't fire, at-or-past-threshold fires (inclusive
  at exact threshold).

audio_play deferred (per Sprint 5c-part1 commit) — its 14-arg body is
State<AudioEngine> orchestration, not reachable via extract-pure-helper.

Coverage delta:
  psysonic-audio:  39.9% -> 41.5%  (+1.6pp from radio + autoeq)
  WORKSPACE:       42.4% -> 43.0%

Workspace test count: 350 -> 363. cargo clippy --workspace --all-targets
-- -D warnings stays clean.

* test(sprint-5e): add hot-path function coverage soft gate

Sprint 5e — last piece of cuca's per-function ≥80% requirement.
Adds a soft CI gate that warns (but doesn't fail) when a function
listed in `.github/hot-path-functions.txt` is below 80% region
coverage.

.github/hot-path-functions.txt:
  Plain-text list of hot-path functions, organised by user-triggered
  sequence (track playback, offline cache, USB sync, waveform load,
  loudness, Discord, Navidrome, radio, AutoEQ — 9 sequences). Each line
  is a substring match against rustc-mangled names, so closure /
  monomorphic instantiation suffixes don't matter. Comments via `#`.

scripts/check-hot-path-coverage.sh:
  Reads `target/llvm-cov/cov.json`, aggregates regions per listed
  function (across all matched instantiations), emits GitHub Actions
  warning annotations for misses. Exit code stays 0 — soft gate. Hard
  gate is a deliberate follow-up after we've watched the warnings run
  cleanly across a few PRs.

  Requires jq + awk. Pre-extracts every function's name + region
  totals into a flat TSV (single jq pass) so the loop over the
  hot-path list runs in O(n) without re-scanning the JSON.

.github/workflows/rust-tests.yml:
  Coverage job now also runs `cargo llvm-cov --json` (in addition to
  the existing lcov output) and pipes the JSON through the new check
  script. Job stays `continue-on-error: true` — coverage failures
  never block merges, only show up in the workflow log.

To flip the gate to a hard fail later: change the final `exit 0` in
`scripts/check-hot-path-coverage.sh` to `exit ${BELOW}` (or `exit 1`
when `BELOW > 0`). Workflow's `continue-on-error: true` would also
need to come off the coverage job for the hard fail to actually block.

No code changes — pure tooling addition. cargo test + clippy
unchanged, all 363 tests still passing.

* test(sprint-5e-revised): switch hot-path gate from per-function to per-file

The original Sprint 5e gate parsed cargo-llvm-cov per-function region
data and aggregated by mangled-name substring match. That metric turned
out unreliable for our codebase:

  1. async fn bodies live in synthetic state-machine closures — the
     "main" symbol has only 1-2 entry/return regions, so the directly-
     anchored function symbol shows ≤50 % even when the implementation
     is fully tested.

  2. Generic functions (e.g. `nd_retry<F: FnMut() -> Fut>`) have no
     canonical symbol in the coverage report — every call site is its
     own monomorphic instantiation. Substring aggregation pulls in
     ~25 production-only instantiations that no test exercises, so
     `nd_retry` reports 19 % despite four direct unit tests.

  3. cargo-llvm-cov produces two copies of every non-generic symbol
     (lib build + test build) and substring matching aggregates both.

Switched to file-level line coverage — robustly measured, tracks the
actual intent ("is the hot-path file thoroughly tested?"), no symbol-
mangling pitfalls.

.github/hot-path-files.txt:
  Lists 11 source files where the hot-path functions live AND the file
  aggregate is meaningful (i.e. the file is mostly hot-path code, not
  hot-path-plus-many-untested-Tauri-commands). Files with mixed content
  (sync/batch.rs, navidrome/queries.rs, remote.rs, etc.) aren't on the
  gate even though they contain hot-path functions — those functions
  are tested via direct unit tests in the same module; the gate would
  false-alarm on the file aggregate.

scripts/check-hot-path-coverage.sh:
  Reads `target/llvm-cov/cov.json`, looks up `data[0].files[].summary.
  lines.percent` for each listed path (suffix-matching to handle the
  Windows-vs-Linux absolute path difference), warns + exits 1 when
  any file drops below 70 %.

  Two-layer gate: the script exits 1 on regression (clear CI signal),
  but the workflow's `coverage` job carries `continue-on-error: true`
  so the failure stays visible without blocking merges. Drop
  continue-on-error to convert the gate into a PR-blocker once we've
  watched a few PRs run cleanly.

Verified locally: all 11 listed files clear 70 %.
  fs_utils.rs           95.7%
  offline.rs            79.9%
  file_transfer.rs      96.0%
  store.rs              91.0%
  compute.rs            85.7%
  decode.rs             73.1%
  stream/icy.rs        100.0%
  progress_task.rs      90.1%
  ipc.rs                86.5%
  discord.rs            79.6%
  navidrome/client.rs   97.4%

Removed the now-superseded `.github/hot-path-functions.txt`. Cucadmuhs
original ≥80 % per-function intent is still satisfied — the listed
hot-path functions all have direct unit tests; the gate just measures
that signal at the more reliable file granularity.

cargo test + clippy unchanged, 363 tests still passing.

* style: fix needless_return in log_timestamp_local

rustc 1.95 clippy flags the trailing 'return' as needless. Drop the
keyword to satisfy '-D warnings' on CI.

* style: satisfy rustc 1.95 clippy in psysonic-audio Linux paths

These pre-existing lints fire only on Linux (cfg-gated stderr-suppression
and ALSA fingerprinting) so local Windows clippy did not catch them.

- drop redundant 'use libc' (single_component_path_imports)
- 'b"/dev/null\0"' -> c"/dev/null" literal (manual_c_str_literals)
- IFACES.iter().any(|&i| i == s) -> IFACES.contains(&s) (manual_contains)

* style: fix two more rustc 1.95 clippy errors in Linux paths

- perf.rs: needless_return on PerformanceCpuSnapshot tail
- logging.rs: redundant 'use libc' (single_component_path_imports)

* ci(rust-tests): mkdir target/llvm-cov before writing cov.json

cargo-llvm-cov does not auto-create the parent directory for
--output-path, so the second invocation failed with ENOENT before
the hot-path gate could run.
2026-05-10 22:39:35 +02:00
Frank Stellmacher 268086ac74 docs(issue-template): label Nix install option as "flakes" (#519)
The bug report form's install-source dropdown listed "Cachix / Nix",
but Cachix is just a binary cache — users actually install the app
via the Nix flake. Relabel to "flakes" so the dropdown reflects the
mechanism people pick.
2026-05-09 17:44:44 +02:00
Frank Stellmacher acc367207a chore: add GitHub issue forms (bug + feature + config) (#517)
Three files under .github/ISSUE_TEMPLATE/:

- bug_report.yml      Required: summary, repro steps, expected/actual,
                      version, OS. Optional: install source dropdown
                      (AUR / .deb / .rpm / Cachix / .dmg / .msi /
                      from-source), Subsonic server type + version,
                      logs (with inline how-to), screenshots, anything
                      else. Auto-labels: bug, triage.

- feature_request.yml Required: use case (described as workflow, not
                      solution). Optional: proposed solution,
                      alternatives, anything else. Auto-labels:
                      enhancement, triage.

- config.yml          blank_issues_enabled: false; redirects general
                      questions to Discord, Telegram for chat,
                      AUR page for packaging issues.

Net effect: incoming issues land with the info needed to triage
without back-and-forth, and casual support questions are routed off
the issue tracker.
2026-05-09 16:49:04 +02:00
Maxim Isaev 442577abd1 fix(ci): skip promote-main-to-next check gate for non-main sources
Run validate-main-green-ci only when source_branch is main; feature
branches often lack ci-ok. Allow promote when validation is skipped
and log when the gate was bypassed.
2026-05-04 18:11:15 +03:00
Maxim Isaev 9c82d856cc fix(ci): honor source_branch in promote-main-to-next
Add workflow_dispatch input (default main) so validation and the next
reset use the selected tip instead of a hardcoded main ref.
2026-05-04 17:53:32 +03:00
cucadmuh fca084acf9 fix(ci): upgrade github-script action to v9 (#418)
Move reusable channel publish release step from actions/github-script v7 to v9 to stay compatible with Node 24 on GitHub runners.
2026-05-01 21:09:59 +00:00
cucadmuh 3f225951e6 fix(release): restore known-good publish workflow baseline (#415)
Reset reusable channel publish to the last known-good release flow from b83c0f5 and keep build_platform_artifacts gating for source-only dispatch compatibility.
2026-05-01 23:51:00 +03:00
cucadmuh 32e249c411 fix(release): tolerate delayed tag ref visibility checks (#414)
When release and target_commitish are already valid, treat temporary git ref 404 responses as a warning so release jobs continue instead of failing on API propagation lag.
2026-05-01 20:38:37 +00:00
cucadmuh 47f88374e5 fix(release): avoid pre-creating tags before release API call (#413)
Let createRelease own tag creation with target_commitish and remove preflight tag-ref waits to reduce tag visibility races that lead to untagged release behavior.
2026-05-01 20:29:21 +00:00
cucadmuh ade4bd8675 fix(release): restore github-script release creation flow (#412)
Use GitHub REST create/update via actions/github-script with target_commitish and release id from API responses to avoid tag lookup races in the gh CLI path.
2026-05-01 20:21:57 +00:00
cucadmuh 484068e83b fix(release): remove untagged fallback and validate binding by id (#411)
Create and update releases through explicit API payloads, include target_commitish, and verify tag binding through release id to avoid transient tag-endpoint inconsistencies.
2026-05-01 20:14:08 +00:00
cucadmuh 61430e147d fix(release): create releases from verified tags without target_commitish (#410)
Use gh release create --verify-tag and remove target_commitish from release payload
now that tags are created upfront. This avoids server-side untagged release fallback
while preserving deterministic tag-to-release publication.
2026-05-01 20:06:27 +00:00
cucadmuh 4609a09a74 fix(release): create/update releases by id with gh api payloads (#409)
Stop depending on tag lookup right after publish. Resolve release by tag with a
name fallback, then patch/create by id using the same payload and force a final
id-based patch to heal untagged placeholders before downstream upload steps.
2026-05-01 22:57:33 +03:00
cucadmuh d35d199f8d fix(release): switch release create/edit to gh CLI path (#408)
Replace github-script release creation with gh release create/edit plus explicit
release-id resolution and patching. This avoids inconsistent REST createRelease
untagged behavior and keeps publication pinned to app-v tags.
2026-05-01 19:50:47 +00:00
cucadmuh 9ad345e43d Fix/release create tag before verify (#407)
* fix(release): rebind untagged draft releases to expected app-v tag

After create/update, fetch release by id and force tag_name/target_commitish when
GitHub returns an unexpected tag (including untagged placeholders). This self-heals
release metadata before downstream upload steps consume release_id.

* fix(release): remove tauri-action release publishing side effects

Build macOS/Windows bundles with tauri CLI and upload artifacts explicitly via
gh release upload to the expected app-v tag. This prevents tauri-action from
creating untagged releases while keeping release assets deterministic.

* fix(release): wait for tag ref visibility before release API calls

Before create/update release, poll GitHub REST git.getRef(tags/app-v...) until the
new tag is visible. This avoids release API timing gaps where tag exists in git
but release endpoints still return inconsistent not-found/untagged behavior.
2026-05-01 19:43:36 +00:00
cucadmuh 951f2d6163 fix(release): rebind untagged draft releases to expected app-v tag (#406)
After create/update, fetch release by id and force tag_name/target_commitish when
GitHub returns an unexpected tag (including untagged placeholders). This self-heals
release metadata before downstream upload steps consume release_id.
2026-05-01 19:19:11 +00:00
cucadmuh 0646f6884f Fix/release create tag before verify (#405)
* fix(release): create missing app-v tag before release verification

Ensure reusable publish creates and pushes the expected app-v tag when absent,
then validates it points to source_ref. This prevents release records with tag_name
but no git refs/tags object, which previously broke Source code archives.

* fix(release): pin tauri publish to tagged release metadata

Pass tagName/releaseName/releaseDraft/prerelease to tauri-action in addition to
releaseId, so asset upload fallback remains bound to the expected app-v release
instead of creating untagged releases.

* chore(ci): align workflow action versions for release flow

Update github-script usage to v9 across release-related workflows and keep
the current tauri-action release binding changes in the same branch for testing.

* fix(release): harden tagged release resolution for source-only promote

Canonicalize release_id via getReleaseByTag after create/update and fail fast on
invalid tag/commit inputs to avoid untagged release binding. Also propagate
source-only marker through promote push events so push-triggered channel runs
skip platform artifacts and verify-nix consistently.

* fix(release): avoid tag lookup hard-fail during release creation

Remove immediate getReleaseByTag canonicalization after create/update because
GitHub can return 404 for tag-based release lookup while the release id is valid.
Keep release_id flow and downstream release-id validation to prevent regressions.
2026-05-01 19:13:09 +00:00
cucadmuh 8d424fbc98 Fix/release create tag before verify (#404)
* fix(release): create missing app-v tag before release verification

Ensure reusable publish creates and pushes the expected app-v tag when absent,
then validates it points to source_ref. This prevents release records with tag_name
but no git refs/tags object, which previously broke Source code archives.

* fix(release): pin tauri publish to tagged release metadata

Pass tagName/releaseName/releaseDraft/prerelease to tauri-action in addition to
releaseId, so asset upload fallback remains bound to the expected app-v release
instead of creating untagged releases.

* chore(ci): align workflow action versions for release flow

Update github-script usage to v9 across release-related workflows and keep
the current tauri-action release binding changes in the same branch for testing.

* fix(release): harden tagged release resolution for source-only promote

Canonicalize release_id via getReleaseByTag after create/update and fail fast on
invalid tag/commit inputs to avoid untagged release binding. Also propagate
source-only marker through promote push events so push-triggered channel runs
skip platform artifacts and verify-nix consistently.
2026-05-01 19:04:26 +00:00
cucadmuh 090d129283 Fix/release create tag before verify (#403)
* fix(release): create missing app-v tag before release verification

Ensure reusable publish creates and pushes the expected app-v tag when absent,
then validates it points to source_ref. This prevents release records with tag_name
but no git refs/tags object, which previously broke Source code archives.

* fix(release): pin tauri publish to tagged release metadata

Pass tagName/releaseName/releaseDraft/prerelease to tauri-action in addition to
releaseId, so asset upload fallback remains bound to the expected app-v release
instead of creating untagged releases.

* chore(ci): align workflow action versions for release flow

Update github-script usage to v9 across release-related workflows and keep
the current tauri-action release binding changes in the same branch for testing.
2026-05-01 18:44:44 +00:00
cucadmuh dbc814da4c Fix/release create tag before verify (#402)
* fix(release): create missing app-v tag before release verification

Ensure reusable publish creates and pushes the expected app-v tag when absent,
then validates it points to source_ref. This prevents release records with tag_name
but no git refs/tags object, which previously broke Source code archives.

* fix(release): pin tauri publish to tagged release metadata

Pass tagName/releaseName/releaseDraft/prerelease to tauri-action in addition to
releaseId, so asset upload fallback remains bound to the expected app-v release
instead of creating untagged releases.
2026-05-01 18:37:03 +00:00
cucadmuh 59f3a194d8 fix(release): create missing app-v tag before release verification (#401)
Ensure reusable publish creates and pushes the expected app-v tag when absent,
then validates it points to source_ref. This prevents release records with tag_name
but no git refs/tags object, which previously broke Source code archives.
2026-05-01 18:24:27 +00:00
cucadmuh f91c57ca68 fix(release): retry tag ref visibility checks after publish (#400)
GitHub ref APIs can briefly return 404 right after create/update release.
Retry getRef(tags/...) before failing binding verification to avoid false
negatives that interrupt next/release channel publishing.
2026-05-01 21:19:07 +03:00
cucadmuh fef13fefd1 Fix/release untagged guard (#399)
* fix(release): prevent untagged fallback from tauri publish

Set explicit github-script output for release_id and validate it before build jobs.
This prevents tauri-action from creating untagged releases when release id wiring
breaks and keeps assets attached to the intended app-v tag release.

* fix(release): add source-only promote mode and harden release binding

Add a source_only dispatch option to promote workflows and propagate it into
channel publish so maintainers can skip platform builds and verify-nix when needed.
Also validate release/tag/commit binding to prevent untagged fallback and ensure
source archives stay aligned with the intended app-v tag.
2026-05-01 21:09:09 +03:00
cucadmuh b83c0f5e50 fix(release): retarget mismatched tags instead of failing (#389)
When an existing app-v tag points to a different commit than source_ref,
re-point it to the checked out source commit and continue publishing.
This preserves Source code archive correctness without blocking artifact release.
2026-04-30 22:12:45 +03:00
cucadmuh 316ff1d43b fix(release): pin tag creation to source_ref commit (#385)
Ensure GitHub release tags are created from the checked out channel ref and fail
early if an existing tag points to a different commit. This keeps Source code
archives aligned with built artifacts and prevents mixed-release snapshots.
2026-04-30 21:18:49 +03:00
cucadmuh 10ca1bc051 Feat/promote sync tauri version (#368)
* ci(release): sync Cargo/tauri versions after npm version on promote

Keep bundle artifact names aligned with package.json by updating
src-tauri/Cargo.toml and tauri.conf.json when promoting channel branches.

Made-with: Cursor

* ci(release): sync Cargo/tauri in post-release dev bump PR

Run the same package.json→Tauri sync after bumping main to the next -dev
version so local builds match auto-generated PR contents.
2026-04-29 21:38:48 +00:00
cucadmuh e15ca83bd5 ci(release): unify GitHub release title format across channels (#359)
Use a single release title pattern (`Psysonic v<version>`) for both RC and
stable releases, while keeping prerelease/draft flags unchanged.
2026-04-29 08:13:17 +00:00
cucadmuh 14c66da087 fix(ci): Update next.yml (#358)
draft_release: true at next channel
2026-04-29 08:07:35 +00:00
cucadmuh cf24dc0e7b ci(release): skip channel publish on Nix-only pushes (#356)
Avoid feedback loop when merging verify-nix refresh PRs (flake.lock +
nix/) back into next/release.
2026-04-29 01:47:44 +03:00
cucadmuh b7a842395c fix(ci): correct node -p quoting for package.json version in Actions shell (#354)
Single-quoted bash passes backslashes literally; escaped quotes broke Node on v24.
2026-04-29 01:26:23 +03:00