feat(server): capability framework, AudioMuse sonic routing & PsyLab Connections (#1033)

* feat(server): probe AudioMuse via OpenSubsonic and add PsyLab Connections tab

Navidrome ≥0.62: detect sonicSimilarity extension for reliable plugin signal;
older servers keep the legacy getSimilarSongs probe. PsyLab gets a Connections
tab with session, endpoint, and active-server capability details.

* feat(psylab): polish Connections tab, admin role probe, and tab bar layout

Status badges and Navidrome admin/user validation in Connections; prevent
PsyLab tab row from vertically collapsing under the Logs flex layout.

* docs: add CHANGELOG and credits for PR #1032

* feat(settings): auto-enable AudioMuse on Navidrome 0.62+ with status indicator

Replace the per-server manual toggle with a probe-driven badge when
sonicSimilarity is available; pre-0.62 Navidrome keeps the legacy toggle.

* feat(server): capability framework with AudioMuse sonic routing

Add a declarative server-capability catalog (src/serverCapabilities/) that
picks a feature strategy per server generation, runs only the needed probes,
and routes API calls. AudioMuse Instant Mix now prefers the OpenSubsonic
sonicSimilarity endpoint (getSonicSimilarTracks) on Navidrome 0.62+ and
falls back to legacy getSimilarSongs.

- catalog/context/resolve: eligibility, detection, activation, call routing
- storeView: read facade over the existing per-server probe maps
- getSonicSimilarTracks API client + fetchSimilarTracksRouted router
- route Instant Mix and Lucky Mix through the resolver
- ServersTab + PsyLab Connections read the resolver (auto status vs toggle)
- tests: resolve, storeView, router

* docs: update CHANGELOG and credits for PR #1033

Renamed branch supersedes PR #1032: point changelog/credits at #1033 and
document the server-capability framework, auto-managed AudioMuse indicator,
and sonic Instant Mix routing.

* refactor(server): address PR #1033 review — idempotent probe, drop dead code

- Make scheduleInstantMixProbeForServer idempotent: skip when a definitive
  result is cached; re-probe only on force (add/edit/test server), a prior
  error, or a server version/type change (invalidated in setSubsonicServerIdentity).
  Removes the steady-state 120 s re-probe, the present→probing→present flicker,
  and the momentary legacy-fallback routing window.
- Remove now-dead identity helpers (showAudiomuseNavidromeServerSetting,
  isAudiomusePluginAutoManaged, isNavidromeSonicSimilarityEligible,
  resolveAudiomusePluginProbeUiStatus + type) and the superseded
  probeAudiomusePluginWithCredentials; the catalog is the single source of truth.
- Drop the never-emitted 'unsupported' AudiomusePluginProbeResult variant.
- Fill audiomuseStatus* keys in all 8 non-en locales.
- Tests: probe idempotency + version-change invalidation; retarget
  OpenSubsonic test to fetchOpenSubsonicExtensionsWithCredentials.
This commit is contained in:
cucadmuh
2026-06-09 00:16:29 +03:00
committed by GitHub
parent 0878cbf308
commit 6118b3940f
43 changed files with 1867 additions and 74 deletions
+89
View File
@@ -0,0 +1,89 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('./subsonicOpenSubsonic', () => ({
fetchOpenSubsonicExtensionsWithCredentials: vi.fn(),
}));
import { fetchOpenSubsonicExtensionsWithCredentials } from './subsonicOpenSubsonic';
import { scheduleInstantMixProbeForServer } from './subsonic';
import { useAuthStore } from '../store/authStore';
import type { SubsonicServerIdentity } from '../utils/server/subsonicServerIdentity';
const fetchMock = vi.mocked(fetchOpenSubsonicExtensionsWithCredentials);
const SID = 'srv-probe';
const id062: SubsonicServerIdentity = { type: 'navidrome', serverVersion: '0.62.0', openSubsonic: true };
const flush = () => new Promise(resolve => setTimeout(resolve, 0));
function reset() {
useAuthStore.setState({
subsonicServerIdentityByServer: {},
audiomusePluginProbeByServer: {},
instantMixProbeByServer: {},
audiomuseNavidromeByServer: {},
audiomuseNavidromeIssueByServer: {},
} as never);
}
describe('scheduleInstantMixProbeForServer (idempotency)', () => {
beforeEach(() => {
fetchMock.mockReset();
fetchMock.mockResolvedValue(['sonicSimilarity']);
reset();
});
it('probes once, caches the result, then skips on the next poll', async () => {
scheduleInstantMixProbeForServer(SID, 'url', 'u', 'p', id062);
expect(fetchMock).toHaveBeenCalledTimes(1);
await flush();
expect(useAuthStore.getState().audiomusePluginProbeByServer[SID]).toBe('present');
scheduleInstantMixProbeForServer(SID, 'url', 'u', 'p', id062);
expect(fetchMock).toHaveBeenCalledTimes(1);
});
it('re-probes when forced (user-initiated refresh)', async () => {
scheduleInstantMixProbeForServer(SID, 'url', 'u', 'p', id062);
await flush();
scheduleInstantMixProbeForServer(SID, 'url', 'u', 'p', id062, true);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
it('re-probes after a prior error', async () => {
fetchMock.mockResolvedValueOnce(null);
scheduleInstantMixProbeForServer(SID, 'url', 'u', 'p', id062);
await flush();
expect(useAuthStore.getState().audiomusePluginProbeByServer[SID]).toBe('error');
scheduleInstantMixProbeForServer(SID, 'url', 'u', 'p', id062);
expect(fetchMock).toHaveBeenCalledTimes(2);
});
});
describe('setSubsonicServerIdentity (version-change cache invalidation)', () => {
beforeEach(reset);
it('clears cached probes on a version change but keeps the opt-in', () => {
useAuthStore.setState({
subsonicServerIdentityByServer: { [SID]: id062 },
audiomusePluginProbeByServer: { [SID]: 'present' },
audiomuseNavidromeByServer: { [SID]: true },
} as never);
useAuthStore.getState().setSubsonicServerIdentity(SID, { type: 'navidrome', serverVersion: '0.63.0', openSubsonic: true });
const s = useAuthStore.getState();
expect(s.audiomusePluginProbeByServer[SID]).toBeUndefined();
expect(s.audiomuseNavidromeByServer[SID]).toBe(true);
});
it('keeps cached probes when the identity is unchanged', () => {
useAuthStore.setState({
subsonicServerIdentityByServer: { [SID]: id062 },
audiomusePluginProbeByServer: { [SID]: 'present' },
} as never);
useAuthStore.getState().setSubsonicServerIdentity(SID, { ...id062 });
expect(useAuthStore.getState().audiomusePluginProbeByServer[SID]).toBe('present');
});
});
+52 -6
View File
@@ -2,10 +2,18 @@ import axios from 'axios';
import md5 from 'md5';
import { useAuthStore } from '../store/authStore';
import {
isNavidromeAudiomuseSoftwareEligible,
type InstantMixProbeResult,
type SubsonicServerIdentity,
} from '../utils/server/subsonicServerIdentity';
import { fetchOpenSubsonicExtensionsWithCredentials } from './subsonicOpenSubsonic';
import { buildCapabilityContext } from '../serverCapabilities/context';
import {
PROBE_LEGACY_INSTANT_MIX,
PROBE_OPENSUBSONIC_EXTENSIONS,
SERVER_CAPABILITY_CATALOG,
SONIC_SIMILARITY_EXTENSION,
} from '../serverCapabilities/catalog';
import { neededProbeIds } from '../serverCapabilities/resolve';
import {
SUBSONIC_CLIENT,
api,
@@ -104,16 +112,54 @@ export async function probeInstantMixWithCredentials(
}
}
/** After a successful ping, probe Instant Mix in the background (Navidrome ≥ 0.60 only). */
/**
* After a successful ping, run the server-capability probes needed by the catalog
* (`serverCapabilities/`). Which probes run is decided by the strategies eligible
* for this server generation — not by inline version checks here.
*
* Currently: Navidrome ≥ 0.62 → `getOpenSubsonicExtensions` (sonicSimilarity);
* Navidrome 0.600.61 → legacy `getSimilarSongs` Instant Mix probe.
*
* Idempotent: a server's advertised capabilities are static within a session, so
* once a definitive result is cached the probe is skipped. This is called on every
* 120 s connection poll, so re-fetching each time would be wasteful and would flip
* the resolved status (and the routed endpoint) through a `probing` window. Pass
* `force` for user-initiated refreshes (add/edit/test server); a server version or
* type change clears the cache (see `setSubsonicServerIdentity`), forcing a re-probe.
*/
export function scheduleInstantMixProbeForServer(
serverId: string,
serverUrl: string,
username: string,
password: string,
identity: SubsonicServerIdentity,
force = false,
): void {
if (!isNavidromeAudiomuseSoftwareEligible(identity)) return;
void probeInstantMixWithCredentials(serverUrl, username, password).then(result =>
useAuthStore.getState().setInstantMixProbe(serverId, result),
);
const ctx = buildCapabilityContext(identity);
const probeIds = neededProbeIds(SERVER_CAPABILITY_CATALOG, ctx);
const store = useAuthStore.getState();
if (probeIds.has(PROBE_OPENSUBSONIC_EXTENSIONS)) {
const cached = store.audiomusePluginProbeByServer[serverId];
// Re-probe only without a definitive cached result (or on force / prior error).
// `probing` means an in-flight fetch — skip to avoid a duplicate request.
if (force || cached === undefined || cached === 'error') {
store.setAudiomusePluginProbe(serverId, 'probing');
void fetchOpenSubsonicExtensionsWithCredentials(serverUrl, username, password).then(extensions => {
const result = extensions === null
? 'error'
: extensions.includes(SONIC_SIMILARITY_EXTENSION) ? 'present' : 'absent';
useAuthStore.getState().setAudiomusePluginProbe(serverId, result);
});
}
}
if (probeIds.has(PROBE_LEGACY_INSTANT_MIX)) {
const cached = store.instantMixProbeByServer[serverId];
if (force || cached === undefined || cached === 'error') {
void probeInstantMixWithCredentials(serverUrl, username, password).then(result =>
useAuthStore.getState().setInstantMixProbe(serverId, result),
);
}
}
}
+79
View File
@@ -0,0 +1,79 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
vi.mock('./subsonicClient', () => ({
api: vi.fn(),
apiForServer: vi.fn(),
libraryFilterParams: () => ({}),
libraryFilterParamsForServer: () => ({}),
}));
vi.mock('./subsonicLibrary', () => ({
filterSongsToActiveLibrary: async (songs: unknown[]) => songs,
filterSongsToServerLibrary: async (songs: unknown[]) => songs,
similarSongsRequestCount: (count: number) => count,
}));
import { api } from './subsonicClient';
import { fetchSimilarTracksRouted } from './subsonicArtists';
import { useAuthStore } from '../store/authStore';
const SID = 'srv-router';
const apiMock = vi.mocked(api);
function seedServer(identity: Record<string, unknown>, probes: Record<string, unknown>) {
useAuthStore.setState({
activeServerId: SID,
subsonicServerIdentityByServer: { [SID]: identity as never },
audiomusePluginProbeByServer: {},
instantMixProbeByServer: {},
audiomuseNavidromeByServer: {},
...probes,
} as never);
}
const SONIC_RESPONSE = { sonicMatch: [{ entry: { id: 'sonic-1', title: 'Sonic' } }] };
const SIMILAR_RESPONSE = { similarSongs: { song: [{ id: 'legacy-1', title: 'Legacy' }] } };
describe('fetchSimilarTracksRouted', () => {
beforeEach(() => {
apiMock.mockReset();
});
it('prefers sonicSimilarity on Navidrome 0.62 with plugin', async () => {
seedServer({ type: 'navidrome', serverVersion: '0.62.0', openSubsonic: true }, {
audiomusePluginProbeByServer: { [SID]: 'present' },
});
apiMock.mockImplementation(async (endpoint: string) =>
(endpoint === 'getSonicSimilarTracks.view' ? SONIC_RESPONSE : SIMILAR_RESPONSE) as never);
const result = await fetchSimilarTracksRouted('seed', 10);
expect(result.map(s => s.id)).toEqual(['sonic-1']);
expect(apiMock).toHaveBeenCalledWith('getSonicSimilarTracks.view', expect.anything());
expect(apiMock).not.toHaveBeenCalledWith('getSimilarSongs.view', expect.anything());
});
it('falls back to legacy when sonic returns empty', async () => {
seedServer({ type: 'navidrome', serverVersion: '0.62.0', openSubsonic: true }, {
audiomusePluginProbeByServer: { [SID]: 'present' },
});
apiMock.mockImplementation(async (endpoint: string) =>
(endpoint === 'getSonicSimilarTracks.view' ? { sonicMatch: [] } : SIMILAR_RESPONSE) as never);
const result = await fetchSimilarTracksRouted('seed', 10);
expect(result.map(s => s.id)).toEqual(['legacy-1']);
expect(apiMock).toHaveBeenCalledWith('getSonicSimilarTracks.view', expect.anything());
expect(apiMock).toHaveBeenCalledWith('getSimilarSongs.view', expect.anything());
});
it('uses legacy only on Navidrome 0.62 without plugin', async () => {
seedServer({ type: 'navidrome', serverVersion: '0.62.0', openSubsonic: true }, {
audiomusePluginProbeByServer: { [SID]: 'absent' },
});
apiMock.mockImplementation(async () => SIMILAR_RESPONSE as never);
const result = await fetchSimilarTracksRouted('seed', 10);
expect(result.map(s => s.id)).toEqual(['legacy-1']);
expect(apiMock).not.toHaveBeenCalledWith('getSonicSimilarTracks.view', expect.anything());
expect(apiMock).toHaveBeenCalledWith('getSimilarSongs.view', expect.anything());
});
});
+47
View File
@@ -2,6 +2,11 @@ import { useAuthStore } from '../store/authStore';
import { api, apiForServer, libraryFilterParams, libraryFilterParamsForServer } from './subsonicClient';
import { filterSongsToServerLibrary } from './subsonicLibrary';
import { filterSongsToActiveLibrary, similarSongsRequestCount } from './subsonicLibrary';
import {
FEATURE_AUDIOMUSE_SIMILAR_TRACKS,
OP_SIMILAR_TRACKS,
} from '../serverCapabilities/catalog';
import { resolveCallRoutesForServer } from '../serverCapabilities/storeView';
import type {
SubsonicAlbum,
SubsonicArtist,
@@ -109,3 +114,45 @@ export async function getSimilarSongs(id: string, count = 50): Promise<SubsonicS
return [];
}
}
/**
* Sonic (audio-analysis) similar tracks via the OpenSubsonic `sonicSimilarity`
* extension (Navidrome ≥ 0.62 + AudioMuse plugin). Returns `[]` when the server
* has no provider (HTTP 404) so callers can fall back.
*/
export async function getSonicSimilarTracks(id: string, count = 50): Promise<SubsonicSong[]> {
try {
const requestCount = similarSongsRequestCount(count);
const data = await api<{ sonicMatch: Array<{ entry?: SubsonicSong }> | { entry?: SubsonicSong } }>(
'getSonicSimilarTracks.view',
{ id, count: requestCount, ...libraryFilterParams() },
);
const raw = data.sonicMatch;
const list = Array.isArray(raw) ? raw : raw ? [raw] : [];
const songs = list.map(m => m.entry).filter((e): e is SubsonicSong => !!e);
if (songs.length === 0) return [];
const filtered = await filterSongsToActiveLibrary(songs);
return filtered.slice(0, count);
} catch {
return [];
}
}
/**
* Capability-routed similar tracks for the active server. Prefers the sonic
* similarity endpoint when the AudioMuse plugin is detected (Navidrome ≥ 0.62),
* falling back to legacy `getSimilarSongs` on empty/unavailable.
*/
export async function fetchSimilarTracksRouted(songId: string, count = 50): Promise<SubsonicSong[]> {
const { activeServerId } = useAuthStore.getState();
if (!activeServerId) return getSimilarSongs(songId, count);
const routes = resolveCallRoutesForServer(activeServerId, FEATURE_AUDIOMUSE_SIMILAR_TRACKS, OP_SIMILAR_TRACKS);
if (routes.length === 0) return getSimilarSongs(songId, count);
for (const route of routes) {
const songs = route.transport === 'opensubsonic'
? await getSonicSimilarTracks(songId, count)
: await getSimilarSongs(songId, count);
if (songs.length > 0) return songs;
}
return [];
}
+72
View File
@@ -0,0 +1,72 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import axios from 'axios';
import {
fetchOpenSubsonicExtensionsWithCredentials,
hasOpenSubsonicExtension,
parseOpenSubsonicExtensions,
} from './subsonicOpenSubsonic';
vi.mock('axios');
function okExtensions(extensions: unknown[]) {
return {
data: {
'subsonic-response': {
status: 'ok',
openSubsonic: true,
openSubsonicExtensions: extensions,
},
},
};
}
describe('parseOpenSubsonicExtensions', () => {
it('parses extension names and versions', () => {
const parsed = parseOpenSubsonicExtensions([
{ name: 'sonicSimilarity', versions: [1] },
{ name: 'playbackReport', versions: [1, 2] },
{ bad: true },
]);
expect(parsed).toEqual([
{ name: 'sonicSimilarity', versions: [1] },
{ name: 'playbackReport', versions: [1, 2] },
]);
});
});
describe('hasOpenSubsonicExtension', () => {
it('detects sonicSimilarity', () => {
const extensions = parseOpenSubsonicExtensions([{ name: 'sonicSimilarity', versions: [1] }]);
expect(hasOpenSubsonicExtension(extensions, 'sonicSimilarity')).toBe(true);
expect(hasOpenSubsonicExtension(extensions, 'other')).toBe(false);
});
});
describe('fetchOpenSubsonicExtensionsWithCredentials', () => {
beforeEach(() => {
vi.clearAllMocks();
});
it('returns the advertised extension names', async () => {
vi.mocked(axios.get).mockResolvedValue(
okExtensions([{ name: 'sonicSimilarity', versions: [1] }, { name: 'playbackReport', versions: [1] }]),
);
await expect(
fetchOpenSubsonicExtensionsWithCredentials('https://music.test', 'u', 'p'),
).resolves.toEqual(['sonicSimilarity', 'playbackReport']);
});
it('returns an empty list when none are advertised', async () => {
vi.mocked(axios.get).mockResolvedValue(okExtensions([]));
await expect(
fetchOpenSubsonicExtensionsWithCredentials('https://music.test', 'u', 'p'),
).resolves.toEqual([]);
});
it('returns null on request failure', async () => {
vi.mocked(axios.get).mockRejectedValue(new Error('boom'));
await expect(
fetchOpenSubsonicExtensionsWithCredentials('https://music.test', 'u', 'p'),
).resolves.toBeNull();
});
});
+47
View File
@@ -0,0 +1,47 @@
import { apiWithCredentials } from './subsonicClient';
export interface OpenSubsonicExtension {
name: string;
versions: number[];
}
export function parseOpenSubsonicExtensions(raw: unknown): OpenSubsonicExtension[] {
if (!Array.isArray(raw)) return [];
return raw
.filter((entry): entry is Record<string, unknown> => !!entry && typeof entry === 'object' && !Array.isArray(entry))
.map(entry => ({
name: typeof entry.name === 'string' ? entry.name : '',
versions: Array.isArray(entry.versions)
? entry.versions.filter((v): v is number => typeof v === 'number')
: [],
}))
.filter(entry => entry.name.length > 0);
}
export function hasOpenSubsonicExtension(extensions: readonly OpenSubsonicExtension[], name: string): boolean {
return extensions.some(ext => ext.name === name);
}
/**
* Fetch the list of OpenSubsonic extension names advertised by the server, or
* `null` when the request fails. Shared probe for any extension-gated feature.
*/
export async function fetchOpenSubsonicExtensionsWithCredentials(
serverUrl: string,
username: string,
password: string,
): Promise<string[] | null> {
try {
const data = await apiWithCredentials<{ openSubsonicExtensions?: unknown }>(
serverUrl,
username,
password,
'getOpenSubsonicExtensions.view',
{},
12000,
);
return parseOpenSubsonicExtensions(data.openSubsonicExtensions).map(ext => ext.name);
} catch {
return null;
}
}