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
+27
View File
@@ -128,6 +128,25 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### PsyLab — Connections tab and Navidrome admin role
**By [@cucadmuh](https://github.com/cucadmuh), PR [#1033](https://github.com/Psychotoxical/psysonic/pull/1033)**
* New **Connections** tab: session/endpoint status, active-server capability readout (OpenSubsonic, AudioMuse detection, provider/strategy, detection trust, resolved call route, and AudioMuse mode), and queue-playback server when it differs from the active profile.
* Navidrome **admin vs standard user** badge via native login probe — useful when diagnosing plugin/settings visibility.
### Servers — capability framework with AudioMuse sonic routing (Navidrome ≥ 0.62)
**By [@cucadmuh](https://github.com/cucadmuh), PR [#1033](https://github.com/Psychotoxical/psysonic/pull/1033)**
* New declarative **server-capability framework** (`src/serverCapabilities/`): a catalog picks a feature strategy per server generation, runs only the needed probes, and routes API calls — replacing scattered version checks in the UI and call sites.
* Navidrome **0.62+**: detect the AudioMuse-AI plugin from `getOpenSubsonicExtensions` when `sonicSimilarity` is advertised — the first reliable signal. Settings shows an **auto-managed status indicator** (no manual toggle); older Navidrome keeps the manual toggle and the legacy `getSimilarSongs` Instant Mix probe.
* **Path routing**: Instant Mix and Lucky Mix prefer the OpenSubsonic `getSonicSimilarTracks` endpoint when the plugin is present, falling back to legacy `getSimilarSongs`.
## Fixed ## Fixed
### Servers — complete border on the active server card ### Servers — complete border on the active server card
@@ -198,6 +217,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### PsyLab — tab bar no longer collapses on the Logs tab
**By [@cucadmuh](https://github.com/cucadmuh), PR [#1033](https://github.com/Psychotoxical/psysonic/pull/1033)**
* The PsyLab tab row keeps its height when the Logs flex layout fills the modal — tabs were previously squashed to a thin strip.
## [1.47.0] ## [1.47.0]
> **🙏 Thank you to our amazing Discord community.** This release would not have been possible without your tireless support, quality checks, bug reports and all-round collaboration. Every report, every repro and every bit of feedback shaped what shipped here — thank you. Come join us: [discord.gg/AMnDRErm4u](https://discord.gg/AMnDRErm4u) > **🙏 Thank you to our amazing Discord community.** This release would not have been possible without your tireless support, quality checks, bug reports and all-round collaboration. Every report, every repro and every bit of feedback shaped what shipped here — thank you. Come join us: [discord.gg/AMnDRErm4u](https://discord.gg/AMnDRErm4u)
+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');
});
});
+49 -3
View File
@@ -2,10 +2,18 @@ import axios from 'axios';
import md5 from 'md5'; import md5 from 'md5';
import { useAuthStore } from '../store/authStore'; import { useAuthStore } from '../store/authStore';
import { import {
isNavidromeAudiomuseSoftwareEligible,
type InstantMixProbeResult, type InstantMixProbeResult,
type SubsonicServerIdentity, type SubsonicServerIdentity,
} from '../utils/server/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 { import {
SUBSONIC_CLIENT, SUBSONIC_CLIENT,
api, 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( export function scheduleInstantMixProbeForServer(
serverId: string, serverId: string,
serverUrl: string, serverUrl: string,
username: string, username: string,
password: string, password: string,
identity: SubsonicServerIdentity, identity: SubsonicServerIdentity,
force = false,
): void { ): void {
if (!isNavidromeAudiomuseSoftwareEligible(identity)) return; 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 => void probeInstantMixWithCredentials(serverUrl, username, password).then(result =>
useAuthStore.getState().setInstantMixProbe(serverId, 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 { api, apiForServer, libraryFilterParams, libraryFilterParamsForServer } from './subsonicClient';
import { filterSongsToServerLibrary } from './subsonicLibrary'; import { filterSongsToServerLibrary } from './subsonicLibrary';
import { filterSongsToActiveLibrary, similarSongsRequestCount } 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 { import type {
SubsonicAlbum, SubsonicAlbum,
SubsonicArtist, SubsonicArtist,
@@ -109,3 +114,45 @@ export async function getSimilarSongs(id: string, count = 50): Promise<SubsonicS
return []; 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;
}
}
+42 -11
View File
@@ -24,7 +24,10 @@ import {
} from '../../utils/server/serverUrlRemigration'; } from '../../utils/server/serverUrlRemigration';
import { useConfirmModalStore } from '../../store/confirmModalStore'; import { useConfirmModalStore } from '../../store/confirmModalStore';
import { showToast } from '../../utils/ui/toast'; import { showToast } from '../../utils/ui/toast';
import { showAudiomuseNavidromeServerSetting } from '../../utils/server/subsonicServerIdentity'; import PerfProbeStatusBadge, { type PerfProbeBadgeTone } from '../sidebar/perfProbe/PerfProbeStatusBadge';
import { FEATURE_AUDIOMUSE_SIMILAR_TRACKS } from '../../serverCapabilities/catalog';
import { resolveFeatureForServer } from '../../serverCapabilities/storeView';
import type { CapabilityStatus, ResolvedCapability } from '../../serverCapabilities/types';
import { serverListDisplayLabel } from '../../utils/server/serverDisplayName'; import { serverListDisplayLabel } from '../../utils/server/serverDisplayName';
import { serverIndexKeyForProfile } from '../../utils/server/serverIndexKey'; import { serverIndexKeyForProfile } from '../../utils/server/serverIndexKey';
import { switchActiveServer } from '../../utils/server/switchActiveServer'; import { switchActiveServer } from '../../utils/server/switchActiveServer';
@@ -33,6 +36,24 @@ import { ServerGripHandle } from './ServerGripHandle';
const AUDIOMUSE_NV_PLUGIN_URL = 'https://github.com/NeptuneHub/AudioMuse-AI-NV-plugin'; const AUDIOMUSE_NV_PLUGIN_URL = 'https://github.com/NeptuneHub/AudioMuse-AI-NV-plugin';
function audiomuseProbeBadge(
status: CapabilityStatus,
t: (key: string) => string,
): { tone: PerfProbeBadgeTone; label: string } {
switch (status) {
case 'present': return { tone: 'ok', label: t('settings.audiomuseStatusActive') };
case 'absent': return { tone: 'muted', label: t('settings.audiomuseStatusNotDetected') };
case 'error': return { tone: 'error', label: t('settings.audiomuseStatusProbeFailed') };
default: return { tone: 'warn', label: t('settings.audiomuseStatusChecking') };
}
}
/** Row visibility: hide only when a manual (legacy) strategy proves the feature absent. */
function showAudiomuseRow(resolved: ResolvedCapability | null): boolean {
if (!resolved || resolved.strategyId === null || resolved.status === 'ineligible') return false;
return !(resolved.activation === 'manual' && resolved.status === 'absent');
}
type ServerDropTarget = { idx: number; before: boolean } | null; type ServerDropTarget = { idx: number; before: boolean } | null;
export function ServersTab({ export function ServersTab({
@@ -135,7 +156,7 @@ export function ServersTab({
openSubsonic: probe.ping.openSubsonic, openSubsonic: probe.ping.openSubsonic,
}; };
auth.setSubsonicServerIdentity(server.id, identity); auth.setSubsonicServerIdentity(server.id, identity);
scheduleInstantMixProbeForServer(server.id, probe.baseUrl, server.username, server.password, identity); scheduleInstantMixProbeForServer(server.id, probe.baseUrl, server.username, server.password, identity, true);
} }
setConnStatus(s => ({ ...s, [server.id]: probe.ok ? 'ok' : 'error' })); setConnStatus(s => ({ ...s, [server.id]: probe.ok ? 'ok' : 'error' }));
} catch { } catch {
@@ -232,7 +253,7 @@ export function ServersTab({
openSubsonic: ping.openSubsonic, openSubsonic: ping.openSubsonic,
}; };
auth.setSubsonicServerIdentity(id, identity); auth.setSubsonicServerIdentity(id, identity);
scheduleInstantMixProbeForServer(id, data.url, data.username, data.password, identity); scheduleInstantMixProbeForServer(id, data.url, data.username, data.password, identity, true);
setConnStatus(s => ({ ...s, [id]: 'ok' })); setConnStatus(s => ({ ...s, [id]: 'ok' }));
const added = useAuthStore.getState().servers.find(s => s.id === id); const added = useAuthStore.getState().servers.find(s => s.id === id);
if (added) void bootstrapIndexedServer(added); if (added) void bootstrapIndexedServer(added);
@@ -324,7 +345,7 @@ export function ServersTab({
openSubsonic: ping.openSubsonic, openSubsonic: ping.openSubsonic,
}; };
auth.setSubsonicServerIdentity(id, identity); auth.setSubsonicServerIdentity(id, identity);
scheduleInstantMixProbeForServer(id, data.url, data.username, data.password, identity); scheduleInstantMixProbeForServer(id, data.url, data.username, data.password, identity, true);
} }
setConnStatus(s => ({ ...s, [id]: ping.ok ? 'ok' : 'error' })); setConnStatus(s => ({ ...s, [id]: ping.ok ? 'ok' : 'error' }));
} catch { } catch {
@@ -483,10 +504,13 @@ export function ServersTab({
onVerify={() => void librarySync.runServerAction(serverIndexKeyForProfile(srv), 'verify')} onVerify={() => void librarySync.runServerAction(serverIndexKeyForProfile(srv), 'verify')}
onCancel={() => void librarySync.handleCancel()} onCancel={() => void librarySync.handleCancel()}
/> />
{showAudiomuseNavidromeServerSetting( {(() => {
auth.subsonicServerIdentityByServer[srv.id], const resolved = resolveFeatureForServer(srv.id, FEATURE_AUDIOMUSE_SIMILAR_TRACKS);
auth.instantMixProbeByServer[srv.id], if (!showAudiomuseRow(resolved) || !resolved) return null;
) && ( const autoManaged = resolved.activation === 'auto';
const probeBadge = audiomuseProbeBadge(resolved.status, t);
const audiomuseActive = !!auth.audiomuseNavidromeByServer[srv.id];
return (
<div <div
className="settings-toggle-row" className="settings-toggle-row"
data-settings-search={t('settings.audiomuseTitle')} data-settings-search={t('settings.audiomuseTitle')}
@@ -497,7 +521,7 @@ export function ServersTab({
<div> <div>
<div style={{ fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}> <div style={{ fontWeight: 500, display: 'flex', alignItems: 'center', gap: 8, flexWrap: 'wrap' }}>
{t('settings.audiomuseTitle')} {t('settings.audiomuseTitle')}
{!!auth.audiomuseNavidromeByServer[srv.id] && auth.audiomuseNavidromeIssueByServer[srv.id] && ( {audiomuseActive && auth.audiomuseNavidromeIssueByServer[srv.id] && (
<AlertTriangle <AlertTriangle
size={16} size={16}
style={{ color: 'var(--warning, #f59e0b)', flexShrink: 0 }} style={{ color: 'var(--warning, #f59e0b)', flexShrink: 0 }}
@@ -506,6 +530,7 @@ export function ServersTab({
/> />
)} )}
</div> </div>
{!autoManaged && (
<div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.45 }}> <div style={{ fontSize: 12, color: 'var(--text-muted)', lineHeight: 1.45 }}>
<Trans <Trans
i18nKey="settings.audiomuseDesc" i18nKey="settings.audiomuseDesc"
@@ -523,20 +548,26 @@ export function ServersTab({
}} }}
/> />
</div> </div>
)}
</div> </div>
</div> </div>
{autoManaged ? (
<PerfProbeStatusBadge tone={probeBadge.tone}>{probeBadge.label}</PerfProbeStatusBadge>
) : (
<label className="toggle-switch" aria-label={t('settings.audiomuseTitle')}> <label className="toggle-switch" aria-label={t('settings.audiomuseTitle')}>
<input <input
type="checkbox" type="checkbox"
checked={!!auth.audiomuseNavidromeByServer[srv.id]} checked={audiomuseActive}
onChange={e => auth.setAudiomuseNavidromeEnabled(srv.id, e.target.checked)} onChange={e => auth.setAudiomuseNavidromeEnabled(srv.id, e.target.checked)}
/> />
<span className="toggle-track" /> <span className="toggle-track" />
</label> </label>
</div>
)} )}
</div> </div>
); );
})()}
</div>
);
})} })}
</div> </div>
)} )}
@@ -1,16 +1,17 @@
import { useState } from 'react'; import { useState } from 'react';
import { Activity, ScrollText, SlidersHorizontal, Wrench, X } from 'lucide-react'; import { Activity, Network, ScrollText, SlidersHorizontal, Wrench, X } from 'lucide-react';
import { createPortal } from 'react-dom'; import { createPortal } from 'react-dom';
import SidebarPerfProbeMonitorTab from './perfProbe/SidebarPerfProbeMonitorTab'; import SidebarPerfProbeMonitorTab from './perfProbe/SidebarPerfProbeMonitorTab';
import SidebarPerfProbeTogglesTab from './perfProbe/SidebarPerfProbeTogglesTab'; import SidebarPerfProbeTogglesTab from './perfProbe/SidebarPerfProbeTogglesTab';
import SidebarPerfProbeTuningTab from './perfProbe/SidebarPerfProbeTuningTab'; import SidebarPerfProbeTuningTab from './perfProbe/SidebarPerfProbeTuningTab';
import SidebarPerfProbeLogsTab from './perfProbe/SidebarPerfProbeLogsTab'; import SidebarPerfProbeLogsTab from './perfProbe/SidebarPerfProbeLogsTab';
import SidebarPerfProbeConnectionsTab from './perfProbe/SidebarPerfProbeConnectionsTab';
import { resetPerfProbeFlags, type PerfProbeFlags } from '../../utils/perf/perfFlags'; import { resetPerfProbeFlags, type PerfProbeFlags } from '../../utils/perf/perfFlags';
import { clearPerfLiveOverlayPins } from '../../utils/perf/perfOverlayPins'; import { clearPerfLiveOverlayPins } from '../../utils/perf/perfOverlayPins';
import { resetPerfOverlayAppearance } from '../../utils/perf/perfOverlayAppearance'; import { resetPerfOverlayAppearance } from '../../utils/perf/perfOverlayAppearance';
import { resetPerfOverlayMode } from '../../utils/perf/perfOverlayMode'; import { resetPerfOverlayMode } from '../../utils/perf/perfOverlayMode';
type TabId = 'monitor' | 'toggles' | 'tuning' | 'logs'; type TabId = 'monitor' | 'connections' | 'toggles' | 'tuning' | 'logs';
interface Props { interface Props {
open: boolean; open: boolean;
@@ -65,7 +66,7 @@ export default function SidebarPerfProbeModal({
<header className="sidebar-perf-modal__header"> <header className="sidebar-perf-modal__header">
<h3 id="psylab-title" className="modal-title">PsyLab</h3> <h3 id="psylab-title" className="modal-title">PsyLab</h3>
<p className="sidebar-perf-modal__hint"> <p className="sidebar-perf-modal__hint">
Live metrics with optional on-screen overlays, runtime tuning, and diagnostic disable toggles. Live metrics, server connections, runtime tuning, and diagnostic disable toggles.
</p> </p>
</header> </header>
@@ -80,6 +81,16 @@ export default function SidebarPerfProbeModal({
<Activity size={15} /> <Activity size={15} />
Monitor Monitor
</button> </button>
<button
type="button"
role="tab"
aria-selected={tab === 'connections'}
className={`sidebar-perf-modal__tab${tab === 'connections' ? ' sidebar-perf-modal__tab--active' : ''}`}
onClick={() => setTab('connections')}
>
<Network size={15} />
Connections
</button>
<button <button
type="button" type="button"
role="tab" role="tab"
@@ -114,6 +125,7 @@ export default function SidebarPerfProbeModal({
<div className={`sidebar-perf-modal__body${tab === 'logs' ? ' sidebar-perf-modal__body--logs' : ''}`}> <div className={`sidebar-perf-modal__body${tab === 'logs' ? ' sidebar-perf-modal__body--logs' : ''}`}>
{tab === 'monitor' && <SidebarPerfProbeMonitorTab />} {tab === 'monitor' && <SidebarPerfProbeMonitorTab />}
{tab === 'connections' && <SidebarPerfProbeConnectionsTab />}
{tab === 'tuning' && <SidebarPerfProbeTuningTab />} {tab === 'tuning' && <SidebarPerfProbeTuningTab />}
{tab === 'toggles' && ( {tab === 'toggles' && (
<SidebarPerfProbeTogglesTab <SidebarPerfProbeTogglesTab
@@ -0,0 +1,23 @@
import type { ReactNode } from 'react';
export interface PerfProbeDetailRow {
label: string;
value: ReactNode;
}
interface Props {
rows: PerfProbeDetailRow[];
}
export default function PerfProbeDetailList({ rows }: Props) {
return (
<dl className="perf-server-dl">
{rows.map(row => (
<div key={row.label} className="perf-server-dl__row">
<dt>{row.label}</dt>
<dd>{row.value}</dd>
</div>
))}
</dl>
);
}
@@ -71,6 +71,7 @@ interface SectionProps {
hint?: string; hint?: string;
children: ReactNode; children: ReactNode;
defaultOpen?: boolean; defaultOpen?: boolean;
layout?: 'grid' | 'stack';
onOpenChange?: (open: boolean) => void; onOpenChange?: (open: boolean) => void;
} }
@@ -79,6 +80,7 @@ export function PerfProbeMetricSection({
hint, hint,
children, children,
defaultOpen = true, defaultOpen = true,
layout = 'grid',
onOpenChange, onOpenChange,
}: SectionProps) { }: SectionProps) {
return ( return (
@@ -92,7 +94,9 @@ export function PerfProbeMetricSection({
<span>{title}</span> <span>{title}</span>
{hint && <span className="perf-metric-section__hint">{hint}</span>} {hint && <span className="perf-metric-section__hint">{hint}</span>}
</summary> </summary>
<div className="perf-metric-section__grid">{children}</div> <div className={layout === 'stack' ? 'perf-metric-section__body' : 'perf-metric-section__grid'}>
{children}
</div>
</details> </details>
); );
} }
@@ -0,0 +1,16 @@
import type { ReactNode } from 'react';
export type PerfProbeBadgeTone = 'ok' | 'warn' | 'error' | 'neutral' | 'muted';
interface Props {
tone: PerfProbeBadgeTone;
children: ReactNode;
}
export default function PerfProbeStatusBadge({ tone, children }: Props) {
return (
<span className={`perf-status-badge perf-status-badge--${tone}`}>
{children}
</span>
);
}
@@ -0,0 +1,129 @@
import { useAuthStore } from '../../../store/authStore';
import { usePlayerStore } from '../../../store/playerStore';
import { useConnectionStatus } from '../../../hooks/useConnectionStatus';
import { useNavidromeAdminRole } from '../../../hooks/useNavidromeAdminRole';
import { serverListDisplayLabel } from '../../../utils/server/serverDisplayName';
import { findServerByIdOrIndexKey } from '../../../utils/server/serverLookup';
import { PerfProbeMetricSection } from './PerfProbeMetricCard';
import PerfProbeDetailList from './PerfProbeDetailList';
import PerfProbeStatusBadge, { type PerfProbeBadgeTone } from './PerfProbeStatusBadge';
import SidebarPerfProbeServerSection from './SidebarPerfProbeServerSection';
function connectionStatusBadge(status: string): { tone: PerfProbeBadgeTone; label: string } {
switch (status) {
case 'connected': return { tone: 'ok', label: 'Connected' };
case 'disconnected': return { tone: 'error', label: 'Disconnected' };
case 'checking': return { tone: 'warn', label: 'Checking…' };
default: return { tone: 'muted', label: status };
}
}
function sessionBadge(loggedIn: boolean): { tone: PerfProbeBadgeTone; label: string } {
return loggedIn
? { tone: 'ok', label: 'Logged in' }
: { tone: 'muted', label: 'Not logged in' };
}
function adminRoleBadge(role: ReturnType<typeof useNavidromeAdminRole>): { tone: PerfProbeBadgeTone; label: string } {
switch (role) {
case 'admin': return { tone: 'ok', label: 'Admin' };
case 'user': return { tone: 'neutral', label: 'Standard user' };
case 'checking':
case 'idle': return { tone: 'warn', label: 'Checking…' };
case 'error': return { tone: 'error', label: 'Could not verify' };
case 'na':
default: return { tone: 'muted', label: 'N/A (not Navidrome)' };
}
}
function endpointBadge(isLan: boolean): { tone: PerfProbeBadgeTone; label: string } {
return isLan
? { tone: 'ok', label: 'LAN' }
: { tone: 'neutral', label: 'Public / remote' };
}
export default function SidebarPerfProbeConnectionsTab() {
const { status, isLan, serverName } = useConnectionStatus();
const isLoggedIn = useAuthStore(s => s.isLoggedIn);
const activeServerId = useAuthStore(s => s.activeServerId);
const servers = useAuthStore(s => s.servers);
const connectUrl = useAuthStore(s => s.getBaseUrl());
const queueServerId = usePlayerStore(s => s.queueServerId);
const adminRole = useNavidromeAdminRole();
const queueServer = queueServerId ? findServerByIdOrIndexKey(queueServerId) : undefined;
const queueDiffersFromActive = Boolean(
queueServerId && activeServerId && queueServerId !== activeServerId,
);
const connBadge = connectionStatusBadge(status);
const sessBadge = sessionBadge(isLoggedIn);
const roleBadge = adminRoleBadge(adminRole);
return (
<div className="perf-monitor">
<div className="perf-conn-summary" aria-label="Connection overview">
<div className="perf-conn-summary__item">
<span className="perf-conn-summary__label">Link</span>
<PerfProbeStatusBadge tone={connBadge.tone}>{connBadge.label}</PerfProbeStatusBadge>
</div>
<div className="perf-conn-summary__item">
<span className="perf-conn-summary__label">Session</span>
<PerfProbeStatusBadge tone={sessBadge.tone}>{sessBadge.label}</PerfProbeStatusBadge>
</div>
{isLoggedIn && (
<div className="perf-conn-summary__item">
<span className="perf-conn-summary__label">Role</span>
<PerfProbeStatusBadge tone={roleBadge.tone}>{roleBadge.label}</PerfProbeStatusBadge>
</div>
)}
</div>
<PerfProbeMetricSection title="Connection" defaultOpen layout="stack">
<PerfProbeDetailList
rows={[
{
label: 'Status',
value: <PerfProbeStatusBadge tone={connBadge.tone}>{connBadge.label}</PerfProbeStatusBadge>,
},
{
label: 'Session',
value: <PerfProbeStatusBadge tone={sessBadge.tone}>{sessBadge.label}</PerfProbeStatusBadge>,
},
...(isLoggedIn
? [{
label: 'Navidrome role',
value: <PerfProbeStatusBadge tone={roleBadge.tone}>{roleBadge.label}</PerfProbeStatusBadge>,
}]
: []),
...(serverName ? [{ label: 'Browse label', value: serverName }] : []),
...(connectUrl ? [{ label: 'Connect URL', value: <code className="perf-server-dl__code">{connectUrl}</code> }] : []),
...(status === 'connected'
? [{
label: 'Endpoint',
value: (
<PerfProbeStatusBadge tone={endpointBadge(isLan).tone}>
{endpointBadge(isLan).label}
</PerfProbeStatusBadge>
),
}]
: []),
]}
/>
</PerfProbeMetricSection>
<SidebarPerfProbeServerSection adminRole={adminRole} />
{queueDiffersFromActive && queueServer && (
<PerfProbeMetricSection title="Queue playback server" defaultOpen={false} layout="stack">
<PerfProbeDetailList
rows={[
{ label: 'Name', value: serverListDisplayLabel(queueServer, servers) },
{ label: 'Scope key', value: <code className="perf-server-dl__code">{queueServerId}</code> },
]}
/>
</PerfProbeMetricSection>
)}
</div>
);
}
@@ -0,0 +1,155 @@
import { useAuthStore } from '../../../store/authStore';
import type { NavidromeAdminRole } from '../../../hooks/useNavidromeAdminRole';
import { isNavidromeServer } from '../../../utils/server/subsonicServerIdentity';
import { FEATURE_AUDIOMUSE_SIMILAR_TRACKS, OP_SIMILAR_TRACKS } from '../../../serverCapabilities/catalog';
import {
isFeatureActiveForServer,
resolveCallRoutesForServer,
resolveFeatureForServer,
} from '../../../serverCapabilities/storeView';
import type { CapabilityStatus, FeatureTrust, ResolvedCapability } from '../../../serverCapabilities/types';
import { PerfProbeMetricSection } from './PerfProbeMetricCard';
import PerfProbeDetailList, { type PerfProbeDetailRow } from './PerfProbeDetailList';
import PerfProbeStatusBadge, { type PerfProbeBadgeTone } from './PerfProbeStatusBadge';
function formatServerType(identity: { type?: string; serverVersion?: string; openSubsonic?: boolean } | undefined): string {
if (!identity?.type?.trim()) return 'Unknown';
const version = identity.serverVersion?.trim();
return version ? `${identity.type} ${version}` : identity.type;
}
function detectionBadge(status: CapabilityStatus): { tone: PerfProbeBadgeTone; label: string } {
switch (status) {
case 'present': return { tone: 'ok', label: 'Detected' };
case 'absent': return { tone: 'muted', label: 'Not detected' };
case 'probing': return { tone: 'warn', label: 'Checking…' };
case 'error': return { tone: 'error', label: 'Probe failed' };
case 'unknown': return { tone: 'muted', label: 'Not probed yet' };
default: return { tone: 'muted', label: 'N/A' };
}
}
function strategyLabel(strategyId: string | null): string {
switch (strategyId) {
case 'opensubsonic.sonicSimilarity': return 'sonicSimilarity (OpenSubsonic)';
case 'subsonic.getSimilarSongs': return 'getSimilarSongs (legacy)';
default: return '—';
}
}
function trustBadge(trust: FeatureTrust | null): { tone: PerfProbeBadgeTone; label: string } {
switch (trust) {
case 'high': return { tone: 'ok', label: 'high' };
case 'low': return { tone: 'warn', label: 'heuristic' };
default: return { tone: 'muted', label: '—' };
}
}
function adminRoleBadge(role: NavidromeAdminRole): { tone: PerfProbeBadgeTone; label: string } {
switch (role) {
case 'admin': return { tone: 'ok', label: 'Admin' };
case 'user': return { tone: 'neutral', label: 'Standard user' };
case 'checking':
case 'idle': return { tone: 'warn', label: 'Checking…' };
case 'error': return { tone: 'error', label: 'Could not verify' };
case 'na':
default: return { tone: 'muted', label: 'N/A' };
}
}
interface Props {
adminRole?: NavidromeAdminRole;
}
export default function SidebarPerfProbeServerSection({ adminRole = 'na' }: Props) {
const activeServerId = useAuthStore(s => s.activeServerId);
const server = useAuthStore(s => s.servers.find(srv => srv.id === s.activeServerId));
const identity = useAuthStore(s =>
activeServerId ? s.subsonicServerIdentityByServer[activeServerId] : undefined,
);
// Subscribe to the probe maps so the resolver-derived rows re-render on probe updates.
useAuthStore(s => (activeServerId ? s.audiomusePluginProbeByServer[activeServerId] : undefined));
useAuthStore(s => (activeServerId ? s.instantMixProbeByServer[activeServerId] : undefined));
useAuthStore(s => (activeServerId ? s.audiomuseNavidromeByServer[activeServerId] : undefined));
if (!server) {
return (
<PerfProbeMetricSection title="Active server" defaultOpen layout="stack">
<div className="perf-monitor-empty perf-monitor-empty--inline">
No server configured.
</div>
</PerfProbeMetricSection>
);
}
const navidrome = isNavidromeServer(identity);
const role = adminRoleBadge(adminRole);
const resolved: ResolvedCapability | null = activeServerId
? resolveFeatureForServer(activeServerId, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)
: null;
const audiomuseActive = activeServerId
? isFeatureActiveForServer(activeServerId, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)
: false;
const routes = activeServerId
? resolveCallRoutesForServer(activeServerId, FEATURE_AUDIOMUSE_SIMILAR_TRACKS, OP_SIMILAR_TRACKS)
: [];
const rows: PerfProbeDetailRow[] = [
{ label: 'Name', value: server.name || server.url },
{ label: 'Profile URL', value: <code className="perf-server-dl__code">{server.url}</code> },
{ label: 'Subsonic server', value: formatServerType(identity) },
{
label: 'OpenSubsonic',
value: identity?.openSubsonic
? <PerfProbeStatusBadge tone="ok">yes</PerfProbeStatusBadge>
: identity
? <PerfProbeStatusBadge tone="muted">no</PerfProbeStatusBadge>
: '—',
},
];
if (navidrome) {
rows.push({
label: 'Navidrome role',
value: <PerfProbeStatusBadge tone={role.tone}>{role.label}</PerfProbeStatusBadge>,
});
}
if (resolved && resolved.strategyId !== null && resolved.status !== 'ineligible') {
const detect = detectionBadge(resolved.status);
const trust = trustBadge(resolved.trust);
rows.push(
{
label: 'AudioMuse Instant Mix',
value: <PerfProbeStatusBadge tone={detect.tone}>{detect.label}</PerfProbeStatusBadge>,
},
{ label: 'Provider', value: <code className="perf-server-dl__code">{strategyLabel(resolved.strategyId)}</code> },
{
label: 'Detection trust',
value: <PerfProbeStatusBadge tone={trust.tone}>{trust.label}</PerfProbeStatusBadge>,
},
{
label: 'Mode',
value: audiomuseActive
? (
<PerfProbeStatusBadge tone="ok">
{resolved.activation === 'auto' ? 'active (auto)' : 'enabled in Settings'}
</PerfProbeStatusBadge>
)
: <PerfProbeStatusBadge tone="muted">off</PerfProbeStatusBadge>,
},
);
if (routes.length > 0) {
rows.push({
label: 'Call route',
value: <code className="perf-server-dl__code">{routes.map(r => r.endpoint).join(' → ')}</code>,
});
}
}
return (
<PerfProbeMetricSection title="Active server" defaultOpen layout="stack">
<PerfProbeDetailList rows={rows} />
</PerfProbeMetricSection>
);
}
+1
View File
@@ -156,6 +156,7 @@ const CONTRIBUTOR_ENTRIES = [
'Offline browse — local-bytes catalog when server is down, integration contract (context/policy/resolvers), disconnect nav fork, Home stale-cache feed, read-only context menus, PlayerBar rating/favorite guard (PR #1017)', 'Offline browse — local-bytes catalog when server is down, integration contract (context/policy/resolvers), disconnect nav fork, Home stale-cache feed, read-only context menus, PlayerBar rating/favorite guard (PR #1017)',
'Themed startup splash before Vite loads — deferred window show, per-theme logo gradient (PR #1030)', 'Themed startup splash before Vite loads — deferred window show, per-theme logo gradient (PR #1030)',
'Artist page: Top Tracks play when album list is empty on the page (PR #1031)', 'Artist page: Top Tracks play when album list is empty on the page (PR #1031)',
'PsyLab Connections tab with server capability readout, Navidrome admin-role probe, and tab-bar layout fix; server-capability framework with AudioMuse detection via OpenSubsonic sonicSimilarity and sonic Instant Mix routing on Navidrome ≥0.62 (PR #1033)',
], ],
}, },
{ {
+114
View File
@@ -0,0 +1,114 @@
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { renderHook, waitFor } from '@testing-library/react';
import { resetAuthStore } from '@/test/helpers/storeReset';
import { useAuthStore } from '@/store/authStore';
vi.mock('@/api/navidromeAdmin', () => ({
ndLogin: vi.fn(),
}));
import { ndLogin } from '@/api/navidromeAdmin';
import { useNavidromeAdminRole } from './useNavidromeAdminRole';
beforeEach(() => {
resetAuthStore();
vi.mocked(ndLogin).mockReset();
});
function seedNavidromeServer(): string {
const id = useAuthStore.getState().addServer({
name: 'Home',
url: 'music.example.com',
username: 'tester',
password: 'pw',
});
useAuthStore.getState().setActiveServer(id);
useAuthStore.getState().setLoggedIn(true);
useAuthStore.getState().setSubsonicServerIdentity(id, {
type: 'navidrome',
serverVersion: '0.62.0',
openSubsonic: true,
});
return id;
}
describe('useNavidromeAdminRole', () => {
it('returns na when not logged in', () => {
const id = useAuthStore.getState().addServer({
name: 'Home',
url: 'https://music.example.com',
username: 'tester',
password: 'pw',
});
useAuthStore.getState().setActiveServer(id);
useAuthStore.getState().setSubsonicServerIdentity(id, {
type: 'navidrome',
serverVersion: '0.62.0',
openSubsonic: true,
});
const { result } = renderHook(() => useNavidromeAdminRole());
expect(result.current).toBe('na');
expect(ndLogin).not.toHaveBeenCalled();
});
it('returns checking until server identity is known', () => {
const id = useAuthStore.getState().addServer({
name: 'Home',
url: 'https://music.example.com',
username: 'tester',
password: 'pw',
});
useAuthStore.getState().setActiveServer(id);
useAuthStore.getState().setLoggedIn(true);
const { result } = renderHook(() => useNavidromeAdminRole());
expect(result.current).toBe('checking');
expect(ndLogin).not.toHaveBeenCalled();
});
it('returns na for non-Navidrome servers', () => {
const id = useAuthStore.getState().addServer({
name: 'Ampache',
url: 'https://music.example.com',
username: 'tester',
password: 'pw',
});
useAuthStore.getState().setActiveServer(id);
useAuthStore.getState().setLoggedIn(true);
useAuthStore.getState().setSubsonicServerIdentity(id, {
type: 'ampache',
serverVersion: '6.0.0',
openSubsonic: false,
});
const { result } = renderHook(() => useNavidromeAdminRole());
expect(result.current).toBe('na');
expect(ndLogin).not.toHaveBeenCalled();
});
it('probes Navidrome native login and reports admin', async () => {
seedNavidromeServer();
vi.mocked(ndLogin).mockResolvedValue({ token: 't', userId: '1', isAdmin: true });
const { result } = renderHook(() => useNavidromeAdminRole());
await waitFor(() => expect(result.current).toBe('admin'));
expect(ndLogin).toHaveBeenCalledWith('http://music.example.com', 'tester', 'pw');
});
it('probes Navidrome native login and reports standard user', async () => {
seedNavidromeServer();
vi.mocked(ndLogin).mockResolvedValue({ token: 't', userId: '2', isAdmin: false });
const { result } = renderHook(() => useNavidromeAdminRole());
await waitFor(() => expect(result.current).toBe('user'));
});
it('returns error when native login fails', async () => {
seedNavidromeServer();
vi.mocked(ndLogin).mockRejectedValue(new Error('denied'));
const { result } = renderHook(() => useNavidromeAdminRole());
await waitFor(() => expect(result.current).toBe('error'));
});
});
+67
View File
@@ -0,0 +1,67 @@
import { useEffect, useState } from 'react';
import { ndLogin } from '../api/navidromeAdmin';
import { useAuthStore } from '../store/authStore';
import { isNavidromeServer } from '../utils/server/subsonicServerIdentity';
export type NavidromeAdminRole = 'idle' | 'checking' | 'admin' | 'user' | 'na' | 'error';
function normalizeServerUrl(url: string): string {
const withScheme = url.startsWith('http') ? url : `http://${url}`;
return withScheme.replace(/\/$/, '');
}
/**
* Probes Navidrome native login for the active server to learn whether the
* current Subsonic credentials belong to an admin account.
*/
export function useNavidromeAdminRole(): NavidromeAdminRole {
const isLoggedIn = useAuthStore(s => s.isLoggedIn);
const activeServerId = useAuthStore(s => s.activeServerId);
const server = useAuthStore(s => s.servers.find(srv => srv.id === s.activeServerId));
const identity = useAuthStore(s =>
activeServerId ? s.subsonicServerIdentityByServer[activeServerId] : undefined,
);
const [role, setRole] = useState<NavidromeAdminRole>('idle');
useEffect(() => {
if (!isLoggedIn || !server) {
setRole('na');
return;
}
if (!identity) {
setRole('checking');
return;
}
if (!isNavidromeServer(identity)) {
setRole('na');
return;
}
let cancelled = false;
setRole('checking');
const serverUrl = normalizeServerUrl(server.url);
ndLogin(serverUrl, server.username, server.password)
.then(res => {
if (cancelled) return;
setRole(res.isAdmin ? 'admin' : 'user');
})
.catch(() => {
if (!cancelled) setRole('error');
});
return () => {
cancelled = true;
};
}, [
isLoggedIn,
activeServerId,
server?.id,
server?.url,
server?.username,
server?.password,
identity?.type,
identity?.serverVersion,
]);
return role;
}
+4
View File
@@ -106,6 +106,10 @@ export const settings = {
userMgmtMagicStringModalDesc: 'Subsonic-Passwort für „{{username}}" eingeben — es wird in den kopierten Magic-String übernommen.', userMgmtMagicStringModalDesc: 'Subsonic-Passwort für „{{username}}" eingeben — es wird in den kopierten Magic-String übernommen.',
userMgmtMagicStringModalConfirm: 'String kopieren', userMgmtMagicStringModalConfirm: 'String kopieren',
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseStatusActive: 'Aktiv',
audiomuseStatusChecking: 'Wird geprüft…',
audiomuseStatusNotDetected: 'Nicht erkannt',
audiomuseStatusProbeFailed: 'Prüfung fehlgeschlagen',
audiomuseDesc: audiomuseDesc:
'Aktivieren, wenn dieser Server das <pluginLink>AudioMuse-AI-Navidrome-Plugin</pluginLink> nutzt. Schaltet Instant Mix pro Titel frei und nutzt ähnliche Künstler vom Server statt Last.fm auf Künstlerseiten.', 'Aktivieren, wenn dieser Server das <pluginLink>AudioMuse-AI-Navidrome-Plugin</pluginLink> nutzt. Schaltet Instant Mix pro Titel frei und nutzt ähnliche Künstler vom Server statt Last.fm auf Künstlerseiten.',
audiomuseIssueHint: audiomuseIssueHint:
+4
View File
@@ -108,6 +108,10 @@ export const settings = {
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseDesc: audiomuseDesc:
'Turn on if this server has the <pluginLink>AudioMuse-AI Navidrome plugin</pluginLink> configured. Enables Instant Mix from tracks and uses server-side similar artists instead of Last.fm on artist pages.', 'Turn on if this server has the <pluginLink>AudioMuse-AI Navidrome plugin</pluginLink> configured. Enables Instant Mix from tracks and uses server-side similar artists instead of Last.fm on artist pages.',
audiomuseStatusActive: 'Active',
audiomuseStatusChecking: 'Checking…',
audiomuseStatusNotDetected: 'Not detected',
audiomuseStatusProbeFailed: 'Probe failed',
audiomuseIssueHint: audiomuseIssueHint:
'Instant Mix failed recently — check the Navidrome plugin and AudioMuse API. Similar artists fall back to Last.fm when the server returns none.', 'Instant Mix failed recently — check the Navidrome plugin and AudioMuse API. Similar artists fall back to Last.fm when the server returns none.',
connected: 'Connected', connected: 'Connected',
+4
View File
@@ -105,6 +105,10 @@ export const settings = {
userMgmtMagicStringModalDesc: 'Introduce la contraseña Subsonic de «{{username}}». Se incluirá en la cadena mágica copiada.', userMgmtMagicStringModalDesc: 'Introduce la contraseña Subsonic de «{{username}}». Se incluirá en la cadena mágica copiada.',
userMgmtMagicStringModalConfirm: 'Copiar cadena', userMgmtMagicStringModalConfirm: 'Copiar cadena',
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseStatusActive: 'Activo',
audiomuseStatusChecking: 'Comprobando…',
audiomuseStatusNotDetected: 'No detectado',
audiomuseStatusProbeFailed: 'Error de comprobación',
audiomuseDesc: audiomuseDesc:
'Activa si este servidor tiene el plugin <pluginLink>AudioMuse-AI Navidrome</pluginLink> configurado. Habilita Mezcla Instantánea desde pistas y usa artistas similares del servidor en lugar de Last.fm en páginas de artistas.', 'Activa si este servidor tiene el plugin <pluginLink>AudioMuse-AI Navidrome</pluginLink> configurado. Habilita Mezcla Instantánea desde pistas y usa artistas similares del servidor en lugar de Last.fm en páginas de artistas.',
audiomuseIssueHint: audiomuseIssueHint:
+4
View File
@@ -105,6 +105,10 @@ export const settings = {
userMgmtMagicStringModalDesc: 'Saisissez le mot de passe Subsonic de « {{username}} ». Il est inclus dans la chaîne magique copiée.', userMgmtMagicStringModalDesc: 'Saisissez le mot de passe Subsonic de « {{username}} ». Il est inclus dans la chaîne magique copiée.',
userMgmtMagicStringModalConfirm: 'Copier la chaîne', userMgmtMagicStringModalConfirm: 'Copier la chaîne',
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseStatusActive: 'Actif',
audiomuseStatusChecking: 'Vérification…',
audiomuseStatusNotDetected: 'Non détecté',
audiomuseStatusProbeFailed: 'Échec de la détection',
audiomuseDesc: audiomuseDesc:
'Activez si ce serveur utilise le <pluginLink>plugin Navidrome AudioMuse-AI</pluginLink>. Active le mix instantané depuis un morceau et affiche les artistes similaires côté serveur au lieu de Last.fm sur les pages artiste.', 'Activez si ce serveur utilise le <pluginLink>plugin Navidrome AudioMuse-AI</pluginLink>. Active le mix instantané depuis un morceau et affiche les artistes similaires côté serveur au lieu de Last.fm sur les pages artiste.',
audiomuseIssueHint: audiomuseIssueHint:
+4
View File
@@ -105,6 +105,10 @@ export const settings = {
userMgmtMagicStringModalDesc: 'Skriv inn Subsonic-passordet for «{{username}}». Det tas med i den kopierte magic string-en.', userMgmtMagicStringModalDesc: 'Skriv inn Subsonic-passordet for «{{username}}». Det tas med i den kopierte magic string-en.',
userMgmtMagicStringModalConfirm: 'Kopier streng', userMgmtMagicStringModalConfirm: 'Kopier streng',
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseStatusActive: 'Aktiv',
audiomuseStatusChecking: 'Sjekker…',
audiomuseStatusNotDetected: 'Ikke oppdaget',
audiomuseStatusProbeFailed: 'Sjekk mislyktes',
audiomuseDesc: audiomuseDesc:
'Slå på hvis denne serveren bruker <pluginLink>AudioMuse-AI Navidrome-plugin</pluginLink>. Aktiverer Instant Mix fra spor og henter lignende artister fra serveren i stedet for Last.fm på artistsider.', 'Slå på hvis denne serveren bruker <pluginLink>AudioMuse-AI Navidrome-plugin</pluginLink>. Aktiverer Instant Mix fra spor og henter lignende artister fra serveren i stedet for Last.fm på artistsider.',
audiomuseIssueHint: audiomuseIssueHint:
+4
View File
@@ -105,6 +105,10 @@ export const settings = {
userMgmtMagicStringModalDesc: 'Voer het Subsonic-wachtwoord voor „{{username}}" in. Het wordt opgenomen in de gekopieerde magic string.', userMgmtMagicStringModalDesc: 'Voer het Subsonic-wachtwoord voor „{{username}}" in. Het wordt opgenomen in de gekopieerde magic string.',
userMgmtMagicStringModalConfirm: 'String kopiëren', userMgmtMagicStringModalConfirm: 'String kopiëren',
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseStatusActive: 'Actief',
audiomuseStatusChecking: 'Controleren…',
audiomuseStatusNotDetected: 'Niet gedetecteerd',
audiomuseStatusProbeFailed: 'Detectie mislukt',
audiomuseDesc: audiomuseDesc:
'Zet aan als deze server de <pluginLink>AudioMuse-AI Navidrome-plugin</pluginLink> gebruikt. Schakelt Instant Mix per nummer in en toont vergelijkbare artiesten van de server i.p.v. Last.fm op artiestpaginas.', 'Zet aan als deze server de <pluginLink>AudioMuse-AI Navidrome-plugin</pluginLink> gebruikt. Schakelt Instant Mix per nummer in en toont vergelijkbare artiesten van de server i.p.v. Last.fm op artiestpaginas.',
audiomuseIssueHint: audiomuseIssueHint:
+4
View File
@@ -105,6 +105,10 @@ export const settings = {
userMgmtMagicStringModalDesc: 'Introdu parola Subsonic pentru "{{username}}". Este inclusă în string-ul magic copiat.', userMgmtMagicStringModalDesc: 'Introdu parola Subsonic pentru "{{username}}". Este inclusă în string-ul magic copiat.',
userMgmtMagicStringModalConfirm: 'Copiază string-ul', userMgmtMagicStringModalConfirm: 'Copiază string-ul',
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseStatusActive: 'Activ',
audiomuseStatusChecking: 'Se verifică…',
audiomuseStatusNotDetected: 'Nedetectat',
audiomuseStatusProbeFailed: 'Verificare eșuată',
audiomuseDesc: audiomuseDesc:
'Pornește dacă acest server are <pluginLink>AudioMuse-AI Navidrome plugin</pluginLink> configurat. Activează Mixul Instant din piese si folosește artiști similari de pe partea de server în loc de Last.fm pe paginile de artiști.', 'Pornește dacă acest server are <pluginLink>AudioMuse-AI Navidrome plugin</pluginLink> configurat. Activează Mixul Instant din piese si folosește artiști similari de pe partea de server în loc de Last.fm pe paginile de artiști.',
audiomuseIssueHint: audiomuseIssueHint:
+4
View File
@@ -105,6 +105,10 @@ export const settings = {
userMgmtMagicStringModalDesc: 'Введите пароль Subsonic для «{{username}}» — он попадёт в копируемую magic string.', userMgmtMagicStringModalDesc: 'Введите пароль Subsonic для «{{username}}» — он попадёт в копируемую magic string.',
userMgmtMagicStringModalConfirm: 'Скопировать строку', userMgmtMagicStringModalConfirm: 'Скопировать строку',
audiomuseTitle: 'AudioMuse-AI (Navidrome)', audiomuseTitle: 'AudioMuse-AI (Navidrome)',
audiomuseStatusActive: 'Активно',
audiomuseStatusChecking: 'Проверка…',
audiomuseStatusNotDetected: 'Не обнаружено',
audiomuseStatusProbeFailed: 'Ошибка проверки',
audiomuseDesc: audiomuseDesc:
'Включите, если на этом сервере настроен <pluginLink>плагин AudioMuse-AI для Navidrome</pluginLink>. Появится Instant Mix для треков, а на странице исполнителя похожие будут браться с сервера вместо Last.fm.', 'Включите, если на этом сервере настроен <pluginLink>плагин AudioMuse-AI для Navidrome</pluginLink>. Появится Instant Mix для треков, а на странице исполнителя похожие будут браться с сервера вместо Last.fm.',
audiomuseIssueHint: audiomuseIssueHint:
+4
View File
@@ -105,6 +105,10 @@ export const settings = {
userMgmtMagicStringModalDesc: '请输入用户「{{username}}」的 Subsonic 密码,它会包含在复制的魔法字符串中。', userMgmtMagicStringModalDesc: '请输入用户「{{username}}」的 Subsonic 密码,它会包含在复制的魔法字符串中。',
userMgmtMagicStringModalConfirm: '复制字符串', userMgmtMagicStringModalConfirm: '复制字符串',
audiomuseTitle: 'AudioMuse-AINavidrome', audiomuseTitle: 'AudioMuse-AINavidrome',
audiomuseStatusActive: '已启用',
audiomuseStatusChecking: '检测中…',
audiomuseStatusNotDetected: '未检测到',
audiomuseStatusProbeFailed: '检测失败',
audiomuseDesc: audiomuseDesc:
'若此服务器已配置 <pluginLink>AudioMuse-AI Navidrome 插件</pluginLink>请开启。可从曲目启动即时混音,并在艺人页使用服务器返回的相似艺人,而非 Last.fm。', '若此服务器已配置 <pluginLink>AudioMuse-AI Navidrome 插件</pluginLink>请开启。可从曲目启动即时混音,并在艺人页使用服务器返回的相似艺人,而非 Last.fm。',
audiomuseIssueHint: audiomuseIssueHint:
+71
View File
@@ -0,0 +1,71 @@
import type { CapabilityDefinition } from './types';
/**
* Declarative map of server-side features, the strategies that can provide them
* per server generation, how to detect each, and which endpoint to route to.
*
* To add a feature with a new server path:
* 1. (optional) register a probe in `probes.ts` and map it in the orchestrator
* (`api/subsonic.ts`) + read facade (`storeView.ts`).
* 2. add a `CapabilityDefinition` here with one strategy per server generation.
* 3. consumers read it via `storeView` (UI) and the call router (runtime).
* No version `if` checks belong in UI or call sites they live here.
*/
export const SONIC_SIMILARITY_EXTENSION = 'sonicSimilarity';
export const FEATURE_AUDIOMUSE_SIMILAR_TRACKS = 'audiomuse.similarTracks';
export const PROBE_OPENSUBSONIC_EXTENSIONS = 'opensubsonic.extensions';
export const PROBE_LEGACY_INSTANT_MIX = 'navidrome.instantMix.legacy';
/** Operation names used by the call router. */
export const OP_SIMILAR_TRACKS = 'similarTracks';
export const SERVER_CAPABILITY_CATALOG: CapabilityDefinition[] = [
{
feature: FEATURE_AUDIOMUSE_SIMILAR_TRACKS,
labelKey: 'settings.audiomuseTitle',
strategies: [
{
// Navidrome ≥ 0.62: AudioMuse plugin advertised via OpenSubsonic.
id: 'opensubsonic.sonicSimilarity',
priority: 100,
when: (ctx) => ctx.isNavidrome && ctx.semverGte([0, 62, 0]),
detection: {
kind: 'extension',
probeId: PROBE_OPENSUBSONIC_EXTENSIONS,
extension: SONIC_SIMILARITY_EXTENSION,
},
trust: 'high',
activation: 'auto',
calls: {
[OP_SIMILAR_TRACKS]: { endpoint: 'getSonicSimilarTracks.view', transport: 'opensubsonic' },
},
labelKey: 'settings.audiomuseStrategySonic',
},
{
// Navidrome ≥ 0.60: legacy Instant Mix via getSimilarSongs (agents/plugin).
id: 'subsonic.getSimilarSongs',
priority: 50,
when: (ctx) => ctx.isNavidrome && ctx.semverGte([0, 60, 0]),
detection: {
kind: 'functional',
probeId: PROBE_LEGACY_INSTANT_MIX,
presentWhen: (outcome) => outcome.status === 'present',
},
trust: 'low',
activation: 'manual',
alwaysCallable: true,
calls: {
[OP_SIMILAR_TRACKS]: { endpoint: 'getSimilarSongs.view', transport: 'subsonic' },
},
labelKey: 'settings.audiomuseStrategyLegacy',
},
],
},
];
export function getCapabilityDefinition(feature: string): CapabilityDefinition | undefined {
return SERVER_CAPABILITY_CATALOG.find((d) => d.feature === feature);
}
+26
View File
@@ -0,0 +1,26 @@
import {
isNavidromeServer,
parseLeadingSemver,
type SubsonicServerIdentity,
} from '../utils/server/subsonicServerIdentity';
import type { CapabilityContext, Semver } from './types';
function semverGte(a: Semver, b: Semver): boolean {
for (let i = 0; i < 3; i++) {
if (a[i] > b[i]) return true;
if (a[i] < b[i]) return false;
}
return true;
}
/** Build the eligibility context for a connected server from its `ping` identity. */
export function buildCapabilityContext(identity: SubsonicServerIdentity | undefined): CapabilityContext {
const version = parseLeadingSemver(identity?.serverVersion);
return {
identity,
isNavidrome: isNavidromeServer(identity),
openSubsonic: !!identity?.openSubsonic,
version,
semverGte: (min) => (version ? semverGte(version, min) : false),
};
}
+117
View File
@@ -0,0 +1,117 @@
import { describe, expect, it } from 'vitest';
import { buildCapabilityContext } from './context';
import {
FEATURE_AUDIOMUSE_SIMILAR_TRACKS,
OP_SIMILAR_TRACKS,
PROBE_LEGACY_INSTANT_MIX,
PROBE_OPENSUBSONIC_EXTENSIONS,
SERVER_CAPABILITY_CATALOG,
SONIC_SIMILARITY_EXTENSION,
getCapabilityDefinition,
} from './catalog';
import {
isCapabilityActive,
neededProbeIds,
pickStrategy,
resolveCallChain,
resolveCapability,
} from './resolve';
import type { ProbeOutcome } from './types';
const def = getCapabilityDefinition(FEATURE_AUDIOMUSE_SIMILAR_TRACKS)!;
function ctxFor(version: string | undefined, type = 'navidrome') {
return buildCapabilityContext(version === undefined && type === ''
? undefined
: { type, serverVersion: version, openSubsonic: true });
}
const extPresent: ProbeOutcome = { status: 'present', extensions: [SONIC_SIMILARITY_EXTENSION] };
const extAbsent: ProbeOutcome = { status: 'present', extensions: [] };
describe('pickStrategy', () => {
it('chooses sonicSimilarity on Navidrome ≥ 0.62', () => {
expect(pickStrategy(def, ctxFor('0.62.0'))?.id).toBe('opensubsonic.sonicSimilarity');
});
it('chooses legacy getSimilarSongs on Navidrome 0.61', () => {
expect(pickStrategy(def, ctxFor('0.61.0'))?.id).toBe('subsonic.getSimilarSongs');
});
it('is ineligible on non-Navidrome', () => {
expect(pickStrategy(def, ctxFor('1.0.0', 'gonic'))).toBeNull();
});
it('is ineligible on Navidrome older than 0.60', () => {
expect(pickStrategy(def, ctxFor('0.59.9'))).toBeNull();
});
});
describe('neededProbeIds', () => {
it('asks for the extensions probe on 0.62+', () => {
const ids = neededProbeIds(SERVER_CAPABILITY_CATALOG, ctxFor('0.62.0'));
expect(ids.has(PROBE_OPENSUBSONIC_EXTENSIONS)).toBe(true);
expect(ids.has(PROBE_LEGACY_INSTANT_MIX)).toBe(false);
});
it('asks for the legacy probe on 0.61', () => {
const ids = neededProbeIds(SERVER_CAPABILITY_CATALOG, ctxFor('0.61.0'));
expect(ids.has(PROBE_LEGACY_INSTANT_MIX)).toBe(true);
expect(ids.has(PROBE_OPENSUBSONIC_EXTENSIONS)).toBe(false);
});
});
describe('resolveCapability', () => {
it('present when sonicSimilarity extension is advertised', () => {
const r = resolveCapability(def, ctxFor('0.62.0'), { [PROBE_OPENSUBSONIC_EXTENSIONS]: extPresent });
expect(r).toMatchObject({ strategyId: 'opensubsonic.sonicSimilarity', status: 'present', trust: 'high', activation: 'auto' });
});
it('absent when extensions list lacks sonicSimilarity', () => {
const r = resolveCapability(def, ctxFor('0.62.0'), { [PROBE_OPENSUBSONIC_EXTENSIONS]: extAbsent });
expect(r.status).toBe('absent');
});
it('error propagates from probe', () => {
const r = resolveCapability(def, ctxFor('0.62.0'), { [PROBE_OPENSUBSONIC_EXTENSIONS]: { status: 'error' } });
expect(r.status).toBe('error');
});
it('unknown when not yet probed', () => {
expect(resolveCapability(def, ctxFor('0.62.0'), {}).status).toBe('unknown');
});
it('legacy present when functional probe ok', () => {
const r = resolveCapability(def, ctxFor('0.61.0'), { [PROBE_LEGACY_INSTANT_MIX]: { status: 'present' } });
expect(r).toMatchObject({ strategyId: 'subsonic.getSimilarSongs', status: 'present', trust: 'low', activation: 'manual' });
});
it('ineligible on non-Navidrome', () => {
expect(resolveCapability(def, ctxFor('1.0.0', 'gonic'), {}).status).toBe('ineligible');
});
});
describe('isCapabilityActive', () => {
it('auto feature on iff detected present', () => {
const present = resolveCapability(def, ctxFor('0.62.0'), { [PROBE_OPENSUBSONIC_EXTENSIONS]: extPresent });
const absent = resolveCapability(def, ctxFor('0.62.0'), { [PROBE_OPENSUBSONIC_EXTENSIONS]: extAbsent });
expect(isCapabilityActive(present, false)).toBe(true);
expect(isCapabilityActive(absent, true)).toBe(false);
});
it('manual feature follows opt-in unless proven absent', () => {
const ok = resolveCapability(def, ctxFor('0.61.0'), { [PROBE_LEGACY_INSTANT_MIX]: { status: 'present' } });
const empty = resolveCapability(def, ctxFor('0.61.0'), { [PROBE_LEGACY_INSTANT_MIX]: { status: 'absent' } });
expect(isCapabilityActive(ok, true)).toBe(true);
expect(isCapabilityActive(ok, false)).toBe(false);
expect(isCapabilityActive(empty, true)).toBe(false);
});
});
describe('resolveCallChain (prefer sonic, fallback legacy)', () => {
it('0.62 with plugin → sonic then legacy', () => {
const chain = resolveCallChain(def, ctxFor('0.62.0'), { [PROBE_OPENSUBSONIC_EXTENSIONS]: extPresent }, OP_SIMILAR_TRACKS);
expect(chain.map(r => r.endpoint)).toEqual(['getSonicSimilarTracks.view', 'getSimilarSongs.view']);
});
it('0.62 without plugin → legacy only', () => {
const chain = resolveCallChain(def, ctxFor('0.62.0'), { [PROBE_OPENSUBSONIC_EXTENSIONS]: extAbsent }, OP_SIMILAR_TRACKS);
expect(chain.map(r => r.endpoint)).toEqual(['getSimilarSongs.view']);
});
it('0.61 → legacy only', () => {
const chain = resolveCallChain(def, ctxFor('0.61.0'), {}, OP_SIMILAR_TRACKS);
expect(chain.map(r => r.endpoint)).toEqual(['getSimilarSongs.view']);
});
it('non-Navidrome → empty', () => {
expect(resolveCallChain(def, ctxFor('1.0.0', 'gonic'), {}, OP_SIMILAR_TRACKS)).toEqual([]);
});
});
+109
View File
@@ -0,0 +1,109 @@
import type {
CapabilityCallRoute,
CapabilityContext,
CapabilityDefinition,
CapabilityStatus,
CapabilityStrategy,
ProbeOutcome,
ResolvedCapability,
StrategyDetection,
} from './types';
/** Strategies eligible for this server, strongest first. */
export function eligibleStrategies(
def: CapabilityDefinition,
ctx: CapabilityContext,
): CapabilityStrategy[] {
return def.strategies
.filter((s) => s.when(ctx))
.sort((a, b) => b.priority - a.priority);
}
/** The single strategy that owns this feature on the connected server. */
export function pickStrategy(
def: CapabilityDefinition,
ctx: CapabilityContext,
): CapabilityStrategy | null {
return eligibleStrategies(def, ctx)[0] ?? null;
}
/** Probe ids that need running for the selected strategy of each catalog feature. */
export function neededProbeIds(
catalog: CapabilityDefinition[],
ctx: CapabilityContext,
): Set<string> {
const ids = new Set<string>();
for (const def of catalog) {
const strategy = pickStrategy(def, ctx);
if (strategy) ids.add(strategy.detection.probeId);
}
return ids;
}
export function detectionStatus(
detection: StrategyDetection,
outcome: ProbeOutcome | undefined,
): CapabilityStatus {
if (!outcome) return 'unknown';
if (outcome.status === 'probing') return 'probing';
if (outcome.status === 'error') return 'error';
if (detection.kind === 'extension') {
if (outcome.status !== 'present') return 'absent';
return (outcome.extensions ?? []).includes(detection.extension) ? 'present' : 'absent';
}
return detection.presentWhen(outcome) ? 'present' : 'absent';
}
/** Resolve a feature's current state from catalog + probe outcomes. */
export function resolveCapability(
def: CapabilityDefinition,
ctx: CapabilityContext,
probes: Record<string, ProbeOutcome | undefined>,
): ResolvedCapability {
const strategy = pickStrategy(def, ctx);
if (!strategy) {
return { feature: def.feature, strategyId: null, status: 'ineligible', trust: null, activation: null };
}
const outcome = probes[strategy.detection.probeId];
return {
feature: def.feature,
strategyId: strategy.id,
status: detectionStatus(strategy.detection, outcome),
trust: strategy.trust,
activation: strategy.activation,
};
}
/**
* Whether a resolved feature is effectively on. Auto features follow detection;
* manual features follow the user opt-in unless detection proves them absent.
*/
export function isCapabilityActive(resolved: ResolvedCapability, userOptIn: boolean): boolean {
if (resolved.strategyId === null || resolved.status === 'ineligible') return false;
if (resolved.activation === 'auto') return resolved.status === 'present';
if (resolved.status === 'absent') return false;
return userOptIn;
}
/**
* Ordered call routes for an operation: strongest strategy first. A strategy is
* included when its detection is present, or when it is marked `alwaysCallable`
* (legacy fallback). Enables prefer-new-then-fallback routing.
*/
export function resolveCallChain(
def: CapabilityDefinition,
ctx: CapabilityContext,
probes: Record<string, ProbeOutcome | undefined>,
op: string,
): CapabilityCallRoute[] {
const routes: CapabilityCallRoute[] = [];
for (const strategy of eligibleStrategies(def, ctx)) {
const call = strategy.calls[op];
if (!call) continue;
const status = detectionStatus(strategy.detection, probes[strategy.detection.probeId]);
if (status === 'present' || strategy.alwaysCallable) {
routes.push({ strategyId: strategy.id, endpoint: call.endpoint, transport: call.transport });
}
}
return routes;
}
+67
View File
@@ -0,0 +1,67 @@
import { beforeEach, describe, expect, it } from 'vitest';
import { useAuthStore } from '../store/authStore';
import { FEATURE_AUDIOMUSE_SIMILAR_TRACKS, OP_SIMILAR_TRACKS } from './catalog';
import {
isFeatureActiveForServer,
resolveCallRoutesForServer,
resolveFeatureForServer,
} from './storeView';
const SID = 'srv-test';
function seed(identity: Record<string, unknown>, extra: Record<string, unknown> = {}) {
useAuthStore.setState({
subsonicServerIdentityByServer: { [SID]: identity as never },
audiomusePluginProbeByServer: {},
instantMixProbeByServer: {},
audiomuseNavidromeByServer: {},
...extra,
} as never);
}
describe('storeView (capability read facade)', () => {
beforeEach(() => {
useAuthStore.setState({
subsonicServerIdentityByServer: {},
audiomusePluginProbeByServer: {},
instantMixProbeByServer: {},
audiomuseNavidromeByServer: {},
} as never);
});
it('resolves sonic strategy as present from the plugin probe map', () => {
seed({ type: 'navidrome', serverVersion: '0.62.1', openSubsonic: true }, {
audiomusePluginProbeByServer: { [SID]: 'present' },
});
const resolved = resolveFeatureForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS);
expect(resolved).toMatchObject({ strategyId: 'opensubsonic.sonicSimilarity', status: 'present', activation: 'auto' });
expect(isFeatureActiveForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)).toBe(true);
expect(resolveCallRoutesForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS, OP_SIMILAR_TRACKS).map(r => r.endpoint))
.toEqual(['getSonicSimilarTracks.view', 'getSimilarSongs.view']);
});
it('resolves sonic absent → legacy-only route, feature off', () => {
seed({ type: 'navidrome', serverVersion: '0.62.1', openSubsonic: true }, {
audiomusePluginProbeByServer: { [SID]: 'absent' },
});
expect(resolveFeatureForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)?.status).toBe('absent');
expect(isFeatureActiveForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)).toBe(false);
expect(resolveCallRoutesForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS, OP_SIMILAR_TRACKS).map(r => r.endpoint))
.toEqual(['getSimilarSongs.view']);
});
it('legacy server: manual opt-in drives active state', () => {
seed({ type: 'navidrome', serverVersion: '0.61.0', openSubsonic: false }, {
instantMixProbeByServer: { [SID]: 'ok' },
audiomuseNavidromeByServer: { [SID]: true },
});
expect(resolveFeatureForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)?.strategyId).toBe('subsonic.getSimilarSongs');
expect(isFeatureActiveForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)).toBe(true);
});
it('non-Navidrome server resolves ineligible with no routes', () => {
seed({ type: 'gonic', serverVersion: '0.16.0', openSubsonic: true });
expect(resolveFeatureForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS)?.status).toBe('ineligible');
expect(resolveCallRoutesForServer(SID, FEATURE_AUDIOMUSE_SIMILAR_TRACKS, OP_SIMILAR_TRACKS)).toEqual([]);
});
});
+85
View File
@@ -0,0 +1,85 @@
import { useAuthStore } from '../store/authStore';
import type {
AudiomusePluginProbeResult,
InstantMixProbeResult,
} from '../utils/server/subsonicServerIdentity';
import { buildCapabilityContext } from './context';
import {
PROBE_LEGACY_INSTANT_MIX,
PROBE_OPENSUBSONIC_EXTENSIONS,
SONIC_SIMILARITY_EXTENSION,
getCapabilityDefinition,
} from './catalog';
import {
isCapabilityActive,
resolveCallChain,
resolveCapability,
} from './resolve';
import type {
CapabilityCallRoute,
ProbeOutcome,
ResolvedCapability,
} from './types';
/**
* Probe results currently live in dedicated per-server store maps. This facade
* maps them into the generic `ProbeOutcome` shape the resolver consumes, so the
* catalog/resolver/router stay storage-agnostic.
*/
function pluginProbeToOutcome(probe: AudiomusePluginProbeResult | undefined): ProbeOutcome | undefined {
switch (probe) {
case 'present': return { status: 'present', extensions: [SONIC_SIMILARITY_EXTENSION] };
case 'absent': return { status: 'present', extensions: [] };
case 'probing': return { status: 'probing' };
case 'error': return { status: 'error' };
default: return undefined;
}
}
function legacyProbeToOutcome(probe: InstantMixProbeResult | undefined): ProbeOutcome | undefined {
switch (probe) {
case 'ok': return { status: 'present' };
case 'empty':
case 'skipped': return { status: 'absent' };
case 'error': return { status: 'error' };
default: return undefined;
}
}
export function buildProbeOutcomesForServer(serverId: string): Record<string, ProbeOutcome | undefined> {
const s = useAuthStore.getState();
return {
[PROBE_OPENSUBSONIC_EXTENSIONS]: pluginProbeToOutcome(s.audiomusePluginProbeByServer[serverId]),
[PROBE_LEGACY_INSTANT_MIX]: legacyProbeToOutcome(s.instantMixProbeByServer[serverId]),
};
}
export function resolveFeatureForServer(
serverId: string,
feature: string,
): ResolvedCapability | null {
const def = getCapabilityDefinition(feature);
if (!def) return null;
const s = useAuthStore.getState();
const ctx = buildCapabilityContext(s.subsonicServerIdentityByServer[serverId]);
return resolveCapability(def, ctx, buildProbeOutcomesForServer(serverId));
}
export function isFeatureActiveForServer(serverId: string, feature: string): boolean {
const resolved = resolveFeatureForServer(serverId, feature);
if (!resolved) return false;
const userOptIn = !!useAuthStore.getState().audiomuseNavidromeByServer[serverId];
return isCapabilityActive(resolved, userOptIn);
}
export function resolveCallRoutesForServer(
serverId: string,
feature: string,
op: string,
): CapabilityCallRoute[] {
const def = getCapabilityDefinition(feature);
if (!def) return [];
const s = useAuthStore.getState();
const ctx = buildCapabilityContext(s.subsonicServerIdentityByServer[serverId]);
return resolveCallChain(def, ctx, buildProbeOutcomesForServer(serverId), op);
}
+92
View File
@@ -0,0 +1,92 @@
import type { SubsonicServerIdentity } from '../utils/server/subsonicServerIdentity';
export type Semver = [number, number, number];
/**
* Derived view of a connected server used by capability strategies to decide
* eligibility. Built once from the `ping` identity (see `context.ts`).
*/
export interface CapabilityContext {
identity: SubsonicServerIdentity | undefined;
isNavidrome: boolean;
openSubsonic: boolean;
version: Semver | null;
/** True when the connected server version is ≥ `min` (false when unknown). */
semverGte(min: Semver): boolean;
}
/** Raw outcome of a single probe (one network question against the server). */
export type ProbeStatus = 'probing' | 'present' | 'absent' | 'error';
export interface ProbeOutcome {
status: ProbeStatus;
/** OpenSubsonic extension names, for `extension`-kind detectors to read. */
extensions?: string[];
}
export type FeatureTrust = 'high' | 'low';
export type FeatureActivation = 'auto' | 'manual';
/** How a strategy decides it is actually available on the connected server. */
export type StrategyDetection =
| { kind: 'extension'; probeId: string; extension: string }
| { kind: 'functional'; probeId: string; presentWhen: (outcome: ProbeOutcome) => boolean };
/** A concrete API route a strategy can serve for a named operation. */
export interface CapabilityCall {
/** Subsonic REST endpoint, e.g. `getSonicSimilarTracks.view`. */
endpoint: string;
transport: 'subsonic' | 'opensubsonic';
}
/**
* One way to provide a feature on a given server generation. Higher `priority`
* wins when several strategies are eligible for the same server.
*/
export interface CapabilityStrategy {
id: string;
priority: number;
/** Eligible for the connected server type/version. */
when: (ctx: CapabilityContext) => boolean;
detection: StrategyDetection;
trust: FeatureTrust;
activation: FeatureActivation;
/** Operations this strategy can serve, keyed by operation name. */
calls: Record<string, CapabilityCall>;
/**
* Callable as a fallback even when detection is not satisfied e.g. legacy
* `getSimilarSongs` still answers via Last.fm / local agents.
*/
alwaysCallable?: boolean;
labelKey: string;
}
export interface CapabilityDefinition {
feature: string;
labelKey: string;
strategies: CapabilityStrategy[];
}
export type CapabilityStatus =
| 'ineligible'
| 'unknown'
| 'probing'
| 'present'
| 'absent'
| 'error';
/** Resolved per-server state for one feature, derived from catalog + probes. */
export interface ResolvedCapability {
feature: string;
strategyId: string | null;
status: CapabilityStatus;
trust: FeatureTrust | null;
activation: FeatureActivation | null;
}
/** An ordered call route returned by the router for a feature operation. */
export interface CapabilityCallRoute {
strategyId: string;
endpoint: string;
transport: 'subsonic' | 'opensubsonic';
}
+40 -4
View File
@@ -17,10 +17,9 @@ type SetState = (
* ping reveals the server isn't AudioMuse-eligible (wrong type or * ping reveals the server isn't AudioMuse-eligible (wrong type or
* too old), wipe the related caps for that id so the UI doesn't * too old), wipe the related caps for that id so the UI doesn't
* keep a stale toggle. * keep a stale toggle.
* - `setInstantMixProbe` probe result for getSimilarSongs. If * - `setInstantMixProbe` legacy probe (pre-0.62). If `empty`, wipe AudioMuse caps.
* `empty`, wipe the related AudioMuse caps so the row hides. * - `setAudiomusePluginProbe` Navidrome 0.62 `sonicSimilarity` extension probe.
* - `setAudiomuseNavidromeIssue` set/clear the "current session * - `setAudiomuseNavidromeIssue` set/clear the "current session saw a failure" flag.
* saw a failure" flag.
*/ */
export function createPerServerCapabilityActions(set: SetState): Pick< export function createPerServerCapabilityActions(set: SetState): Pick<
AuthState, AuthState,
@@ -28,6 +27,7 @@ export function createPerServerCapabilityActions(set: SetState): Pick<
| 'setAudiomuseNavidromeEnabled' | 'setAudiomuseNavidromeEnabled'
| 'setSubsonicServerIdentity' | 'setSubsonicServerIdentity'
| 'setInstantMixProbe' | 'setInstantMixProbe'
| 'setAudiomusePluginProbe'
| 'setAudiomuseNavidromeIssue' | 'setAudiomuseNavidromeIssue'
> { > {
return { return {
@@ -50,16 +50,31 @@ export function createPerServerCapabilityActions(set: SetState): Pick<
setSubsonicServerIdentity: (serverId, identity) => setSubsonicServerIdentity: (serverId, identity) =>
set(s => { set(s => {
const prev = s.subsonicServerIdentityByServer[serverId];
const subsonicServerIdentityByServer = { ...s.subsonicServerIdentityByServer, [serverId]: { ...identity } }; const subsonicServerIdentityByServer = { ...s.subsonicServerIdentityByServer, [serverId]: { ...identity } };
if (!isNavidromeAudiomuseSoftwareEligible(identity)) { if (!isNavidromeAudiomuseSoftwareEligible(identity)) {
const { [serverId]: _a, ...audiomuseRest } = s.audiomuseNavidromeByServer; const { [serverId]: _a, ...audiomuseRest } = s.audiomuseNavidromeByServer;
const { [serverId]: _i, ...issueRest } = s.audiomuseNavidromeIssueByServer; const { [serverId]: _i, ...issueRest } = s.audiomuseNavidromeIssueByServer;
const { [serverId]: _p, ...probeRest } = s.instantMixProbeByServer; const { [serverId]: _p, ...probeRest } = s.instantMixProbeByServer;
const { [serverId]: _pp, ...pluginProbeRest } = s.audiomusePluginProbeByServer;
return { return {
subsonicServerIdentityByServer, subsonicServerIdentityByServer,
audiomuseNavidromeByServer: audiomuseRest, audiomuseNavidromeByServer: audiomuseRest,
audiomuseNavidromeIssueByServer: issueRest, audiomuseNavidromeIssueByServer: issueRest,
instantMixProbeByServer: probeRest, instantMixProbeByServer: probeRest,
audiomusePluginProbeByServer: pluginProbeRest,
};
}
// Server generation changed (version/type) → drop cached capability probes
// so the next probe re-runs against the new generation. The user opt-in
// (`audiomuseNavidromeByServer`) is preserved.
if (prev && (prev.serverVersion !== identity.serverVersion || prev.type !== identity.type)) {
const { [serverId]: _p, ...probeRest } = s.instantMixProbeByServer;
const { [serverId]: _pp, ...pluginProbeRest } = s.audiomusePluginProbeByServer;
return {
subsonicServerIdentityByServer,
instantMixProbeByServer: probeRest,
audiomusePluginProbeByServer: pluginProbeRest,
}; };
} }
return { subsonicServerIdentityByServer }; return { subsonicServerIdentityByServer };
@@ -80,6 +95,27 @@ export function createPerServerCapabilityActions(set: SetState): Pick<
return { instantMixProbeByServer }; return { instantMixProbeByServer };
}), }),
setAudiomusePluginProbe: (serverId, result) =>
set(s => {
const audiomusePluginProbeByServer = { ...s.audiomusePluginProbeByServer, [serverId]: result };
if (result === 'present') {
return {
audiomusePluginProbeByServer,
audiomuseNavidromeByServer: { ...s.audiomuseNavidromeByServer, [serverId]: true },
};
}
if (result === 'absent' || result === 'error') {
const { [serverId]: _a, ...audiomuseRest } = s.audiomuseNavidromeByServer;
const { [serverId]: _i, ...issueRest } = s.audiomuseNavidromeIssueByServer;
return {
audiomusePluginProbeByServer,
audiomuseNavidromeByServer: audiomuseRest,
audiomuseNavidromeIssueByServer: issueRest,
};
}
return { audiomusePluginProbeByServer };
}),
setAudiomuseNavidromeIssue: (serverId, hasIssue) => setAudiomuseNavidromeIssue: (serverId, hasIssue) =>
set(s => set(s =>
hasIssue hasIssue
+2
View File
@@ -56,6 +56,7 @@ export function createServerProfileActions(set: SetState): Pick<
const { [id]: _idn, ...identityRest } = s.subsonicServerIdentityByServer; const { [id]: _idn, ...identityRest } = s.subsonicServerIdentityByServer;
const { [id]: _iss, ...issueRest } = s.audiomuseNavidromeIssueByServer; const { [id]: _iss, ...issueRest } = s.audiomuseNavidromeIssueByServer;
const { [id]: _pr, ...probeRest } = s.instantMixProbeByServer; const { [id]: _pr, ...probeRest } = s.instantMixProbeByServer;
const { [id]: _ppl, ...pluginProbeRest } = s.audiomusePluginProbeByServer;
return { return {
servers: newServers, servers: newServers,
activeServerId: switchedAway ? (newServers[0]?.id ?? null) : s.activeServerId, activeServerId: switchedAway ? (newServers[0]?.id ?? null) : s.activeServerId,
@@ -65,6 +66,7 @@ export function createServerProfileActions(set: SetState): Pick<
subsonicServerIdentityByServer: identityRest, subsonicServerIdentityByServer: identityRest,
audiomuseNavidromeIssueByServer: issueRest, audiomuseNavidromeIssueByServer: issueRest,
instantMixProbeByServer: probeRest, instantMixProbeByServer: probeRest,
audiomusePluginProbeByServer: pluginProbeRest,
}; };
}); });
}, },
+12
View File
@@ -255,6 +255,18 @@ describe('per-server bookkeeping setters', () => {
'srv-1': true, 'srv-1': true,
}); });
}); });
it('setAudiomusePluginProbe auto-enables AudioMuse when sonicSimilarity is present', () => {
useAuthStore.getState().setAudiomusePluginProbe('srv-1', 'present');
expect(useAuthStore.getState().audiomusePluginProbeByServer).toEqual({ 'srv-1': 'present' });
expect(useAuthStore.getState().audiomuseNavidromeByServer).toEqual({ 'srv-1': true });
});
it('setAudiomusePluginProbe clears AudioMuse when the extension is absent', () => {
useAuthStore.getState().setAudiomuseNavidromeEnabled('srv-1', true);
useAuthStore.getState().setAudiomusePluginProbe('srv-1', 'absent');
expect(useAuthStore.getState().audiomuseNavidromeByServer).toEqual({});
});
}); });
describe('genre blacklist + audio output device', () => { describe('genre blacklist + audio output device', () => {
+1
View File
@@ -121,6 +121,7 @@ export const useAuthStore = create<AuthState>()(
subsonicServerIdentityByServer: {}, subsonicServerIdentityByServer: {},
audiomuseNavidromeIssueByServer: {}, audiomuseNavidromeIssueByServer: {},
instantMixProbeByServer: {}, instantMixProbeByServer: {},
audiomusePluginProbeByServer: {},
isLoggedIn: false, isLoggedIn: false,
isConnecting: false, isConnecting: false,
connectionError: null, connectionError: null,
+10 -2
View File
@@ -1,5 +1,6 @@
import type { EntityRatingSupportLevel } from '../api/subsonicTypes'; import type { EntityRatingSupportLevel } from '../api/subsonicTypes';
import type { import type {
AudiomusePluginProbeResult,
InstantMixProbeResult, InstantMixProbeResult,
SubsonicServerIdentity, SubsonicServerIdentity,
} from '../utils/server/subsonicServerIdentity'; } from '../utils/server/subsonicServerIdentity';
@@ -250,7 +251,8 @@ export interface AuthState {
setEntityRatingSupport: (serverId: string, level: EntityRatingSupportLevel) => void; setEntityRatingSupport: (serverId: string, level: EntityRatingSupportLevel) => void;
/** /**
* Per server: Navidrome has the AudioMuse-AI plugin use `getSimilarSongs` (Instant Mix) and * Per server: AudioMuse-AI features active manual opt-in on pre-0.62 Navidrome; auto-set on
* 0.62+ when `sonicSimilarity` probe is `present`. Uses `getSimilarSongs` (Instant Mix) and
* `getArtistInfo2` similar artists instead of Last.fm for discovery on this server. * `getArtistInfo2` similar artists instead of Last.fm for discovery on this server.
*/ */
audiomuseNavidromeByServer: Record<string, boolean>; audiomuseNavidromeByServer: Record<string, boolean>;
@@ -265,11 +267,17 @@ export interface AuthState {
setAudiomuseNavidromeIssue: (serverId: string, hasIssue: boolean) => void; setAudiomuseNavidromeIssue: (serverId: string, hasIssue: boolean) => void;
/** /**
* `getSimilarSongs` probe per server (after ping). `empty` hides the AudioMuse row; re-run by testing connection. * `getSimilarSongs` probe per server (after ping). `empty` hides the AudioMuse row on pre-0.62 Navidrome.
*/ */
instantMixProbeByServer: Record<string, InstantMixProbeResult>; instantMixProbeByServer: Record<string, InstantMixProbeResult>;
setInstantMixProbe: (serverId: string, result: InstantMixProbeResult) => void; setInstantMixProbe: (serverId: string, result: InstantMixProbeResult) => void;
/**
* Navidrome 0.62: `sonicSimilarity` extension probe (`present` = AudioMuse-style plugin active).
*/
audiomusePluginProbeByServer: Record<string, AudiomusePluginProbeResult>;
setAudiomusePluginProbe: (serverId: string, result: AudiomusePluginProbeResult) => void;
// Status // Status
isLoggedIn: boolean; isLoggedIn: boolean;
isConnecting: boolean; isConnecting: boolean;
+134 -2
View File
@@ -95,21 +95,28 @@
.sidebar-perf-modal__tabs { .sidebar-perf-modal__tabs {
display: flex; display: flex;
gap: 6px; flex: 0 0 auto;
flex-shrink: 0;
gap: 4px;
margin: 12px 0 10px; margin: 12px 0 10px;
padding: 4px; padding: 4px;
border-radius: 12px; border-radius: 12px;
background: color-mix(in srgb, var(--bg-card, var(--bg-app)) 88%, transparent); background: color-mix(in srgb, var(--bg-card, var(--bg-app)) 88%, transparent);
border: 1px solid color-mix(in srgb, var(--text-muted) 18%, transparent); border: 1px solid color-mix(in srgb, var(--text-muted) 18%, transparent);
overflow-x: auto;
scrollbar-width: thin;
} }
.sidebar-perf-modal__tab { .sidebar-perf-modal__tab {
flex: 1; flex: 0 0 auto;
min-width: 4.5rem;
min-height: 2.25rem;
display: inline-flex; display: inline-flex;
align-items: center; align-items: center;
justify-content: center; justify-content: center;
gap: 6px; gap: 6px;
padding: 8px 10px; padding: 8px 10px;
white-space: nowrap;
border: none; border: none;
border-radius: 9px; border-radius: 9px;
background: transparent; background: transparent;
@@ -312,6 +319,130 @@
font-size: 11px; font-size: 11px;
} }
.perf-metric-section__body {
padding: 0 10px 10px;
}
.perf-conn-summary {
display: flex;
flex-wrap: wrap;
gap: 8px;
margin-bottom: 12px;
padding: 10px;
border-radius: 12px;
border: 1px solid color-mix(in srgb, var(--text-muted) 16%, transparent);
background: color-mix(in srgb, var(--bg-card, var(--bg-app)) 88%, transparent);
}
.perf-conn-summary__item {
display: flex;
flex-direction: column;
align-items: flex-start;
gap: 4px;
min-width: 88px;
flex: 1 1 auto;
}
.perf-conn-summary__label {
font-size: 10px;
font-weight: 600;
letter-spacing: 0.05em;
text-transform: uppercase;
color: color-mix(in srgb, var(--text-muted) 90%, transparent);
}
.perf-status-badge {
display: inline-flex;
align-items: center;
gap: 4px;
padding: 2px 8px;
border-radius: 999px;
font-size: 11px;
font-weight: 600;
line-height: 1.35;
border: 1px solid transparent;
white-space: nowrap;
}
.perf-status-badge--ok {
color: #9ece6a;
background: color-mix(in srgb, #9ece6a 14%, transparent);
border-color: color-mix(in srgb, #9ece6a 28%, transparent);
}
.perf-status-badge--warn {
color: #e0af68;
background: color-mix(in srgb, #e0af68 14%, transparent);
border-color: color-mix(in srgb, #e0af68 28%, transparent);
}
.perf-status-badge--error {
color: #f7768e;
background: color-mix(in srgb, #f7768e 14%, transparent);
border-color: color-mix(in srgb, #f7768e 28%, transparent);
}
.perf-status-badge--neutral {
color: #7aa2f7;
background: color-mix(in srgb, #7aa2f7 14%, transparent);
border-color: color-mix(in srgb, #7aa2f7 28%, transparent);
}
.perf-status-badge--muted {
color: var(--text-muted);
background: color-mix(in srgb, var(--text-muted) 10%, transparent);
border-color: color-mix(in srgb, var(--text-muted) 20%, transparent);
}
.perf-server-dl {
margin: 0;
padding: 0;
display: flex;
flex-direction: column;
gap: 0;
font-size: 12px;
border-radius: 10px;
border: 1px solid color-mix(in srgb, var(--text-muted) 12%, transparent);
overflow: hidden;
}
.perf-server-dl__row {
display: grid;
grid-template-columns: minmax(110px, 38%) 1fr;
gap: 8px 12px;
align-items: center;
padding: 8px 10px;
border-top: 1px solid color-mix(in srgb, var(--text-muted) 10%, transparent);
}
.perf-server-dl__row:first-child {
border-top: none;
}
.perf-server-dl__row:nth-child(even) {
background: color-mix(in srgb, var(--bg-sidebar, var(--bg-app)) 40%, transparent);
}
.perf-server-dl__row dt {
margin: 0;
color: var(--text-muted);
font-weight: 500;
font-size: 11px;
}
.perf-server-dl__row dd {
margin: 0;
color: var(--text-primary, var(--text));
word-break: break-word;
}
.perf-server-dl__code {
font-family: ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, monospace;
font-size: 11px;
color: color-mix(in srgb, var(--text-primary, var(--text)) 92%, var(--accent));
word-break: break-all;
}
.perf-live-poll { .perf-live-poll {
margin-bottom: 12px; margin-bottom: 12px;
padding: 10px 12px; padding: 10px 12px;
@@ -907,6 +1038,7 @@
} }
.sidebar-perf-modal__actions { .sidebar-perf-modal__actions {
flex-shrink: 0;
margin-top: 14px; margin-top: 14px;
display: flex; display: flex;
justify-content: flex-end; justify-content: flex-end;
@@ -1,6 +1,6 @@
import { join } from '@tauri-apps/api/path'; import { join } from '@tauri-apps/api/path';
import { invoke } from '@tauri-apps/api/core'; import { invoke } from '@tauri-apps/api/core';
import { getSimilarSongs2, getSimilarSongs, getTopSongs } from '../../api/subsonicArtists'; import { getSimilarSongs2, fetchSimilarTracksRouted, getTopSongs } from '../../api/subsonicArtists';
import { filterSongsForLuckyMixRatings, getMixMinRatingsConfigFromAuth } from '../mix/mixRatingFilter'; import { filterSongsForLuckyMixRatings, getMixMinRatingsConfigFromAuth } from '../mix/mixRatingFilter';
import { buildDownloadUrl } from '../../api/subsonicStreamUrl'; import { buildDownloadUrl } from '../../api/subsonicStreamUrl';
import { useAuthStore } from '../../store/authStore'; import { useAuthStore } from '../../store/authStore';
@@ -112,7 +112,7 @@ export async function startInstantMix(
usePlayerStore.getState().reseedQueueForInstantMix(song); usePlayerStore.getState().reseedQueueForInstantMix(song);
const serverId = useAuthStore.getState().activeServerId; const serverId = useAuthStore.getState().activeServerId;
try { try {
const similar = await getSimilarSongs(song.id, 50); const similar = await fetchSimilarTracksRouted(song.id, 50);
if (serverId) useAuthStore.getState().setAudiomuseNavidromeIssue(serverId, false); if (serverId) useAuthStore.getState().setAudiomuseNavidromeIssue(serverId, false);
const mixCfg = getMixMinRatingsConfigFromAuth(); const mixCfg = getMixMinRatingsConfigFromAuth();
const ratedFiltered = await filterSongsForLuckyMixRatings( const ratedFiltered = await filterSongsForLuckyMixRatings(
+2 -2
View File
@@ -1,4 +1,4 @@
import { getSimilarSongs } from '../../api/subsonicArtists'; import { fetchSimilarTracksRouted } from '../../api/subsonicArtists';
import { filterSongsToActiveLibrary, getRandomSongs } from '../../api/subsonicLibrary'; import { filterSongsToActiveLibrary, getRandomSongs } from '../../api/subsonicLibrary';
import type { SubsonicAlbum, SubsonicSong } from '../../api/subsonicTypes'; import type { SubsonicAlbum, SubsonicSong } from '../../api/subsonicTypes';
import type { QueueItemRef } from '../../store/playerStoreTypes'; import type { QueueItemRef } from '../../store/playerStoreTypes';
@@ -292,7 +292,7 @@ export async function buildAndPlayLuckyMix(): Promise<void> {
for (let i = 0; i < seeds.length; i++) { for (let i = 0; i < seeds.length; i++) {
bailIfCancelled(); bailIfCancelled();
const seed = seeds[i]; const seed = seeds[i];
const oneRaw = await getSimilarSongs(seed.id, 60).catch(() => [] as SubsonicSong[]); const oneRaw = await fetchSimilarTracksRouted(seed.id, 60).catch(() => [] as SubsonicSong[]);
const oneScoped = await filterSongsToActiveLibrary(oneRaw); const oneScoped = await filterSongsToActiveLibrary(oneRaw);
similarRaw = uniqueAppend(similarRaw, oneRaw); similarRaw = uniqueAppend(similarRaw, oneRaw);
similar = uniqueAppend(similar, oneScoped); similar = uniqueAppend(similar, oneScoped);
@@ -0,0 +1,40 @@
import { describe, expect, it } from 'vitest';
import {
isNavidromeAudiomuseSoftwareEligible,
isNavidromeServer,
parseLeadingSemver,
} from './subsonicServerIdentity';
describe('parseLeadingSemver', () => {
it('parses Navidrome-style version strings', () => {
expect(parseLeadingSemver('0.62.0 (2026-06-08)')).toEqual([0, 62, 0]);
expect(parseLeadingSemver('v0.61.2')).toEqual([0, 61, 2]);
});
it('returns null for unparseable input', () => {
expect(parseLeadingSemver(undefined)).toBeNull();
expect(parseLeadingSemver('unknown')).toBeNull();
});
});
describe('isNavidromeServer', () => {
it('matches the navidrome type case-insensitively', () => {
expect(isNavidromeServer({ type: 'navidrome' })).toBe(true);
expect(isNavidromeServer({ type: 'Navidrome' })).toBe(true);
expect(isNavidromeServer({ type: 'gonic' })).toBe(false);
expect(isNavidromeServer(undefined)).toBe(false);
});
});
describe('isNavidromeAudiomuseSoftwareEligible', () => {
it('is permissive until a typed ping arrives', () => {
expect(isNavidromeAudiomuseSoftwareEligible(undefined)).toBe(true);
expect(isNavidromeAudiomuseSoftwareEligible({})).toBe(true);
});
it('requires Navidrome ≥ 0.60 once metadata is known', () => {
expect(isNavidromeAudiomuseSoftwareEligible({ type: 'navidrome', serverVersion: '0.60.0' })).toBe(true);
expect(isNavidromeAudiomuseSoftwareEligible({ type: 'navidrome', serverVersion: '0.59.9' })).toBe(false);
expect(isNavidromeAudiomuseSoftwareEligible({ type: 'gonic', serverVersion: '1.0.0' })).toBe(false);
});
});
+17 -17
View File
@@ -8,9 +8,19 @@ export type SubsonicServerIdentity = {
/** Result of `getRandomSongs` + `getSimilarSongs` probe (Instant Mix / agent chain). */ /** Result of `getRandomSongs` + `getSimilarSongs` probe (Instant Mix / agent chain). */
export type InstantMixProbeResult = 'ok' | 'empty' | 'error' | 'skipped'; export type InstantMixProbeResult = 'ok' | 'empty' | 'error' | 'skipped';
/**
* Navidrome 0.62 exposes the OpenSubsonic `sonicSimilarity` extension when an audio-similarity
* plugin (e.g. AudioMuse-AI) is active the first reliable plugin signal.
*/
export type AudiomusePluginProbeResult =
| 'probing'
| 'present'
| 'absent'
| 'error';
const NAVIDROME_MIN_FOR_PLUGINS: [number, number, number] = [0, 60, 0]; const NAVIDROME_MIN_FOR_PLUGINS: [number, number, number] = [0, 60, 0];
function parseLeadingSemver(version: string | undefined): [number, number, number] | null { export function parseLeadingSemver(version: string | undefined): [number, number, number] | null {
if (!version) return null; if (!version) return null;
const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(version).trim()); const m = /^v?(\d+)\.(\d+)\.(\d+)/.exec(String(version).trim());
if (!m) return null; if (!m) return null;
@@ -25,29 +35,19 @@ function semverGte(a: [number, number, number], b: [number, number, number]): bo
return true; return true;
} }
export function isNavidromeServer(identity: SubsonicServerIdentity | undefined): boolean {
if (!identity?.type?.trim()) return false;
return identity.type.trim().toLowerCase() === 'navidrome';
}
/** /**
* Navidrome version from ping supports the plugin system ( 0.60). Unknown `type` stays permissive * Navidrome version from ping supports the plugin system ( 0.60). Unknown `type` stays permissive
* until the first successful ping with metadata. * until the first successful ping with metadata.
*/ */
export function isNavidromeAudiomuseSoftwareEligible(identity: SubsonicServerIdentity | undefined): boolean { export function isNavidromeAudiomuseSoftwareEligible(identity: SubsonicServerIdentity | undefined): boolean {
if (!identity?.type?.trim()) return true; if (!identity?.type?.trim()) return true;
const t = identity.type.trim().toLowerCase(); if (!isNavidromeServer(identity)) return false;
if (t !== 'navidrome') return false;
const parsed = parseLeadingSemver(identity.serverVersion); const parsed = parseLeadingSemver(identity.serverVersion);
if (!parsed) return true; if (!parsed) return true;
return semverGte(parsed, NAVIDROME_MIN_FOR_PLUGINS); return semverGte(parsed, NAVIDROME_MIN_FOR_PLUGINS);
} }
/**
* Whether to show the per-server AudioMuse (Navidrome plugin) toggle in Settings.
* Uses software eligibility from ping plus an optional Instant Mix probe: if the server returns no
* similar tracks for several random songs, the row stays hidden (typical when no plugin / no agents).
*/
export function showAudiomuseNavidromeServerSetting(
identity: SubsonicServerIdentity | undefined,
instantMixProbe: InstantMixProbeResult | undefined,
): boolean {
if (!isNavidromeAudiomuseSoftwareEligible(identity)) return false;
if (instantMixProbe === 'empty') return false;
return true;
}