Files
Psychotoxical-psysonic/src/hooks/useConnectionStatus.test.ts
T
cucadmuh fc34a0ec59 feat(offline): local-bytes browse when server is unreachable (#1017)
* feat(offline): local-bytes browse for artists and albums

Make Artists, All Albums, and artist/album detail pages work offline
from the library index limited to on-disk library and favorite-auto
tracks. Add a DEV header toggle to simulate offline browse for testing.

* feat(offline): reactive DEV offline toggle with full disconnect simulation

Subscribe nav and browse/detail hooks to useOfflineBrowseActive so UI
refreshes on toggle. DEV force-offline now blocks server probes, reports
disconnected status, and gates Subsonic like real offline for player parity.

* feat(offline): bytes-first favorites when offline browse is active

Load Favorites from local playback bytes, filter starred tracks client-side,
and restrict album-level star queries to local album ids. Drop interim perf
attempts (lean SQL, progressive load, connection singleton, prefetch UX).

* feat(offline): tracks, help, player stats; suspend library picker offline

- Offline browse for Tracks hub from local bytes; sidebar nav for tracks/help/statistics
- Statistics redirects to player-stats offline; server/Last.fm tabs skip network fetches
- Hide music-library picker offline; save filter and restore on reconnect (all libraries while disconnected)
- Unified isOfflineSidebarNavAllowed for library + system entries

* feat(offline): fork disconnect navigation by offline browse capability

When the server drops: stay on the page if nothing is browsable offline;
reload in place on offline-capable routes; otherwise redirect to All Albums
instead of the old /offline or /favorites bounce.

* feat(offline): browse cached playlists when the server is down

List and open manually pinned regular playlists from local library-tier
bytes offline, with sidebar/nav routing and read-only playlist UI.

* feat(offline): read-only artist detail and local play-all paths

Hide favorites and discography offline actions when browse is offline;
load Play All, Shuffle, and top-track continuation from local album bytes.

* feat(offline): read-only album detail and enqueue from local bytes

Hide favorites, download, and cache-offline actions on album pages when
offline browse is active. Favorites album cards enqueue via the same
resolveAlbumForServer path as play, including local playback bytes.

* chore: remove unused import in AlbumCard after enqueue refactor

* feat(offline): unify browse integration contract across the app

Add useOfflineBrowseContext, offlineMediaResolve, and offlineActionPolicy;
wire shell nav to a single capability source; migrate play/enqueue and
context-menu paths off raw getAlbum; replace readOnly with action policy
on detail surfaces. Tests updated for the media-resolve facade.

* feat(offline): close browse contract gaps and fix offline Home feed

Split offline browse modules, align favorites capability across servers,
wire action policy on context menus, migrate hooks to useOfflineBrowseContext,
and preserve stale Home feed cache when offline so the UI does not empty.

* fix(offline): block playbar stars, close audit gaps, trim dead exports

Hide star rating and favorite in PlayerBar when offline browse is active via
offlineActionPolicy playerBar surface. Wire stay-reload token into browse
hooks, migrate hooks to context.active, guard rating prefetch network calls,
and route playlist load through resolvePlaylist.

* docs: add CHANGELOG and credits for offline browse PR #1017

* fix(offline): stop DEV connection probe regression in tests

React to devForceOffline transitions only in useConnectionStatus so mount
does not double-fire check() or ignore disableBackgroundPolling. Add
pingWithCredentials to PlayerBar test mock and DEV-toggle unit tests.
2026-06-07 15:59:41 +03:00

174 lines
6.5 KiB
TypeScript

import { beforeEach, describe, expect, it, vi } from 'vitest';
import { renderHook, act, waitFor } from '@testing-library/react';
import { resetAuthStore } from '@/test/helpers/storeReset';
import { useAuthStore } from '@/store/authStore';
import {
invalidateReachableEndpointCache,
type PickReachableResult,
} from '@/utils/server/serverEndpoint';
vi.mock('@/api/subsonic', () => ({
pingWithCredentials: vi.fn(),
scheduleInstantMixProbeForServer: vi.fn(),
}));
vi.mock('@/utils/perf/perfFlags', () => ({
usePerfProbeFlags: () => ({ disableBackgroundPolling: false }),
}));
import { pingWithCredentials } from '@/api/subsonic';
import { useDevOfflineBrowseStore } from '@/store/devOfflineBrowseStore';
import { useConnectionStatus } from './useConnectionStatus';
beforeEach(() => {
resetAuthStore();
invalidateReachableEndpointCache();
useDevOfflineBrowseStore.getState().setForceOffline(false);
vi.mocked(pingWithCredentials).mockReset();
});
function seedDualAddressServer(): string {
const id = useAuthStore.getState().addServer({
name: 'Home',
url: 'https://music.example.com',
alternateUrl: 'http://192.168.0.10',
username: 'tester',
password: 'pw',
});
useAuthStore.getState().setActiveServer(id);
return id;
}
describe('useConnectionStatus.isLan', () => {
it('reports the active endpoint kind after a probe, not the primary URL kind', async () => {
seedDualAddressServer();
// LAN endpoint answers — alternateUrl is the LAN side here, so a
// primary-url-only check would say "public". We assert it says "local"
// (active endpoint kind).
vi.mocked(pingWithCredentials).mockImplementation(async url =>
url === 'http://192.168.0.10'
? { ok: true, type: 'navidrome', serverVersion: '0.55.0', openSubsonic: true }
: { ok: false },
);
const { result } = renderHook(() => useConnectionStatus());
await waitFor(() => expect(result.current.status).toBe('connected'));
expect(result.current.isLan).toBe(true);
});
it('falls back to public when only the public address answers', async () => {
seedDualAddressServer();
vi.mocked(pingWithCredentials).mockImplementation(async url =>
url === 'https://music.example.com'
? { ok: true, type: 'navidrome', serverVersion: '0.55.0', openSubsonic: true }
: { ok: false },
);
const { result } = renderHook(() => useConnectionStatus());
await waitFor(() => expect(result.current.status).toBe('connected'));
// primary url is `https://music.example.com` — public. isLanUrl alone
// would have said `false` for the wrong reason (because the primary
// happens to be public); the test is meaningful because the LAN side
// was probed first and refused, so `activeEndpointKind` actively
// reflects "public".
expect(result.current.isLan).toBe(false);
});
it('falls back to primary URL classification before the first probe completes', () => {
seedDualAddressServer();
// Don't resolve the ping — the hook is still in the `checking` state.
let _resolve: ((v: PickReachableResult) => void) | null = null;
vi.mocked(pingWithCredentials).mockReturnValue(
new Promise(r => {
_resolve = ((res: PickReachableResult) => {
if (res.ok) {
r({
ok: true,
type: res.ping.type,
serverVersion: res.ping.serverVersion,
openSubsonic: res.ping.openSubsonic,
});
} else {
r({ ok: false });
}
}) as never;
}),
);
const { result } = renderHook(() => useConnectionStatus());
// Before the probe completes, isLan reflects the primary URL — public
// here, so false.
expect(result.current.isLan).toBe(false);
});
});
describe('useConnectionStatus online event', () => {
it('flushes the reachable-endpoint cache when the browser fires online', async () => {
seedDualAddressServer();
// Initial probe: LAN answers.
vi.mocked(pingWithCredentials).mockImplementation(async url =>
url === 'http://192.168.0.10'
? { ok: true, type: 'navidrome', serverVersion: '0.55.0', openSubsonic: true }
: { ok: false },
);
const { result } = renderHook(() => useConnectionStatus());
await waitFor(() => expect(result.current.status).toBe('connected'));
// Now flip: LAN goes dark, only public answers. The 120 s tick won't
// fire in this test; we trigger the online event instead. The handler
// invalidates the sticky cache so the next probe goes LAN-first and
// flips over to public when LAN refuses.
vi.mocked(pingWithCredentials).mockClear();
vi.mocked(pingWithCredentials).mockImplementation(async url =>
url === 'https://music.example.com'
? { ok: true, type: 'navidrome', serverVersion: '0.55.0', openSubsonic: true }
: { ok: false },
);
await act(async () => {
window.dispatchEvent(new Event('online'));
});
await waitFor(() => expect(result.current.isLan).toBe(false));
// Both endpoints were probed (LAN refused, public answered).
expect(vi.mocked(pingWithCredentials).mock.calls.length).toBeGreaterThanOrEqual(2);
});
});
describe('useConnectionStatus DEV offline toggle', () => {
it('does not probe again on mount beyond the polling effect', async () => {
seedDualAddressServer();
vi.mocked(pingWithCredentials).mockResolvedValue({
ok: true,
type: 'navidrome',
serverVersion: '0.55.0',
openSubsonic: true,
});
renderHook(() => useConnectionStatus());
await waitFor(() => expect(vi.mocked(pingWithCredentials).mock.calls.length).toBeGreaterThanOrEqual(1));
const callsAfterMount = vi.mocked(pingWithCredentials).mock.calls.length;
await new Promise(r => setTimeout(r, 20));
expect(vi.mocked(pingWithCredentials).mock.calls.length).toBe(callsAfterMount);
});
it('disconnects on force-offline toggle without an extra probe', async () => {
seedDualAddressServer();
vi.mocked(pingWithCredentials).mockResolvedValue({
ok: true,
type: 'navidrome',
serverVersion: '0.55.0',
openSubsonic: true,
});
const { result } = renderHook(() => useConnectionStatus());
await waitFor(() => expect(result.current.status).toBe('connected'));
const callsBeforeToggle = vi.mocked(pingWithCredentials).mock.calls.length;
act(() => useDevOfflineBrowseStore.getState().setForceOffline(true));
await waitFor(() => expect(result.current.status).toBe('disconnected'));
expect(vi.mocked(pingWithCredentials).mock.calls.length).toBe(callsBeforeToggle);
});
});