Commit Graph

1436 Commits

Author SHA1 Message Date
Frank Stellmacher 7e902b918c refactor(player): E.39 — extract resume action (#603)
Move the ~165-LOC `resume` action body into `runResume(set, get)`
in `src/store/resumeAction.ts`, following the helper-with-thin-wrapper
pattern from E.37 + E.38.

Covers all three resume branches:
- Orbit guest catch-up to host's live position (same-track → seek;
  different-track → playTrack + deferred seek).
- Radio resume via HTML5 audio.
- Regular track resume: warm engine (audio_resume) or cold start
  (hot-cache promote → getSong refetch → audio_play → seek to
  persisted currentTime, with currentTrack fallback on fetch fail).

Pure code-move. playerStore.ts: 868 → 702 LOC (−166).
2026-05-12 21:46:20 +02:00
Frank Stellmacher 0aadae061f refactor(player): E.38 — extract seek action (#602)
Move the ~63-LOC `seek` action body into `runSeek(set, get, progress)`
in `src/store/seekAction.ts`, following the helper-with-thin-wrapper
pattern from E.37 (updateReplayGain).

The action handles the full seek path: 0..1 fraction → bounded time,
100 ms debounce, hot-cache-rebind branch via playTrack, and the
recoverable-seek-error retry burst (visual target pin + restart on
"not seekable" + bounded retry window).

Pure code-move. playerStore.ts: 938 → 868 LOC (−70).
2026-05-12 21:38:03 +02:00
Frank Stellmacher 14346d1482 refactor(player): E.37 — extract updateReplayGainForCurrentTrack (#601)
Move the ~50-LOC `updateReplayGainForCurrentTrack` action body into
`runUpdateReplayGainForCurrentTrack(set, get)` in a dedicated module,
following the helper-with-thin-wrapper pattern from
`applyQueueHistorySnapshot` (E.30) rather than a single-action
factory.

The action recomputes the normalization snapshot + pushes fresh
ReplayGain/loudness state to the engine when mode toggles change
or the loudness cache fills mid-playback.

Pure code-move. playerStore.ts: 991 → 938 LOC (−53).
2026-05-12 21:14:24 +02:00
Frank Stellmacher 55b2b12fa5 refactor(player): E.36 — extract schedule-pause/resume factory (#600)
Four scheduled-timer actions extracted into `createScheduleActions`
(`src/store/scheduleActions.ts`):

- `schedulePauseIn` / `scheduleResumeIn` — clamp the delay to ≥ 500 ms,
  store absolute target + start timestamps (for the countdown UI),
  and arm a single-shot timer.
- `clearScheduledPause` / `clearScheduledResume` — cancel the timer
  and blank the timestamps.

Pure code-move. playerStore.ts: 1030 → 991 LOC (−39, first sub-1000
state since Phase E started).
2026-05-12 21:06:48 +02:00
Frank Stellmacher 1e2c651196 refactor(player): E.35 — extract misc-actions factory (#599)
Heterogeneous "misc" cluster — seven small-to-medium actions that
didn't fit the more focused factories (transport / queue / Last.fm /
UI state):

- `playRadio` — switches the player into HTML5 radio mode.
- `previous` — Subsonic-style back: restart if past 3 s, otherwise
  jump to the previous queue index.
- `setVolume` — clamps + propagates to Rust engine and radio sink.
- `setProgress` — pure UI state update for progress polling.
- `initializeFromServerQueue` — startup queue restore from Navidrome.
- `reanalyzeLoudnessForTrack` — toast + reseed the loudness cache.
- `reseedQueueForInstantMix` — replace the queue with a single track.

Pure code-move. playerStore.ts: 1167 → 1030 LOC (−137).
2026-05-12 21:01:12 +02:00
Frank Stellmacher 76fc3bb9c9 refactor(player): E.34 — extract transport-light + undo/redo factories (#598)
Two small action-factory extractions in one PR, both following the
pattern from E.31–E.33.

- `createTransportLightActions` — `stop`, `pause`, `resetAudioPause`,
  `togglePlay`. Everything in the pause/togglePlay cluster except
  `resume` (~165 LOC, deferred to its own PR).
- `createUndoRedoActions` — `undoLastQueueEdit`, `redoLastQueueEdit`.
  Trivial wrappers around `applyQueueHistorySnapshot` + the queue-undo
  stack helpers.

Pure code-move. playerStore.ts: 1247 → 1167 LOC (−80).
2026-05-12 20:52:22 +02:00
Frank Stellmacher 168d5905c2 refactor(player): E.33 — extract queue mutation actions as factory (#597)
Move all eleven queue-mutation actions (enqueue, enqueueAt, playNext,
enqueueRadio, setRadioArtistId, pruneUpcomingToCurrent, clearQueue,
reorderQueue, shuffleQueue, shuffleUpcomingQueue, removeTrack) from
the playerStore create() body into a new `createQueueMutationActions`
factory, following the action-factory pattern established in E.31
(Last.fm) + E.32 (UI state).

Pure code-move: existing characterization tests in
playerStore.queue.test.ts continue to exercise the actions through
the full store flow.

playerStore.ts: 1463 → 1247 LOC (−216).
2026-05-12 20:40:04 +02:00
Frank Stellmacher 0c2aa993f2 refactor(player): E.32 — extract UI state actions as factory (#596)
Ten pure-UI state setters move into `src/store/uiStateActions.ts` as a
`createUiStateActions(set)` factory:

  - `setStarredOverride`, `setUserRatingOverride` — optimistic overrides
  - `openContextMenu`, `closeContextMenu` — context menu modal
  - `openSongInfo`, `closeSongInfo` — song info modal
  - `toggleQueue`, `setQueueVisible` — queue panel toggle with persisted
    localStorage round-trip
  - `toggleFullscreen` — fullscreen player toggle
  - `toggleRepeat` — repeat mode cycle

All ten are pure state mutators (no audio engine / network calls).
Store body uses `...createUiStateActions(set)`. Action-factory pattern
established by E.31 reused here. `persistQueueVisibility` import drops
from playerStore.

playerStore 1504 → 1463 LOC.
2026-05-12 20:25:21 +02:00
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