mirror of
https://github.com/Psychotoxical/psysonic.git
synced 2026-07-21 14:55:43 +00:00
1a82376f8c
* feat(music-network): core domain types and wire contracts
Foundation for the Music Network framework: provider-agnostic domain
types, capability model, typed errors, and account shapes under
src/music-network/core, plus the ScrobbleWire / EnrichmentWire /
PresetManifest / AuthStrategy contracts. No runtime wiring yet.
* feat(music-network): generic audioscrobbler/listenbrainz/maloja transports
Generalize the Rust remote layer for the Music Network framework. Add
provider-agnostic transports parameterized by base_url:
- audioscrobbler_request: Audioscrobbler v2 with caller-supplied endpoint
(Last.fm, Libre.fm, Rocksky, custom GNU FM, Maloja compat share it)
- listenbrainz_request: Token-header JSON (direct + Maloja LB compat)
- maloja_request: native /apis/mlj_1 JSON
lastfm_request stays as a thin transition delegate against the fixed
host; it is removed once the framework owns all call sites. Wiremock
tests cover audioscrobbler_request with a custom base_url and API-error
mapping.
* feat(music-network): audioscrobbler wire with last.fm + libre.fm presets
Add the Audioscrobbler v2 wire, the behavioural successor to the legacy
src/api/lastfm.ts, implementing the full EnrichmentWire surface (scrobble,
now playing, love/unlove, loved sync, similar artists, track/artist stats,
top lists, recent tracks, user profile, urls).
- client.ts: transport wrapper over audioscrobbler_request, classifying
failures into MusicNetworkError without touching any store
- sign.ts: TS mirror of the api_sig base-string ordering rule (unit-tested)
- auth/tokenPoll.ts: browser token-poll connect flow as a reusable strategy
- presets/lastfm.ts, presets/librefm.ts: bundled, enrichment-capable,
token-poll presets (both endpoints verified live)
Extends WireContext with profileBase and ConnectContext with authBase so
URL builders and connect flows need no preset lookup.
* feat(music-network): listenbrainz + maloja-native wires, paste-auth presets
Add the scrobble-destination wires and presets:
- ListenBrainz wire (scrobble + now playing via playing_now), backing both
the direct api.listenbrainz.org preset and the Maloja /apis/listenbrainz
compat preset (one wire, two presets, differing only by base URL)
- Maloja native wire (/apis/mlj_1/newscrobble, scrobble only — Maloja has
no now-playing endpoint)
- Shared api_key_only paste-auth strategy (token/key/session-key paste);
the Audioscrobbler wire now dispatches token-poll vs paste by preset
- Presets: listenbrainz, maloja_listenbrainz, maloja_native, rocksky
(scrobble-only, session-key paste, bundled keys — verified live), and
custom_gnufm (token-poll, user-supplied url/key/secret)
- Contracts: ConnectContext.authStrategy, PresetManifest.selfHostedApiSuffix
maloja_compat (the {url}/apis/audioscrobbler mode) is intentionally omitted:
its protocol cannot be verified and is almost certainly the legacy handshake,
not the 2.0 web API; Maloja is covered by the native and ListenBrainz modes.
* feat(music-network): registry, orchestrator, enrichment router + runtime facade
Wire the framework together behind a single facade:
- registry: wireRegistry (WireId -> wire), presetRegistry (the 7 built-in
presets), registerBuiltinWires (one-time side-effect registration)
- CapabilityProbe: wire probe overlaid by manifest staticCapabilities as the
final authority (lets two presets on one wire diverge, e.g. Rocksky's
nowPlaying:false over the Audioscrobbler wire's optimistic yes)
- ScrobbleOrchestrator: best-effort fan-out; flips the per-account
session-error flag on AUTH_SESSION_INVALID and clears it on next success
- EnrichmentRouter: resolves the single primary to its EnrichmentWire; the
type guard rejects non-enrichment wires (Maloja/ListenBrainz)
- MusicNetworkRuntime: the only app entry point — accounts, roles, fan-out,
enrichment, urls, probe. Reads/writes state through the MusicNetworkStore
port (Phase 5 backs it with the auth store) and a RuntimeHost for side effects
- getMusicNetworkRuntime singleton + index.ts public barrel
Tests cover fan-out, master toggle, capability gating, session-error
flip/clear, primary eligibility, and enrichment routing.
* feat(music-network): auth-store state + lossless legacy migration + runtime bridge
Add the persisted Music Network state to the auth store and wire the runtime,
all additively — nothing existing breaks yet.
- authStoreTypes: musicNetworkAccounts / enrichmentPrimaryId /
scrobblingMasterEnabled + actions; legacy lastfm* fields kept until Phase 6
- authMusicNetworkActions + defaults/wiring (synchronous localStorage)
- accountPersistence: migrateLegacyLastfm (lossless — preserves session key,
username and scrobbling preference; fills bundled Last.fm key from the preset;
sets the migrated account as enrichment primary) + sanitizeAccounts
- authStoreRehydrate: one-shot migration guarded by a sentinel so a later
disconnect cannot resurrect the account from still-present legacy fields
- musicNetworkBridge: backs the MusicNetworkStore port with the auth store and
the RuntimeHost with the Tauri shell; initialized in pre-React bootstrap
nowPlayingEnabled stays a global toggle (not a lastfm* field); the Phase 6
playback call-site will gate dispatchNowPlaying on it, preserving behaviour.
* feat(music-network): route playback, enrichment and love through the runtime
Migrate every Last.fm call-site onto the Music Network runtime, preserving
behaviour:
- playback (audioEventHandlers, playTrackAction): scrobble@50% and now-playing
via dispatchScrobble/dispatchNowPlaying; loved-fetch via isTrackLoved. Now-
playing follows scrobbling (as Last.fm did), Navidrome now-playing keeps the
nowPlayingEnabled gate
- enrichment: useArtistSimilarArtists, useNowPlayingFetchers, Statistics, and
the ArtistDetail similar-artists gate now use the runtime, gated on an
enrichment primary
- love: PlayerBar, PlayerTrackInfo, all context menus, useNowPlayingStarLove and
the startup loved-sync route through setTrackLoved / toggleNetworkLove
- player store: lastfmLoved/lastfmLovedCache -> networkLoved/networkLovedCache;
lastfmActions -> networkLoveActions; loved cache storage renamed with a
lossless legacy-key fallback
- getMusicNetworkRuntimeOrNull() for best-effort callers so they no-op (not
throw) before the runtime is initialized
src/api/lastfm.ts and the Integrations UI still use the legacy path; they are
migrated and removed in the next phase.
* feat(music-network): manifest-driven Integrations UI + scrobble batch format
Replace the Last.fm Integrations card with a manifest-driven Music Network
section, and fix Audioscrobbler scrobbling to the batch/array shape.
- settings/musicNetwork/: MusicNetworkSection (master toggle, destination
cards, enrichment-primary picker, Maloja proxy warning, add-a-service list)
driven entirely off the preset registry; icon map from PresetManifest.icon
- IntegrationsTab delegates to MusicNetworkSection (Discord/Bandsintown/
Navidrome now-playing unchanged)
- i18n: musicNetwork.* across all 9 locales, incl. a per-field help hint for
Rocksky's CLI session-key flow (rocksky login)
- scrobble now uses the documented array form (artist[0]/track[0]/…); the bare
single form is only tolerated by Last.fm, Rocksky requires the indexed form
- auth-error detection keys off the response message (not the ambiguous numeric
code) so a Rocksky server-500 no longer flips the account to a reconnect state
- PresetManifest.PresetField gains an optional helpKey
Rocksky's server rejects some non-ASCII track metadata with a 500 — a Rocksky
backend bug; the client call is correct (verified).
* fix(music-network): clearer Integrations layout + scrobble batch fix
Address UI feedback on the Music Network section:
- per-account scrobble toggle moves inside its account block (was a loose
row between cards — unclear which account it belonged to)
- master toggle and the primary-service picker are now boxed blocks at the top,
not bare rows
- primary-service copy reworked: 'Primary service' + a line spelling out that
liked tracks/similar artists/stats come from it while scrobbling still goes
to all enabled services
- distinct zones separated by dividers (master/primary · connected · add)
Also folds in the verified scrobble fixes: documented array form
(artist[0]/track[0]/…) so Rocksky accepts scrobbles, and auth-error detection
by message rather than the ambiguous numeric code (a Rocksky server-500 no
longer flips the account to a reconnect state). Rocksky session-key field gains
a CLI help hint (rocksky login), all 9 locales.
* feat(music-network): indicator + remove legacy lastfm path
Phase 7b/7c — finish the cutover and delete the old Last.fm path.
- LastfmIndicator -> MusicNetworkIndicator (shows the enrichment primary's
status, click -> Integrations)
- delete src/api/lastfm.ts; remove Rust lastfm_request (remote.rs + lib.rs)
- remove legacy authStore lastfm* fields, actions and types; delete
authLastfmActions.ts; rehydrate migration reads the legacy blob via a cast
- migrate the remaining NowPlaying call-sites (NowPlaying.tsx + the now-playing
fetchers/prewarm/star-love hooks) off lastfmSessionKey/lastfmUsername onto the
enrichment primary (gate + cache key)
- type imports LastfmTrackInfo/LastfmArtistStats -> music-network TrackStats/
ArtistStats; drop 8 stale api/lastfm test mocks and the obsolete Last.fm auth
tests; update settingsTabs + src/CLAUDE.md
No lastfm imports remain outside src/music-network/; lastfm_request removed
(acceptance §12). tsc clean, 1947 frontend tests + remote rust tests green.
* test(music-network): cover scrobble shape + error classification, drop dead i18n keys
Remove the 14 unused legacy scrobble/connection i18n keys across all 9
locales (settings.lfm*/scrobble*, connection.lastfm*); the live love,
profile-link and now-playing keys stay.
Add regression tests for the parity-critical transport logic: the indexed
batch/array scrobble body, the auth-vs-network error classification
(numeric codes collide across providers), and the manifest-overrides-probe
capability merge.
* feat(music-network): provider-agnostic UI + Maloja Audioscrobbler & Koito presets
- de-hardcode the single provider name across every enrichment surface
(love labels, now-playing badge, stats title); derive it from the
enrichment primary and interpolate via {{provider}} i18n params
- surface a toast when a paste-auth connect probe fails — a static
'supported' capability flag no longer masks a runtime probe error
- add the Maloja Audioscrobbler (GNU FM) preset (the third Maloja wire
mode) and a Koito preset (ListenBrainz-compatible), both data-only
- generalise PRIVACY.md and the scrobbling help entry to the framework
- rename residual lfm* identifiers to network*; strip legacy flat
lastfm* fields from the persisted blob; neutral transport error prefix
- tests: error classification, scrobble body, capability probe, registry
* fix(music-network): validate paste-auth keys on connect + UI polish
- AudioscrobblerWire.probe now validates an api_key_only session with a
signed call and reports scrobble:'error' only on a genuine auth failure
(a scrobble-only service that rejects user.getInfo is not a bad key), so
an invalid Maloja Audioscrobbler / Rocksky key surfaces a connect toast
instead of failing silently; WireContext carries the preset authStrategy
- drop the unreachable Statistics empty-state branch and its dead
lfmNotConnected i18n key; use the useEnrichmentPrimaryLabel hook there
- drive the love-button glyph from the enrichment primary's manifest icon;
neutral Music Network section icon; remove a dead LastfmIcon import
- tests: paste-auth vs token-poll probe behaviour
* chore(music-network): rename showLastfmSimilar → showNetworkSimilar, refresh stale comments
Post-parity polish: the similar-artists toggle now sources from the generic
enrichment runtime, so rename the lingering lastfm-flavoured identifier; drop
stale 'Mirrors today's LastfmX' doc comments referencing the removed legacy
types, and generalise the scrobble-point comment.
* docs(changelog): Music Network entry (PR #1066)
Co-Authored-By: cucadmuh <49571317+cucadmuh@users.noreply.github.com>
* fix(music-network): bound request timeout on the provider transports
audioscrobbler_request / listenbrainz_request / maloja_request built a
reqwest client with no timeout, so a hung provider left scrobble / probe /
loved-sync promises unresolved. Add a shared provider_http_client() with a
15s timeout, matching the sibling fetch_* commands. Addresses review C3.
* refactor(music-network): dedupe wire transport + no-enrichment helpers
The three provider clients repeated the same invoke -> classify-error ->
MusicNetworkError boilerplate, and the three probe() bodies repeated the
"mark every enrichment capability no" loop. Extract
wires/shared/invokeTransport() (each wire keeps its own arg shape + auth
rule) and markNoEnrichment() in core/capabilities.ts. Addresses review C4.
* refactor(music-network): drop write-only malojaWireMode dead state
malojaWireMode was written on connect but never read — the wire is resolved
by wireId and the Maloja base URL by the preset's selfHostedApiSuffix.
Remove the field, the MalojaWireMode type, the malojaWireModeFor helper,
the AccountPatch entry, the PresetField union member, and the export.
Addresses review C1.
* refactor(music-network): one useEnrichmentPrimary hook, drop lastfm fallback
The enrichment-primary lookup (accounts.find by enrichmentPrimaryId) was
duplicated across two hooks and inlined in the indicator and both
context-menu builders, two of them with a hardcoded 'lastfm' icon fallback.
Add one music-network/ui/useEnrichmentPrimary() returning
{account,label,icon}|null; useEnrichmentPrimaryLabel/Icon delegate to it and
the indicator + context menus consume it directly. Icon fallback is the
neutral 'custom' glyph, never a provider (provider-agnostic, §7.3).
Addresses review C2.
---------
Co-authored-by: cucadmuh <49571317+cucadmuh@users.noreply.github.com>
261 lines
12 KiB
TypeScript
261 lines
12 KiB
TypeScript
/**
|
|
* Regression tests for the id-gating tuple pattern in `useNowPlayingFetchers`.
|
|
*
|
|
* Each id-keyed slot (`artistInfo`, `songMeta`, `albumData`, `discography`) is
|
|
* held as a `{ id, value }` tuple internally and gated on id-match at the
|
|
* return statement. This guarantees that consumers building a `cacheKey` from
|
|
* the current id can never receive a value paired with a previously-current
|
|
* id — the bug that PR #732 fixed inside `NowPlayingInfo.tsx` and that this
|
|
* hook would otherwise leak into every other consumer (e.g. ArtistCard on the
|
|
* NowPlaying page).
|
|
*/
|
|
import { renderHook, act, waitFor } from '@testing-library/react';
|
|
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
import type { SubsonicArtistInfo, SubsonicSong, SubsonicAlbum } from '../api/subsonicTypes';
|
|
|
|
vi.mock('../api/subsonicArtists');
|
|
vi.mock('../api/subsonicLibrary');
|
|
vi.mock('../api/bandsintown');
|
|
vi.mock('../utils/network/subsonicNetworkGuard', () => ({
|
|
shouldAttemptSubsonicForServer: vi.fn(() => true),
|
|
}));
|
|
|
|
import { shouldAttemptSubsonicForServer } from '../utils/network/subsonicNetworkGuard';
|
|
import { getArtistForServer, getArtistInfoForServer, getTopSongsForServer } from '../api/subsonicArtists';
|
|
import { getAlbumForServer, getSongForServer } from '../api/subsonicLibrary';
|
|
import { fetchBandsintownEvents } from '../api/bandsintown';
|
|
import { useNowPlayingFetchers, type NowPlayingFetchersDeps } from './useNowPlayingFetchers';
|
|
|
|
// The real getArtistInfo signature returns `Promise<SubsonicArtistInfo>`, but
|
|
// the hook treats `null` as the "no info available" case and stores it as
|
|
// such in its tuple. The tests mirror that — cast to a nullable-returning
|
|
// shape so we can mock the empty case without `as any` at every site.
|
|
const mockArtistInfo = vi.mocked(getArtistInfoForServer) as unknown as {
|
|
mockImplementation: (impl: (serverId: string, id: string) => Promise<SubsonicArtistInfo | null>) => void;
|
|
mockResolvedValue: (v: SubsonicArtistInfo | null) => void;
|
|
};
|
|
|
|
const baseDeps: NowPlayingFetchersDeps = {
|
|
songId: undefined,
|
|
artistId: undefined,
|
|
albumId: undefined,
|
|
artistName: '',
|
|
enableBandsintown: false,
|
|
audiomuseNavidromeEnabled: false,
|
|
enrichmentKey: '',
|
|
currentTrack: null,
|
|
subsonicServerId: 'srv1',
|
|
fetchEnabled: true,
|
|
};
|
|
|
|
beforeEach(() => {
|
|
vi.mocked(getTopSongsForServer).mockResolvedValue([]);
|
|
vi.mocked(getArtistForServer).mockResolvedValue({ albums: [] } as any);
|
|
vi.mocked(fetchBandsintownEvents).mockResolvedValue([]);
|
|
});
|
|
|
|
afterEach(() => {
|
|
vi.clearAllMocks();
|
|
});
|
|
|
|
/** Deferred promise helper — lets a test step the fetch resolution manually. */
|
|
function deferred<T>() {
|
|
let resolve!: (v: T) => void;
|
|
let reject!: (e?: unknown) => void;
|
|
const promise = new Promise<T>((res, rej) => { resolve = res; reject = rej; });
|
|
return { promise, resolve, reject };
|
|
}
|
|
|
|
describe('useNowPlayingFetchers — id-gated artistInfo', () => {
|
|
it('returns null artistInfo while the previously-resolved info belongs to a different artistId', async () => {
|
|
const a = deferred<SubsonicArtistInfo | null>();
|
|
const b = deferred<SubsonicArtistInfo | null>();
|
|
mockArtistInfo.mockImplementation(async (_sid, id) => {
|
|
if (id === 'art-A') return a.promise;
|
|
if (id === 'art-B') return b.promise;
|
|
return null;
|
|
});
|
|
|
|
const { result, rerender } = renderHook(
|
|
({ artistId }: { artistId: string }) =>
|
|
useNowPlayingFetchers({ ...baseDeps, artistId, artistName: artistId }),
|
|
{ initialProps: { artistId: 'art-A' } },
|
|
);
|
|
|
|
// Before any resolve, no info yet.
|
|
expect(result.current.artistInfo).toBeNull();
|
|
|
|
// Resolve A — artistInfo becomes A's info.
|
|
await act(async () => { a.resolve({ largeImageUrl: 'A.jpg' } as SubsonicArtistInfo); });
|
|
await waitFor(() => {
|
|
expect(result.current.artistInfo).toEqual({ largeImageUrl: 'A.jpg' });
|
|
});
|
|
|
|
// Switch to artistId B. Without id-gating, artistInfo would still be A's
|
|
// info paired with the new B id — the bug that PR #732 fixed in the queue
|
|
// info panel. With gating, artistInfo flips to null immediately.
|
|
rerender({ artistId: 'art-B' });
|
|
expect(result.current.artistInfo).toBeNull();
|
|
|
|
// Resolve B — artistInfo now becomes B's info, never paired with A.
|
|
await act(async () => { b.resolve({ largeImageUrl: 'B.jpg' } as SubsonicArtistInfo); });
|
|
await waitFor(() => {
|
|
expect(result.current.artistInfo).toEqual({ largeImageUrl: 'B.jpg' });
|
|
});
|
|
});
|
|
|
|
it('does not leak a late-arriving resolve for a stale artistId', async () => {
|
|
// Race: artist A's fetch resolves AFTER the consumer switched to B.
|
|
const a = deferred<SubsonicArtistInfo | null>();
|
|
mockArtistInfo.mockImplementation(async (_sid, id) => {
|
|
if (id === 'art-A') return a.promise;
|
|
if (id === 'art-B') return { largeImageUrl: 'B.jpg' } as SubsonicArtistInfo;
|
|
return null;
|
|
});
|
|
|
|
const { result, rerender } = renderHook(
|
|
({ artistId }: { artistId: string }) =>
|
|
useNowPlayingFetchers({ ...baseDeps, artistId, artistName: artistId }),
|
|
{ initialProps: { artistId: 'art-A' } },
|
|
);
|
|
|
|
// Switch to B before A resolves.
|
|
rerender({ artistId: 'art-B' });
|
|
await waitFor(() => {
|
|
expect(result.current.artistInfo).toEqual({ largeImageUrl: 'B.jpg' });
|
|
});
|
|
|
|
// Late A resolve must not overwrite the displayed value for B.
|
|
await act(async () => { a.resolve({ largeImageUrl: 'A.jpg' } as SubsonicArtistInfo); });
|
|
expect(result.current.artistInfo).toEqual({ largeImageUrl: 'B.jpg' });
|
|
});
|
|
});
|
|
|
|
describe('useNowPlayingFetchers — id-gated songMeta / albumData / discography', () => {
|
|
it('gates songMeta on songId match', async () => {
|
|
const s1 = deferred<SubsonicSong | null>();
|
|
const s2 = deferred<SubsonicSong | null>();
|
|
vi.mocked(getSongForServer).mockImplementation(async (_sid, id) => {
|
|
if (id === 's1') return s1.promise;
|
|
if (id === 's2') return s2.promise;
|
|
return null;
|
|
});
|
|
|
|
const { result, rerender } = renderHook(
|
|
({ songId }: { songId: string }) =>
|
|
useNowPlayingFetchers({ ...baseDeps, songId }),
|
|
{ initialProps: { songId: 's1' } },
|
|
);
|
|
|
|
await act(async () => { s1.resolve({ id: 's1', title: 'Track 1' } as SubsonicSong); });
|
|
await waitFor(() => expect(result.current.songMeta?.title).toBe('Track 1'));
|
|
|
|
rerender({ songId: 's2' });
|
|
expect(result.current.songMeta).toBeNull();
|
|
|
|
await act(async () => { s2.resolve({ id: 's2', title: 'Track 2' } as SubsonicSong); });
|
|
await waitFor(() => expect(result.current.songMeta?.title).toBe('Track 2'));
|
|
});
|
|
|
|
it('gates albumData on albumId match', async () => {
|
|
const al1 = deferred<{ album: SubsonicAlbum; songs: SubsonicSong[] } | null>();
|
|
const al2 = deferred<{ album: SubsonicAlbum; songs: SubsonicSong[] } | null>();
|
|
vi.mocked(getAlbumForServer).mockImplementation(async (_sid, id) => {
|
|
if (id === 'alb1') return al1.promise as any;
|
|
if (id === 'alb2') return al2.promise as any;
|
|
return null as any;
|
|
});
|
|
|
|
const { result, rerender } = renderHook(
|
|
({ albumId }: { albumId: string }) =>
|
|
useNowPlayingFetchers({ ...baseDeps, albumId }),
|
|
{ initialProps: { albumId: 'alb1' } },
|
|
);
|
|
|
|
await act(async () => { al1.resolve({ album: { id: 'alb1', name: 'A1' } as SubsonicAlbum, songs: [] }); });
|
|
await waitFor(() => expect(result.current.albumData?.album.name).toBe('A1'));
|
|
|
|
rerender({ albumId: 'alb2' });
|
|
expect(result.current.albumData).toBeNull();
|
|
|
|
await act(async () => { al2.resolve({ album: { id: 'alb2', name: 'A2' } as SubsonicAlbum, songs: [] }); });
|
|
await waitFor(() => expect(result.current.albumData?.album.name).toBe('A2'));
|
|
});
|
|
|
|
it('gates discography on artistId match (empty fallback while gated)', async () => {
|
|
const d1 = deferred<{ artist: any; albums: SubsonicAlbum[] }>();
|
|
const d2 = deferred<{ artist: any; albums: SubsonicAlbum[] }>();
|
|
vi.mocked(getArtistForServer).mockImplementation(async (_sid, id) => {
|
|
if (id === 'art-D1') return d1.promise as any;
|
|
if (id === 'art-D2') return d2.promise as any;
|
|
return { albums: [] } as any;
|
|
});
|
|
mockArtistInfo.mockResolvedValue(null);
|
|
|
|
const { result, rerender } = renderHook(
|
|
({ artistId }: { artistId: string }) =>
|
|
useNowPlayingFetchers({ ...baseDeps, artistId, artistName: artistId }),
|
|
{ initialProps: { artistId: 'art-D1' } },
|
|
);
|
|
|
|
await act(async () => { d1.resolve({ artist: {}, albums: [{ id: 'al-D1' } as SubsonicAlbum] }); });
|
|
await waitFor(() => expect(result.current.discography.map(a => a.id)).toEqual(['al-D1']));
|
|
|
|
rerender({ artistId: 'art-D2' });
|
|
expect(result.current.discography).toEqual([]);
|
|
|
|
await act(async () => { d2.resolve({ artist: {}, albums: [{ id: 'al-D2' } as SubsonicAlbum] }); });
|
|
await waitFor(() => expect(result.current.discography.map(a => a.id)).toEqual(['al-D2']));
|
|
});
|
|
});
|
|
|
|
describe('useNowPlayingFetchers — local-playback metadata', () => {
|
|
// Regression: the metadata gate must never pass the playing track id, or the
|
|
// guard's `psysonic-local://` skip would blank every Subsonic card whenever
|
|
// the track plays from hot-cache / offline bytes. Guard is called with the
|
|
// server id only.
|
|
// Keep the shared guard mock at its permissive default after the behaviour
|
|
// case below swaps in a trackId-sensitive implementation.
|
|
afterEach(() => {
|
|
vi.mocked(shouldAttemptSubsonicForServer).mockImplementation(() => true);
|
|
});
|
|
|
|
it('queries the network guard without a trackId', async () => {
|
|
const guard = vi.mocked(shouldAttemptSubsonicForServer);
|
|
renderHook(() => useNowPlayingFetchers({ ...baseDeps, songId: 'song-1', albumId: 'al-1', artistId: 'art-1', artistName: 'Artist' }));
|
|
await waitFor(() => expect(guard).toHaveBeenCalled());
|
|
for (const call of guard.mock.calls) {
|
|
expect(call).toHaveLength(1);
|
|
expect(call[1]).toBeUndefined();
|
|
}
|
|
});
|
|
|
|
it('still loads album / discography / top songs when the playback bytes are local', async () => {
|
|
// Mirror the real guard: a byte-style call (with a trackId resolving to
|
|
// psysonic-local://) is blocked, but the metadata gate (server id only) is
|
|
// allowed. If the hook ever passed the trackId again, every fetch below
|
|
// would be gated off and the cards would blank — exactly the #1042 bug.
|
|
// Ids are unique to this test so the shared module caches don't short-circuit it.
|
|
vi.mocked(shouldAttemptSubsonicForServer).mockImplementation(
|
|
(_serverId, trackId) => trackId === undefined,
|
|
);
|
|
vi.mocked(getSongForServer).mockResolvedValue({ id: 'np-song', title: 'Local Track' } as SubsonicSong);
|
|
vi.mocked(getAlbumForServer).mockResolvedValue(
|
|
{ album: { id: 'np-al', name: 'Album' } as SubsonicAlbum, songs: [] } as any,
|
|
);
|
|
vi.mocked(getArtistForServer).mockResolvedValue({ albums: [{ id: 'np-al' }] } as any);
|
|
vi.mocked(getTopSongsForServer).mockResolvedValue([{ id: 'np-top' }] as any);
|
|
|
|
const { result } = renderHook(() =>
|
|
useNowPlayingFetchers({ ...baseDeps, songId: 'np-song', albumId: 'np-al', artistId: 'np-art', artistName: 'NP Artist' }),
|
|
);
|
|
|
|
await waitFor(() => expect(getAlbumForServer).toHaveBeenCalledWith('srv1', 'np-al'));
|
|
await waitFor(() => expect(getArtistForServer).toHaveBeenCalledWith('srv1', 'np-art'));
|
|
await waitFor(() => expect(getTopSongsForServer).toHaveBeenCalledWith('srv1', 'NP Artist'));
|
|
await waitFor(() => expect(result.current.albumData?.album.id).toBe('np-al'));
|
|
await waitFor(() => expect(result.current.discography.map(a => a.id)).toEqual(['np-al']));
|
|
await waitFor(() => expect(result.current.topSongs.map(s => s.id)).toEqual(['np-top']));
|
|
});
|
|
});
|