Commit Graph

1128 Commits

Author SHA1 Message Date
Frank Stellmacher 2c5659b425 refactor(player): E.31 — extract Last.fm love actions as factory (#595)
Four Last.fm-related actions move out of the playerStore create()
body into `src/store/lastfmActions.ts` as a `createLastfmActions(set, get)`
factory:

  - `toggleLastfmLove` — flip love + write through to the cache map
  - `setLastfmLoved` — force-set (used by external events)
  - `setLastfmLovedForSong` — write cache for an arbitrary title/artist
  - `syncLastfmLovedTracks` — startup bulk fetch + merge

The store body uses `...createLastfmActions(set, get)` to inline them
back into the actions map. First action-factory cut — sets the
pattern for follow-up Phase E extractions of larger action groups
(playback transport, queue mutators, etc.).

Side-cleanup: 3 last.fm imports drop from playerStore
(`lastfmLoveTrack`, `lastfmUnloveTrack`, `lastfmGetAllLovedTracks`)
since they only fed the moved actions.

playerStore 1550 → 1504 LOC.
2026-05-12 20:17:59 +02:00
Frank Stellmacher 8dfe05fe7d refactor(player): E.30 — extract applyQueueHistorySnapshot (#594)
The ~150-LOC `applyQueueHistorySnapshot` helper that lived inside the
playerStore `create((set, get) => { … })` closure moves out into
`src/store/applyQueueHistorySnapshot.ts`. The function now takes the
zustand `set` / `get` references as explicit parameters; the two
caller sites (`undoLastQueueEdit`, `redoLastQueueEdit`) pass them
through unchanged.

Side-cleanup: four imports that only fed the moved helper drop from
playerStore (getPlaybackSourceKind, queueUndoRestoreAudioEngine,
setPendingQueueListScrollTop, shallowCloneQueueTracks).

playerStore 1706 → 1550 LOC (−156).

The undo/redo flow keeps behaving 1:1 — the function is exported and
deterministic; the closure capture only existed for the set/get pair
which is trivial to pass through.
2026-05-12 20:07:44 +02:00
Frank Stellmacher 6438fff019 refactor(player): E.29 — extract Track + PlayerState types (#593)
The two TypeScript type definitions that other store modules already
depend on move into `src/store/playerStoreTypes.ts`. playerStore.ts
re-exports both for backward compatibility — the ~40 callers
(components, tests, sibling store modules) keep their existing
`import type { Track } from '@/store/playerStore'` imports working.

Side-cleanup: `InternetRadioStation` and `PlaybackSourceKind` imports
drop from playerStore (the new types module pulls them directly).

No behaviour change — pure type relocation.

playerStore 1879 → 1706 LOC (−173).
2026-05-12 19:58:23 +02:00
Frank Stellmacher b0418bf920 refactor(player): E.28 — extract storage + hotkey helpers cluster (#592)
Two small file-private bits move out of playerStore.ts:

  - `src/store/queueVisibilityStorage.ts` — `readInitialQueueVisibility`
    and `persistQueueVisibility` (the QueuePanel show/hide toggle
    survives reloads via a localStorage round-trip; SSR / private-mode
    failures swallowed silently).
  - `src/store/queueUndoHotkey.ts` — `installQueueUndoHotkey` (Ctrl+Z /
    Cmd+Z queue undo, Ctrl+Shift+Z redo, document-capture; skips text
    fields so native text undo stays; idempotent via window-scoped
    flag; mini-player window skipped). Added a `_resetQueueUndoHotkeyForTest`
    that removes the keydown listener too (needed so vitest specs
    don't accumulate handlers across tests).

playerStore re-exports `installQueueUndoHotkey` so bootstrap + tests
keep their existing `from './playerStore'` imports. The
queue-visibility helpers were file-private; no re-exports.

Side-cleanup: `getWindowKind` import is gone from playerStore (only
the moved hotkey installer used it).

16 focused tests pin the storage round-trip, the idempotency flag, the
modifier + key matching, the editable-target skip, and the
preventDefault contract.

playerStore 1940 → 1879 LOC.
2026-05-12 19:41:57 +02:00
Frank Stellmacher 013d6144ca refactor(player): E.27 — extract initAudioListeners into module (#591)
`initAudioListeners` (~430 LOC) moves out of playerStore.ts into
`src/store/initAudioListeners.ts`. The function brings together
several distinct orchestrators: the 7 audio event listeners, startup
Last.fm loved-sync, initial audio-settings push to Rust, the auth
subscriber for live audio-settings changes, the analysis-storage
change handler, MPRIS / OS media controls sync, radio ICY metadata
forward, and Discord Rich Presence sync. Pure code move — no
sub-orchestrator split yet (could be follow-up cuts under
src/store/audio-init/ if it gets unwieldy).

playerStore re-exports `initAudioListeners` so MainApp + the three
characterization test files keep their `from './playerStore'`
imports.

Side-cleanup: 15 more imports drop from playerStore that were only
fed into the now-moved code (analysisSync, normalizationDebug,
normalizationIpcDedupe, normalizationCompare, NORMALIZATION_UI_*,
listen, streamUrlTrackId, buildCoverArtUrl, getAlbumInfo2,
normalizeAnalysisTrackId, bumpWaveformRefreshGen,
clearLoudnessCacheStateForTrackId, setCachedLoudnessGain).

playerStore 2394 → 1940 LOC (−454).
2026-05-12 19:25:34 +02:00
Frank Stellmacher 0cb7fba272 refactor(player): E.26 — extract Rust audio event handlers cluster (#590)
The five `handleAudio*` functions + the `NormalizationStatePayload`
type move into `src/store/audioEventHandlers.ts`:

  - `handleAudioPlaying` — flips isPlaying true + resets progress emit
    throttles + lets hot-cache prefetch resume
  - `handleAudioProgress` (~220 LOC) — the big one: seek-guard, visual
    target apply, live progress emit, store commit, scrobble@50%,
    server heartbeat, byte-preload + gapless-chain triggers
  - `handleAudioEnded` — gapless-switch suppression + radio cleanup +
    repeat-one branch with hot-cache promote + queue advance
  - `handleAudioTrackSwitched` — gapless auto-advance UI sync + Now
    Playing + waveform/loudness refresh
  - `handleAudioError` — toast + skip-after-1.5 s with generation
    guard

`initAudioListeners` (still in playerStore) imports the handlers from
the new module. Side-cleanup: 24 imports in playerStore that were
only consumed by these handlers are gone (bumpPerfCounter,
getPerfProbeFlags, the throttle accessor pair, the playback-progress
emit pair, scrobbleSong, lastfmScrobble, seek target / debounce
accessors, gapless-preload accessors, plus a handful of constants).

Behaviour preserved verbatim — existing `playerStore.events.test.ts`
+ `playerStore.progress.test.ts` characterization suites still pin
the handlers via the live Tauri event channel.

playerStore 2779 → 2394 LOC (−385).
2026-05-12 19:09:32 +02:00
Frank Stellmacher a5aadeea67 refactor(player): E.25 — extract audio-orchestration cluster (#589)
Two thematic cuts in one PR:

  - `src/store/queueUndoAudioRestore.ts` — `queueUndoRestoreAudioEngine`
    (~70 LOC). Reload the Rust audio engine to match a queue-undo
    snapshot: audio_play with snapshot track params, optional
    audio_seek to the snapshot position, audio_pause if the snapshot
    captured a paused state. Generation-guard bails on concurrent
    playTrack. Drives recordEnginePlayUrl, setDeferHotCachePrefetch,
    and touchHotCacheOnPlayback.
  - `src/store/loudnessPrefetch.ts` — `prefetchLoudnessForEnqueuedTracks`.
    Warms the loudness cache for the current track + next-N window
    after a bulk enqueue, no-op when normalization isn't loudness.

Both file-private; no caller-side changes outside playerStore's own
imports. Removes the unused `collectLoudnessBackfillWindowTrackIds`
import that was only feeding the moved prefetch helper.

11 tests across the two modules pin the orchestration: audio_play
payload + seek-when-near-zero + wantPlaying=false → audio_pause +
generation-mismatch bail + .finally clears the hot-cache gate even
on errors; engine guard + window forwarding + sync-flag for prefetch.

playerStore 2865 → 2779 LOC.
2026-05-12 18:08:09 +02:00
Frank Stellmacher 14bdcde33f refactor(player): E.24 — extract radio session + infinite-queue guards (#588)
Cluster of four small mutables in two modules:

  - `src/store/radioSessionState.ts` — `radioFetching` (concurrent
    fetch guard) + `currentRadioArtistId` (seed artist that survives
    track advances) + `radioSessionSeenIds` (dedupe set including
    HISTORY_KEEP-evicted entries, fixes issue #500).
  - `src/store/infiniteQueueState.ts` — `infiniteQueueFetching`
    concurrent fetch guard.

Sed-driven bulk rewrite for the >35 direct-access sites. The four
`= new Set()` resets become `clearRadioSessionSeenIds()` calls and
the `setRadioArtistId` / `enqueueRadio` actions read through
`getCurrentRadioArtistId()` instead of touching the mutable directly.

15 focused tests across the two modules.

playerStore 2867 → 2865 LOC.
2026-05-12 17:26:15 +02:00
Frank Stellmacher 6355946610 refactor(player): E.23 — extract engine state + seek debounce cluster (#587)
Two thematic cuts in one PR:

  - `src/store/engineState.ts` — `isAudioPaused` (warm-vs-cold-resume
    decision flag) + `playGeneration` (monotonically bumped guard
    counter used by long-running async callbacks to detect concurrent
    playTrack and bail). Get/set accessors + `bumpPlayGeneration()`
    that returns the new value (mirrors the original `++playGeneration`
    pattern).
  - `src/store/seekDebounce.ts` — seek-slider debounce timer behind
    `armSeekDebounce(delayMs, onFire)` / `clearSeekDebounce()` /
    `isSeekDebouncePending()`. Collapses the recurring inline
    `if (seekDebounce) { clearTimeout(...); seekDebounce = null; }`
    triple into single calls.

Sed-driven bulk rewrite for the >60 direct-access sites preserved
semantics verbatim (one JSDoc reference to `isAudioPaused` kept as
comment text). 14 tests across the two modules.

playerStore 2869 → 2867 LOC net (small delta — the imports are bigger
than the savings, but the mutables are no longer reachable from
outside their owning modules).
2026-05-12 17:14:37 +02:00
Frank Stellmacher 0eb084c5f8 refactor(player): E.22 — extract seek-fallback retry + visual target state (#586)
The streaming-fallback seek recovery loop + its visual coverup move
into `src/store/seekFallbackState.ts`:

  - 6 module mutables (retry timer + start + target; fallback trackId +
    restartAt; visual target)
  - 3 const gates (180 ms retry interval, 6 s retry budget, 1.6 s
    visual guard)
  - `scheduleSeekFallbackRetry(trackId, seconds)` — bounded retry loop
    that hits `audio_seek` every 180 ms up to 6 s, re-scheduling on
    recoverable errors and clearing the visual target on success or
    hard failure
  - `clearSeekFallbackRetry()` — cancel timer + reset state
  - get/set accessors for the three caller-touched fields
    (`SeekFallbackVisualTarget`, trackId, restartAt)

playerStore's ~30 direct-access sites become accessor calls. Inside
the progress handler the visual target is captured into a local once
per call so type narrowing + repeated reads stay clean.

17 focused tests pin the constants, get/set round-trips, the retry
loop's happy path (setSeekTarget + clear visual), recoverable retry
re-schedule, non-recoverable abort, track-change abort, retry-budget
exhaustion, and the three coalesce cases (different track id /
seconds delta > 0.25 s / seconds delta ≤ 0.25 s).

playerStore 2909 → 2869 LOC.
2026-05-12 17:01:22 +02:00
Frank Stellmacher c10eabe114 refactor(player): E.21 — extract playback-progress throttle timestamps (#585)
Three time-based throttles used by the audio-progress handler move into
`src/store/playbackThrottles.ts`:

  - **Live progress emit** (1.5 s / 0.9 s position delta) — feeds the
    high-frequency pub/sub
  - **Store progress commit** (20 s / 5 s position delta) — writes the
    Zustand store
  - **Normalization UI update** (120 ms) — live dB readout throttle

Module owns three private mutables, exports five constants (the four
window/delta gates + NORMALIZATION_UI_THROTTLE_MS) and six accessors
(get / mark for each), plus `resetProgressEmitThrottles` for the
track-boundary reset path that handleAudioPlaying calls.

playerStore's six direct-access sites + two reset writes collapse to
imports. Behaviour preserved verbatim.

13 focused tests pin each throttle's get/mark cycle, the partial reset
(progress only, not normalization), and constant values.

playerStore +6 LOC net (more import surface than freed mutables) —
shrinkage will come back on the next bigger encapsulation; this PR's
win is logical separation + testability rather than line count.
2026-05-12 16:45:57 +02:00
Frank Stellmacher 6d07720b4f refactor(player): E.20 — extract HTML5 radio player (#584)
The HTMLAudioElement that handles internet-radio streams + its six
event listeners + the bounded stalled-reconnect loop move into
`src/store/radioPlayer.ts`. The module owns the singleton audio
element, the `radioStopping` suppression flag, the reconnect counter
and timer, and `MAX_RADIO_RECONNECTS`. Public API:

  - `playRadioStream(url, volume)` — sets src + clamped volume + play,
    resets reconnect counter
  - `pauseRadio()` / `resumeRadio()` — soft pause/resume (keep src)
  - `stopRadio()` — full stop (flag + pause + clear src + cancel
    reconnect timer)
  - `setRadioVolume(v)` — direct volume with clamp
  - `clearRadioReconnectTimer()` — exposed for cleanup paths

playerStore's seven direct-access patterns become API calls. The
three `radioStopping = true; pause; src = ''` triples collapse to
single `stopRadio()` calls.

18 tests pin the imperative API + the listener loop: ended/error
state-clear, stalled → 4 s reconnect, stalled coalescing, the
MAX_RADIO_RECONNECTS hard stop, playing-resets-counter, and the
suspend → cancel.

playerStore 2983 → 2909 LOC.
2026-05-12 16:28:10 +02:00
Frank Stellmacher 7dc4888a06 refactor(player): E.19 — extract analysis-refresh helpers cluster (#583)
Two thematic cuts in one PR:

  - `src/store/waveformRefresh.ts` — `refreshWaveformForTrack` plus its
    `WaveformCachePayload` type. Fetches the cached waveform row and
    applies bins to the player store, guarded by both the refresh
    generation snapshot and the current-track check so a stale read
    can't overwrite fresh data.
  - `src/store/loudnessRefresh.ts` — `refreshLoudnessForTrack` plus the
    `loudnessRefreshInflight` coalescing map and `LoudnessCachePayload`
    type. Orchestrates the loudness fetch: dedupe concurrent calls by
    (trackId, syncEngine, target), distinguish hit vs miss, enqueue
    bounded backfill, suppress stale-target results by recursive retry.

Both file-private; no caller-side changes outside playerStore's own
imports. Imports of helpers that were only used by these two functions
get cleaned up out of playerStore (coerceWaveformBins, getBackfillAttempts,
forgetLoudnessGain, redactSubsonicUrlForLog, LOUDNESS_BACKFILL_WINDOW_AHEAD,
isTrackInsideLoudnessBackfillWindow, etc.).

20 tests across the two modules pin the orchestration: gen + current-track
guards on waveform; coalesce + hit/miss/backfill/stale-target/sync-flag
branches on loudness.

playerStore 3139 → 2983 LOC — first sub-3000 milestone for Phase E.
2026-05-12 16:15:34 +02:00
Frank Stellmacher 4c64844349 refactor(player): E.18 — extract three transport-coordination modules (#581)
Cluster of three small thematically-related cuts in one PR (per the new
'cluster, don't single-shot' convention):

  - `src/store/seekTargetState.ts` — the seek-target guard (`seekTarget`,
    `seekTargetSetAt`, `SEEK_TARGET_GUARD_TIMEOUT_MS`, set/clear/get
    accessors) that suppresses stale Rust progress ticks until the
    engine catches up to the requested position
  - `src/store/togglePlayLock.ts` — the 300 ms double-click cooldown
    behind a `tryAcquireTogglePlayLock()` helper that auto-releases on
    a timer (collapses the three-line inline pattern in `togglePlay`)
  - `src/store/loudnessReseed.ts` — the full `reseedLoudnessForTrackId`
    pipeline (gen-bump → cache + backfill wipe → state reset → server
    row delete → forced seed enqueue), pulled out of playerStore as a
    single async helper

All three were file-private; no caller-side changes outside
playerStore's own imports. The progress handler's seek-guard branch is
now ~3 lines shorter and reads through accessors. `togglePlay` collapses
to one guard check.

24 tests across the three modules pin the API contracts.

playerStore 3189 → 3139 LOC.
2026-05-12 15:23:40 +02:00
Frank Stellmacher 9029ab8ec5 refactor(player): E.17 — extract stream-cache-to-hot-cache promoter (#580)
`promoteCompletedStreamToHotCache` — wraps the `promote_stream_cache_to_hot_cache`
Rust IPC, forwards the resolved path + size into `useHotCacheStore` as a
`'stream-promote'` entry — moves into `src/store/promoteStreamCache.ts`.
File-private with four call sites; no caller-side changes outside
playerStore's own import.

9 focused tests pin the payload shape (incl. the `'mp3'` suffix fallback
and the null customDir pass-through), the success path that records the
entry, the early-returns for null / empty path, the `size || 0` fallback,
and the silent error swallow.

playerStore 3207 → 3189 LOC.
2026-05-12 15:02:46 +02:00
Frank Stellmacher 3a99be4daa refactor(player): E.16 — extract gapless-preload coordination state (#579)
Three coordinating mutables move into `src/store/gaplessPreloadState.ts`
behind a thin API:

  - `gaplessPreloadingId` / `bytePreloadingId` — guards so the runtime
    doesn't fire a chain-/byte-preload twice for the same id
  - `lastGaplessSwitchTime` — timestamp used by the 500–600 ms
    ghost-IPC suppression guards in `handleAudioEnded` and `playTrack`

Public API: `get…` / `set…` accessors plus `clearPreloadingIds`
(atomic clear of both guards — collapses three `= null; = null;`
duplications) and `markGaplessSwitch` (`Date.now()` stamp). The
mutables are no longer reachable from outside the module.

13 focused tests pin the get/set round-trips, independence between
the two guards, the atomic clear, and the timestamp progression.

playerStore 3208 → 3207 LOC (small delta because the `= null; = null;`
inlines compress to single `clearPreloadingIds()` calls but the
module itself adds the accessor functions to the import list).
2026-05-12 14:53:37 +02:00
Frank Stellmacher 2ad0be6a71 refactor(player): E.15 — extract server queue sync into module (#578)
The server-side queue persistence (Subsonic `savePlayQueue`) helpers
move into `src/store/queueSync.ts`:

  - `syncQueueToServer` — 5-second debounce for rapid edits
  - `flushQueueSyncToServer` — immediate flush (heartbeat, pause,
    app close)
  - `flushPlayQueuePosition` — exported wrapper that reads the live
    playerStore queue + playback-progress current-time, skips radio
    sessions
  - `getLastQueueHeartbeatAt` — accessor the 15-second heartbeat
    throttle in `handleAudioProgress` reads

The two timer/heartbeat mutables (`syncTimeout`, `lastQueueHeartbeatAt`)
are no longer reachable from outside the module. `flushPlayQueuePosition`
is re-exported from playerStore so TauriEventBridge + the persistence
characterization test keep their existing imports.

13 focused tests pin the debounce window, the 1000-id queue cap, the
cancel-on-immediate-flush behaviour, the no-op guards (empty queue /
null currentTrack / radio session), and the heartbeat-timestamp
contract.

playerStore 3238 → 3208 LOC.
2026-05-12 14:43:53 +02:00
Frank Stellmacher 08d098d5aa refactor(player): E.14 — extract loudness-backfill-window helpers (#577)
The `LOUDNESS_BACKFILL_WINDOW_AHEAD` constant, the predicate
`isTrackInsideLoudnessBackfillWindow`, and the id-list collector
`collectLoudnessBackfillWindowTrackIds` move into
`src/store/loudnessBackfillWindow.ts`.

`isTrackInsideLoudnessBackfillWindow` was rewritten to be pure — it
now takes the queue / queueIndex / currentTrack as explicit
parameters instead of reading `usePlayerStore.getState()` internally.
The one call site in `refreshLoudnessForTrack` reads state once and
passes it through. Net: zero behaviour change, clearer test surface
(no store mocks), no top-level coupling back to playerStore.

`prefetchLoudnessForEnqueuedTracks` stays in playerStore — it calls
`refreshLoudnessForTrack` which lives there too.

13 focused tests pin the window-slides-with-queueIndex contract, the
clamp at the end of the queue, the empty-input fallbacks, and the
duplicate collapse when currentTrack is also in the ahead range.

playerStore 3261 → 3238 LOC.
2026-05-12 14:36:55 +02:00
Frank Stellmacher c88649836e refactor(player): E.13 — extract loudness-backfill retry state (#576)
The two parallel maps that bound the per-track loudness backfill
retries (`analysisBackfillInFlightByTrackId`,
`analysisBackfillAttemptsByTrackId`) plus the `MAX_BACKFILL_ATTEMPTS_PER_TRACK`
constant and the `resetLoudnessBackfillStateForTrackId` reseed helper
move into `src/store/loudnessBackfillState.ts`. The new module exposes
a thin API:

  - `isBackfillInFlight` / `getBackfillAttempts` (reads)
  - `markBackfillInFlight(trackId, nextAttempt)` (atomic flag + counter)
  - `clearBackfillInFlight` (after promise settles)
  - `resetBackfillAttempts` (after refresh-hit)
  - `resetLoudnessBackfillStateForTrackId` (full reset across both id forms)

playerStore's five direct-access sites inside `refreshLoudnessForTrack`
become API calls; the mutables are no longer reachable from outside the
module. 13 focused tests pin atomicity, independence between tracks,
the partial-clear shapes (flag-only / counter-only), and the two-form
reseed expansion.

playerStore 3263 → 3261 LOC (small line delta because the inflight
flag + counter setup collapses to one call but the reset helper is no
longer inline).
2026-05-12 14:29:33 +02:00
Frank Stellmacher 85df3e42c1 refactor(player): E.12 — extract skip-to-1★ helper (#575)
`applySkipStarOnManualNext` — the helper that records a manual `next()`
into the per-track skip counter and auto-rates the track 1★ once the
configured threshold crosses — moves into `src/store/skipStarRating.ts`.
File-private with one call site; no caller-side changes outside
playerStore's own import.

10 focused tests pin each early-return branch (manual=false, null
track, threshold not crossed, recordSkipStarManualAdvance returning
null, already-rated via override / queue / passed-track) plus the
happy path that calls setRating(1) + the state update for the queue,
currentTrack, and override map. Promise rejections are verified to
be swallowed.

playerStore 3291 → 3263 LOC.
2026-05-12 14:22:38 +02:00
Frank Stellmacher ddead24678 refactor(player): E.11 — extract two playback-coordination helpers (#574)
Two small file-private helpers move into dedicated modules under
src/store/:

- `waveformRefreshGen.ts` — the per-track generation counter that
  guards against applying a stale waveform read after the cache was
  invalidated. Exposes `bumpWaveformRefreshGen` (existing) +
  `getWaveformRefreshGen` (new accessor that replaces the two direct
  reads at `refreshWaveformForTrack`).
- `hotCacheTouch.ts` — `touchHotCacheOnPlayback` with its empty-id
  guards, called from every `audio_play` entry point.

Both file-private; no caller-side changes outside playerStore's own
imports. 8 focused tests pin the generation-increment + isolation
contract and the touch helper's empty-id guards.

playerStore 3302 → 3291 LOC.
2026-05-12 14:14:50 +02:00
Frank Stellmacher 86b13dd4d0 refactor(player): E.10 — extract normalization-IPC deduplicators (#573)
`invokeAudioSetNormalizationDeduped` (450 ms window for
`audio_set_normalization`) and `invokeAudioUpdateReplayGainDeduped`
(250 ms window for `audio_update_replay_gain`, with LUFS-target /
pre-trim implicitly contributing to the dedupe key) move into
`src/store/normalizationIpcDedupe.ts` along with their four
"last-invoked" mutables.

File-private throughout; three internal call sites become plain
imports. 11 focused tests cover the window-boundary behaviour, the
payload-field sensitivity, the engine-mode key contribution
(re-fires when LUFS target changes even with identical gain), and
the null / NaN serialization.

playerStore 3369 → 3302 LOC.
2026-05-12 14:07:44 +02:00
Frank Stellmacher 89bf7e2364 refactor(player): E.9 — extract scheduled pause/resume timer lifecycle (#572)
Two timer mutables (`scheduledPauseTimer`, `scheduledResumeTimer`) plus
the three clear helpers move into `src/store/scheduleTimers.ts`. The
module also gains `schedulePauseTimer(delayMs, onFire)` /
`scheduleResumeTimer(delayMs, onFire)` so callers no longer need to do
the `window.setTimeout(...) as unknown as number` cast or null the
handle inside the fire callback — the module auto-clears its own
reference before invoking the user callback.

`schedulePauseIn` / `scheduleResumeIn` store actions are now four lines
shorter each and don't reach into the timer mutables.

playerStore 3389 → 3369 LOC. 9 focused tests cover schedule + fire +
clear + replace-on-reschedule + independence between the two timers.
2026-05-12 14:01:36 +02:00
Frank Stellmacher 18b88e3ae0 refactor(player): E.8 — extract loudness-gain cache encapsulation (#571)
The two parallel maps (`cachedLoudnessGainByTrackId`,
`stableLoudnessGainByTrackId`) plus their helpers
(`isReplayGainActive`, `loudnessCacheStateKeysForTrackId`,
`clearLoudnessCacheStateForTrackId`, `loudnessGainDbForEngineBind`)
move into `src/store/loudnessGainCache.ts`. The new module exposes a
thin API:

  - `getCachedLoudnessGain` / `setCachedLoudnessGain`
  - `hasStableLoudness` / `markLoudnessStable` (atomic set + stable)
  - `forgetLoudnessGain` (single-key delete) vs
    `clearLoudnessCacheStateForTrackId` (two-form delete)
  - existing names kept for `isReplayGainActive`,
    `loudnessGainDbForEngineBind`, `loudnessCacheStateKeysForTrackId`

playerStore's seven direct-access sites (delete pairs, set-pair, stable
flag check, cached read, neighbour-cache write) become API calls — the
mutables are no longer reachable from outside the module.

All helpers were file-private; no caller-side changes outside
playerStore's own imports. 22 focused tests pin the API surface including
the partial-vs-stable visibility split and the two delete-shape variants.

playerStore 3415 → 3389 LOC.
2026-05-12 13:54:41 +02:00
Frank Stellmacher a1d7cf330d refactor(player): E.7 — extract two small file-private helpers (#570)
`emitNormalizationDebug` (debug-mode trace forwarder, 15+ internal call
sites) and `isInOrbitSession` (Orbit-active guard used by next() and the
async fallback paths to suppress local queue extensions, 5 call sites)
move into dedicated modules under src/store/. Both were file-private —
no caller-side changes outside playerStore's own imports.

playerStore 3434 → 3415 LOC.
2026-05-12 12:35:01 +02:00
Frank Stellmacher 81b161a418 refactor(player): E.6 — extract deriveNormalizationSnapshot into module (#569)
`deriveNormalizationSnapshot` — the loudness / replaygain / off branch
that the runtime uses to compute the normalization fields on every track
switch and queue rewrite — moves into src/store/normalizationSnapshot.ts.
File-private, four internal call sites updated to import from the new
module. Adds 8 focused tests pinning each branch (off, loudness with
target LUFS, replaygain enabled with tag + pre-gain, replaygain enabled
with fallback) plus neighbour-track context for album-mode resolution.

playerStore 3470 → 3434 LOC.
2026-05-12 12:21:51 +02:00
Frank Stellmacher b68bddd034 refactor(player): E.5 — extract playback-URL routing into module (#568)
Three file-private helpers + their shared module-scoped track id move
into src/store/playbackUrlRouting.ts: recordEnginePlayUrl,
playbackSourceHintForResolvedUrl, shouldRebindPlaybackToHotCache. The
`lastOpenedWithHttpTrackId` mutable goes with them — only those three
read it. No external callers, no re-exports needed.

Adds 12 focused tests covering the source-kind classifier
(stream / hot / offline), the rebind decision across stream:-prefix
forms, the empty-serverId / un-recorded edge cases, and the
test-only reset helper.

playerStore 3490 → 3470 LOC.
2026-05-12 12:07:30 +02:00
Frank Stellmacher 5b89051817 refactor(player): E.4 — extract playback-progress pub/sub into module (#567)
The high-frequency PlaybackProgressSnapshot channel — type, mutable
snapshot, listener Set, emit/get/subscribe — moves into a dedicated
src/store/playbackProgress.ts. playerStore re-exports the public 3
(getPlaybackProgressSnapshot, subscribePlaybackProgress, the type) so
the 5+ external callers (PlayerBar, FullscreenPlayer, WaveformSeek,
LyricsPane, MobilePlayerView, TauriEventBridge) keep their existing
imports.

Direct unit tests pin the delta short-circuit (`currentTime <0.005`,
`progress/buffered <0.0002`) that keeps idle CPU bounded. The
end-to-end Tauri-event drive path remains covered by the existing
playerStore.progress characterization test (unchanged).

playerStore 3516 → 3490 LOC.
2026-05-12 11:58:17 +02:00
Frank Stellmacher d24514d67e refactor(player): E.3 — extract waveform/normalization/seek pure helpers (#566)
Three small tranches out of playerStore.ts:
- src/utils/waveformParse.ts — waveformBlobLenOk + coerceWaveformBins (the
  parser that handles number[] / Uint8Array / ArrayLike payloads Rust
  serializes as).
- src/utils/normalizationCompare.ts — normalizationAlmostEqual (tolerant
  null-aware dB comparison).
- src/utils/seekErrors.ts — isRecoverableSeekError (retry classifier for
  the Rust seek pipeline).

Each gets focused unit tests. All four were file-private, no external
callers — pure code move. playerStore 3556 → 3516 LOC.
2026-05-12 11:45:09 +02:00
Frank Stellmacher 1521e4ea8f refactor(player): E.2 — extract queue-undo machinery into queueUndo.ts (#565)
Move the bounded undo/redo stacks, snapshot factory, scroll-top reader
registry, and pending-scroll-top channel into a dedicated module under
src/store/. playerStore re-exports the three public APIs that QueuePanel
and the test harness already imported (registerQueueListScrollTopReader,
consumePendingQueueListScrollTop, _resetQueueUndoStacksForTest), so no
caller-side changes are needed.

The new module adds explicit push/pop accessors so the undo/redo store
actions stop reaching into module-scoped arrays directly. Inline
`pendingQueueListScrollTop = …` writes inside applyQueueHistorySnapshot
become `setPendingQueueListScrollTop(…)` calls — same effect, scoped
through the module.

PlayerState gets the `export` keyword so queueUndo.ts can type its
state-shaped parameters.

playerStore.ts 3618 → 3576 LOC. queueUndo gains a focused test file
covering snapshot deep-cloning, the redo-stack invalidation on a fresh
undo push, max-size enforcement, and the scroll-top channel.

Pre-PR check: PASS.
2026-05-12 11:25:26 +02:00
Frank Stellmacher dcf3dd98e0 refactor(player): E.1 — extract queue-identity helpers to utils/ (#563)
Four pure helpers move out of playerStore: normalizeAnalysisTrackId,
sameQueueTrackId, queuesStructuralEqual, shallowCloneQueueTracks.
Adds focused unit tests for the stream:-prefix normalization and the
no-op detection that prevents unnecessary queue rewrites.

Behaviour preserved verbatim. playerStore 3618 → 3598 LOC.
2026-05-12 11:08:21 +02:00
cucadmuh f0971d5108 docs(contributing): expand contributor guide structure and checks (#564)
Add quick start, repository layout, explicit main vs promotion branches,
Tauri boundary as its own section, security handling, Nix/Cachix and
non-Linux setup notes, lint/format reality (tsc + clippy), i18n file
locations, consolidated hot-path gate wording, and clearer local
coverage reproduction steps. Remove redundant summary block.
2026-05-12 11:08:01 +02:00
cucadmuh 558abba6af docs: add CONTRIBUTING.md for contributors (#562)
Document where to ask questions, local commands that mirror CI, PR
expectations, caution around disruptive UI, stability of the Tauri
Rust-frontend contract, and impact of on-disk settings changes.
Link the guide from the README Development section.
2026-05-12 10:56:00 +02:00
Frank Stellmacher c0f2bc00dd refactor(app): Phase D — move TauriEventBridge into src/app/ (#561)
Final piece of the App.tsx slim-down. The `TauriEventBridge` component
— ZIP download progress, track-preview lifecycle, audio device
changed/reset, the full `cli:*` listener surface (audio-device-set,
instant-mix, library list/set, server list/set, search, player-command),
tray-icon visibility sync, in-app keybindings keydown handler, media
keys + tray actions, `shortcut:global-action` / `shortcut:run-action`,
seek-relative / seek-absolute / set-volume, the window:close-requested
+ app:force-quit flow (with the shared `performExit` Orbit teardown),
and the `psysonic --info` snapshot publisher — moves into
`src/app/TauriEventBridge.tsx`.

`MainApp` imports it from the new file. `App.tsx` is now 57 LOC: just
the `App()` default-export that branches between `MiniPlayerApp` and
`MainApp` after wiring the shared theme / font / track-preview
document attributes.

A.K.A. App.tsx 1453 → 57 LOC over Phase 2 (M0 + B.1 + B.2 + C.1 + C.2
+ D). Pure code move at every step — no behaviour change.

Pre-PR check: PASS (frontend tests, tsc, coverage gates, prod build,
backend tests, clippy, backend coverage gates).
2026-05-12 10:41:28 +02:00
Frank Stellmacher 796c7567ea refactor(app): Phase C.2 — move AppShell into src/app/AppShell.tsx (#560)
Companion to C.1. The full `AppShell` component — the persistent
sidebar / header / route host / queue-resizer / player-bar layout plus
its ~25 effects (tray-tooltip + title sync, Orbit role/phase body marker,
platform attribute, fullscreen tracking, music-folders + rating-support
probe, sidebar persistence, queue drag, WebKitGTK DnD/select-all
blockers, blur/hidden cosmetic-animation pause) — moves into
`src/app/AppShell.tsx` together with its three private helpers
(`readInitialSidebarCollapsed`, `persistSidebarCollapsed`,
`shouldSuppressQueueResizerMouseDown`). `MainApp` now imports `AppShell`
from the new file instead of the App.tsx re-export.

`App.tsx` 1232 → 560 LOC. What's left is the `TauriEventBridge` (~475
LOC, Phase D) plus the ~50-LOC `App()` default-export that splits
between `MiniPlayerApp` and `MainApp`. Imports that were AppShell-only
(Sidebar / PlayerBar / 9 components / 7 hooks / 3 platform helpers /
useOfflineStore / useConnectionStatus / useEqStore / usePerfProbeFlags /
useTranslation / useIsMobile / probeEntityRatingSupport / Suspense /
useCallback / useRef / useState / useLocation / getCurrentWindow's UI
use / ConnectionIndicator / LastfmIndicator / AppUpdater / TitleBar /
OrbitSessionBar / OrbitStartTrigger / useOrbitHost / useOrbitGuest /
cleanupOrphanedOrbitPlaylists / IS_MACOS / IS_WINDOWS / IS_LINUX /
APP_MAIN_SCROLL_VIEWPORT_ID / AppRoutes / lucide icons) all leave with
the component.

No behaviour change — pure code move + import-graph shuffle. Tests
unchanged; the existing AppShell behaviour is already covered indirectly
by the per-component tests it composes.

Pre-PR check: PASS (frontend tests, tsc, coverage gates, prod build,
backend tests, clippy, backend coverage gates).
2026-05-12 10:29:22 +02:00
Frank Stellmacher 2b1ad1542a refactor(app): Phase C.1 — extract AppRoutes + RequireAuth from App.tsx (#559)
Continues the App.tsx slim-down. Two pieces move out of the monolith:

- `src/app/AppRoutes.tsx` — the route table and its 32 lazy page imports.
  AppShell now renders `<AppRoutes />` inside the existing `<Suspense>`;
  the `perfFlags.disableMainRouteContentMount` placeholder stays in
  AppShell because that branch is a layout concern, not a routing one.
  `useIsMobile()` moves inside AppRoutes so the `/now-playing` mobile
  swap stays self-contained.

- `src/app/RequireAuth.tsx` — the 4-line auth guard, with a focused test
  that covers all three reject paths (no login, no active server id,
  empty server list) plus the happy path. MainApp imports it from the
  new file instead of routing through the App.tsx re-export.

Side-cleanup of imports that B.2 had already orphaned in App.tsx
(`version`, `initAudioListeners`, `lazy`, `Routes`, `Route`, `Navigate`,
`MobilePlayerView`).

`App.tsx` 1308 → 1232 LOC. `AppShell` stays in App.tsx for Phase C.2.

Pre-PR check: PASS (frontend tests, tsc, coverage gates, prod build,
backend tests, clippy, backend coverage gates).
2026-05-12 10:13:27 +02: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 6afbdf9c60 chore(test): activate aggregate vitest coverage thresholds (#553)
Replaces 0/0/0/0 placeholders with a measured floor (~1pp under current
state) so the suite blocks regressions across the whole tree. Per-file
hot-path gate keeps doing the heavy lifting on critical files.
2026-05-12 01:00:56 +02:00
Frank Stellmacher b3646daabd test(playerStore): miscellaneous actions push F1 toward the 50% floor (#550)
24 new tests covering the smaller action surfaces F1 / 2a-c skipped:

- setStarredOverride / setUserRatingOverride (per-id maps)
- openContextMenu / closeContextMenu (state + isOpen flip)
- openSongInfo / closeSongInfo (modal state)
- toggleQueue / setQueueVisible (visibility flip with persisted side effect)
- toggleFullscreen (boolean flip)
- setLastfmLoved (writes verbatim + caches under title::artist when track is
  set; does NOT cache without a track) + toggleLastfmLove (no-op without
  track or session-key; flips state + cache otherwise)
- setLastfmLovedForSong (caches under title::artist key)
- setProgress (currentTime + derived progress)
- stop (invokes audio_stop, resets playback bookkeeping)
- shuffleQueue (no-op when queue < 2; deterministic with mocked RNG,
  current track stays at queueIndex 0)
- shuffleUpcomingQueue (no-op when upcoming < 2; head + current untouched,
  upcoming tail shuffled)
- pruneUpcomingToCurrent (drops everything after queueIndex; clears the
  queue entirely when no current track; early return when queue is already
  empty)
- setRadioArtistId (does-not-throw smoke; no public getter for the
  module-level state it writes)

playerStore.ts coverage 40.48% -> 48.02% lines (functions 37.84% -> 50.34%).
Close to but not over the F1 50% line floor — the remaining ~2pp lives in
playTrack's async hot-cache/replay-gain body, which is the same surface PR
2c flagged for a separate follow-up. Not adding playerStore.ts to the gate
yet; staying out one more PR to see the number stabilise.

Frontend suite: 451 -> 475 tests (+24).
2026-05-11 23:48:25 +02:00
Frank Stellmacher 568f3aeb7d test(api): subsonic.ts async endpoint contracts (F3 follow-up) (#549)
39 new tests targeting the response normalization paths the F3 PR (#544)
deferred. Mocks axios at the module boundary; pins:

- api() helper envelope: unwrap subsonic-response on status=ok, throw
  "Invalid response" without envelope, throw the server message on
  status=failed, throw a generic on failed-without-message, propagate
  network failures.
- song-array vs single-object normalization paths:
  - getMusicDirectory normalizes child (object -> [object]), empty -> [].
  - getMusicIndexes flattens index -> artist arrays (object or array).
  - getMusicFolders coerces numeric ids to strings + defaults name.
  - getRandomSongs pass-through behaviour pinned (no normalization --
    Navidrome always returns the array form).
- collection-shape contracts: getAlbum splits { album, songs } + empty
  fallback when album.song is absent, getStarred returns empty arrays
  on missing starred2 / missing fields / pass-through arrays.
- single endpoint behaviours: getSong null on failure, getTopSongs []
  + slice to 5, getArtists flatten + empty, search whitespace-query
  short-circuit (no HTTP), getAlbumInfo2 null on error, ping
  true/false based on status.
- pingWithCredentials (explicit-URL path): full response (type +
  serverVersion + openSubsonic), http:// prepend when scheme missing,
  trailing-slash strip before /rest/ping.view, ok=false on any
  failure / status=failed, openSubsonic defaults to false when omitted.

subsonic.ts coverage 12.66% -> 31.87% lines (+19pp). The remaining
surface lives in niche endpoints (playlist mutations, statistics
overview/aggregates, internet radio CRUD, cover-art uploads, ratings
prefetch). Not gate-eligible yet; a follow-up could push to ~60% but
diminishing returns relative to other backlog items.

Frontend suite: 412 -> 451 tests (+39).
2026-05-11 23:41:08 +02:00
Frank Stellmacher 377675ae94 test(ui): MiniPlayer + FullscreenPlayer (§4.5 regression) (Phase F5c) (#548)
MiniPlayer.test.tsx (4): mounts without throwing, renders the
always-present titlebar controls (Pin + Open main window — Close is
Linux-only and lives on the manual smoke list per pick 4a), click on
Open main window / Close does not throw, clicking the Pin button
flips the alwaysOnTop label between "Unpin" and "Pin on top". Bridge
contract (mini:ready / mini:sync, geometry persistence) deferred to
B-tier phase B5 -- jsdom does not model two webviews.

FullscreenPlayer.test.tsx (9): renders the labelled Fullscreen Player
dialog + Close Fullscreen control. Control wiring: Close calls
onClose, Stop calls stop, Previous calls previous, Next calls next,
Repeat cycles via toggleRepeat.

§4.5 of the v2 plan -- useCachedUrl(coverUrl, coverKey, false)
regression. Mocks the CachedImage module so the call args are
observable. Pins:
  - the 500 px cover-art call passes opt=false (no fetchUrl fallback;
    prevents double crossfade fetchUrl -> blobUrl);
  - the 300 px art-box call passes opt=true (default behaviour).
A refactor that "tidies up" the useCachedUrl call sites would silently
regress the FS player cover; this test makes it loud.

Harness fix: vi.mock for @tauri-apps/api/event now returns an async
emit that resolves -- components chain .catch() on emit which crashed
on the bare vi.fn() return value during first-render useEffect.
Benefits any future component test that mounts something using emit.

Frontend suite: 399 -> 412 tests (+13). F5 (and Phases F0-F6) complete.
2026-05-11 23:24:40 +02:00
Frank Stellmacher 2c38db6ea6 test(ui): QueuePanel (§4.4 DnD regression) + PlayerBar (Phase F5b) (#547)
QueuePanel.test.tsx (8): empty-queue affordance, one row per queue track
with matching data-queue-idx, track titles render. Toolbar exposes
Shuffle queue / Save Playlist / Load Playlist / Copy queue share link /
Clear via aria-label; Shuffle is disabled when the queue has fewer than
2 tracks.

§4.4 of the v2 plan -- DnD architecture pin. Queue rows do NOT declare
draggable=true (no HTML5 native drag); the source file has no
dataTransfer.setData / dataTransfer.getData / onDragStart / onDrop JSX
usage; no application/json MIME anywhere. The project's psy-drop custom
event system sidesteps WebView2's text/plain-only restriction by
avoiding HTML5 DnD entirely -- a refactor that re-introduces native DnD
on the queue would silently break Windows.

PlayerBar.test.tsx (9): renders the labelled "Music Player" region.
Surfaces Previous Track / Play / Next Track / Repeat / Stop when a
track is loaded. The middle control flips between "Play" and "Pause"
based on isPlaying. Control wiring: clicking Play/Pause calls
togglePlay, Previous calls previous, Next calls next, Repeat cycles
off -> all -> one, Stop calls stop. The region landmark is still
rendered when no track is loaded.

Adds a generic scrollIntoView no-op stub in src/test/mocks/browser.ts --
jsdom does not implement it and QueuePanel's queueAutoScroll calls it
on mount with auto-advance enabled. Benefits any future component test
that touches scroll affordances.

Frontend suite: 382 -> 399 tests (+17).
2026-05-11 23:16:08 +02:00
Frank Stellmacher fae615fdb8 test(ui): ContextMenu + WaveformSeek behaviour pins (Phase F5a) (#546)
ContextMenu.test.tsx (11): renders nothing when closed, renders when
openContextMenu has run, closeContextMenu hides on next render. Song-type
shows Play Now / Play Next / Add to Queue; album-type shows Open Album
/ Play Next / Enqueue Album / Go to Artist; artist-type shows Start
Radio + share affordances; queue-item shows a Remove option the song
menu does not. Clicking an action calls the expected store method
(playNext, enqueue) and closes the menu. Escape on the menu closes it.

WaveformSeek.test.tsx (8): renders a canvas, cursor=default without
trackId (no-track-loaded affordance), cursor=pointer with a trackId.
Wheel guards: no seek without a trackId, no seek with duration=0. Wheel
commit wiring: 350 ms trailing debounce delays the seek call until
activity settles; rapid wheel events coalesce (fewer commits than
events). Mount + unmount completes without throwing.

Neither component joins the hot-path gate -- jsdom skips canvas drawing
and these files have large branch surfaces (ContextMenu has 13 menu
types, WaveformSeek has the animation loop + 11 seekbar styles) that
need behavioural smoke rather than line coverage. The tests cover the
contract the refactor must preserve; visual / interactive layers stay
on the manual smoke list.

Frontend suite: 363 -> 382 tests (+19).
2026-05-11 23:07:58 +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 ae23bf61eb test(authStore): characterize login + servers + persistence + settings (Phase F2) (#543)
login.test.ts: composed addServer -> setActiveServer -> setLoggedIn flow,
failed-login leaves prior state intact, addServer assigns unique ids,
setConnecting / setConnectionError independence, logout clears
isLoggedIn + musicFolders but keeps server entry, Last.fm session
(setLastfm / connectLastfm / disconnectLastfm contracts).

servers.test.ts: addServer / updateServer (patch by id, no-op on unknown),
setActiveServer (clears musicFolders), removeServer (non-active no-effect,
active picks newServers[0] fallback, last server -> null + isLoggedIn
false, cleans per-server bookkeeping maps), getActiveServer / getBaseUrl
selectors. Includes the gapless / crossfade mutex regression test from
the v2 plan section 4.3 -- callers clear the other flag before setting,
the setters themselves do NOT auto-clear (contract pin).

persistence.test.ts: hydration loads existing localStorage shape, defaults
missing fields, preserves saved values verbatim. Robust to corrupt JSON
and missing top-level state. onRehydrate migrations: clears conflicting
hotCacheEnabled + preloadMode!=off legacy combo, keeps hotCache when
preload was already off, migrates legacy waveform seekbarStyle to truewave,
strips removed animationMode / reducedAnimations fields. partialize strips
musicFolders. Includes the synchronous-storage invariant regression from
the v2 plan section 2 (CLAUDE.md gotcha) -- getActiveServer is visible in
the same tick after addServer + setActiveServer with no await.

settings.test.ts: API-pin sweep across 22 trivial setters via it.each
(rename-resistant), focused tests for setters with logic (clamping in
setTrackPreviewStartRatio / setTrackPreviewDurationSec / setRandomMixSize,
boolean coercion in setTrackPreviewsEnabled, finite-number guard in
setLoudnessPreAnalysisAttenuationDb, default reset in
resetLoudnessPreAnalysisAttenuationDbDefault), per-server bookkeeping
contracts (setEntityRatingSupport / setAudiomuseNavidromeEnabled
positive-opt-in semantics), enum-value setters
(setPreloadMode / setDiscordCoverSource / setLoggingMode / setReplayGainMode /
setNormalizationEngine / setLyricsMode), genre blacklist + audio output
device replacement.

authStore.ts coverage 45.37% -> 79.29% lines (target was 60%). authStore.ts
not yet added to the hot-path gate -- want to see it stable across a few
real PRs first per the gate's curation rule.
2026-05-11 22:30:45 +02:00
Frank Stellmacher 8569a17797 test(playerStore): progress snapshot + persistence flush (Phase F1 / PR 2c) (#542)
progress.test.ts: getPlaybackProgressSnapshot shape + post-emit reflection,
subscribePlaybackProgress (notify, (next, prev) pair, near-duplicate epsilon
coalesce at 0.005 s, unsub stops notifications, multiple subscribers
independent), live-emit throttling guard (drops within 1500 ms + < 0.9 s
delta; large delta passes; time threshold passes).

persistence.test.ts: flushPlayQueuePosition forwards (ids, currentId, posMs)
to savePlayQueue, caps song-id list at 1000, no-ops on radio / no-track /
empty queue, swallows backend errors, floors position to whole ms.

playerStore.ts coverage 39.55% -> 40.48%. F1 50% floor not met -- remaining
~10pp lives in playTrack's async hot-cache/replay-gain body, shuffleQueue,
stop, enqueueRadio, initializeFromServerQueue and the orbit auto-merge
paths. Either a follow-up PR 2d or a revised F1 floor; flagged in the PR
body. Gate unchanged -- playerStore.ts stays out until the floor is met.

Discovered + fixed during this PR: the spread ...await vi.importActual()
mock pattern lets the real savePlayQueue leak through to playerStore.ts's
relative import (../api/subsonic) even when the alias-form is mocked.
Switched persistence.test.ts to an explicit non-spread mock map listing
every export the store uses.
2026-05-11 22:14:57 +02:00
Frank Stellmacher 4a18e15489 test(playerStore): playback actions + audio event handlers (Phase F1 / PR 2b) (#541)
playbackActions.test.ts: pause (invoke + failed-invoke controlled), resume
(warm path, no-track guard), togglePlay (both branches), seek (clamp to
dur-0.25, 100 ms debounce, coalesce rapid drags, no-op guards), next
(advance, repeat=all wrap, repeat=off audio_stop + reset), previous
(>3 s restart, jump-back, queueIndex=0 no-op), toggleRepeat cycle.

events.test.ts: audio:progress (commit on active transport, drop without
track / paused, duration=0 falls back to track.duration), audio:track_switched
(advance, repeat=one pin, repeat=all wrap, end+off no-op, scrobbled+
lastfmLoved reset), audio:ended (immediate playback reset, radio path
clears currentRadio without queue advance). 4 listener-lifecycle regression
tests cover section 4.2 of the pre-refactor testing plan v2 -- cleanup
actually unsubs; re-init keeps count=1; double-init without cleanup stacks
(contract pin so a refactor that drops the cleanup return value fails loudly).

playerStore.ts coverage 18.1% -> 39.55% lines. PR 2c (progress snapshot +
persistence flush) pushes past the F1 50% floor.
2026-05-11 21:56:24 +02:00