feat: Minstrel stops acquiring music and drops Discover
release / go (push) Successful in 1m54s
release / web (push) Failing after 5s
release / integration (push) Failing after 3m44s
release / govulncheck (push) Successful in 20s
release / Attach APK to the Release (tag releases only) (push) Canceled after 0s
release / Build + push container image (push) Canceled after 0s
release / Verify release artifacts (tag releases only) (push) Canceled after 0s
release / Build signed APK (push) Canceled after 19s
release / android (push) Canceled after 2m37s

Minstrel is now a viewer of the library it is pointed at. Finding,
downloading and filing music moves out of it.

Removed from the server:
- the request flow (requests, approval, auto-approve) and the wanted list,
  follows, release profiles and release blocks;
- searching indexers, the download clients, the importer, the album
  lifecycle and missing-file re-acquisition;
- the catalogue's discography, search and art (the MusicBrainz release and
  track-list cache stays, for the duplicate resolver);
- Discover: its suggestions of artists not in the library, snoozes, the
  candidate-artist tag enrichment and its tuning scope;
- writes to acquisition tables from moving the library folder and from
  merging duplicates, the want-list join on Suspect sources, the sealing of
  acquisition credentials, and the release-group lookup only
  re-acquisition used.

Settling a wrong-slot duplicate no longer sets the release aside: the
copies go and their slots show as missing until a good copy is in the
library.

Removed from the web: Admin > Acquisition and Requests, /requests,
/discover, Follow on the artist page, the auto-approve toggle, and the
Collection's wanted-list tabs. The Collection is now the library's health:
an overview, Reports, Duplicates, Suspect sources and Missing files. The
README and docs no longer describe getting music.

The tables stay for now; a later migration drops them. The request
notification kinds and the Android screens are still to go.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
2026-11-21 20:51:14 -05:00
co-authored by Claude Opus 5.5
parent dabe1e052d
commit 55c7497ca7
277 changed files with 521 additions and 40021 deletions
+3 -25
View File
@@ -1,43 +1,21 @@
<script lang="ts">
import { untrack } from 'svelte';
import { page } from '$app/state';
import SectionRail, { type RailItem } from '#lib/components/SectionRail.svelte';
import { createAdminSummaryQuery } from '#lib/api/admin.js';
import { countOf } from '#lib/admin/queues.js';
let { children } = $props<{ children: import('svelte').Snippet }>();
// Admin: one page per section down a left rail, as Settings and
// the Collection are, so the sections sit in the same place everywhere
// and fit a phone. Each queue carries how many wait on you, from one
// summary read that is refreshed whenever you move between admin pages.
// The library's health queues are under Collection.
const summaryStore = createAdminSummaryQuery();
const summary = $derived($summaryStore.data);
// Refetch when the admin moves to another admin page, where they may have
// just cleared something. Not on first mount (the query is fetching
// already), and untracked, so the refetch's own result doesn't loop.
let lastPath = page.url.pathname;
$effect(() => {
const path = page.url.pathname;
if (path === lastPath) return;
lastPath = path;
untrack(() => $summaryStore.refetch?.());
});
const items: RailItem[] = $derived([
// and fit a phone. The library's health queues are under Collection.
const items: RailItem[] = [
{ href: '/admin', label: 'Overview', exact: true },
{ href: '/admin/requests', label: 'Requests', attention: countOf(summary, 'requests') },
{ href: '/admin/library', label: 'Library' },
{ href: '/admin/acquisition', label: 'Acquisition' },
{ href: '/admin/metadata', label: 'Metadata sources' },
{ href: '/admin/email', label: 'Email & network' },
{ href: '/admin/users', label: 'Users' },
{ href: '/admin/backups', label: 'Backups' },
{ href: '/admin/diagnostics', label: 'Diagnostics' },
{ href: '/admin/tuning', label: 'Tuning' }
]);
];
</script>
<div class="space-y-4">
+4 -47
View File
@@ -5,19 +5,16 @@
import { relativeTime } from '#lib/utils/relativeTime.js';
import { formatBytes } from '#lib/utils/bytes.js';
import { QUEUES, countOf, queueLabel } from '#lib/admin/queues.js';
import { liveDownloadLine } from '#lib/wanted/downloadState.js';
import type { Download } from '#lib/api/types.js';
// The admin Overview answers "does anything need me?" first: a
// verdict, then each queue that waits on you with how long its oldest has
// waited, then the empty ones on one line. The queues themselves
// are worked on their own pages; the Overview does not repeat them.
//
// Below the verdict, the server's state: who is listening, what is
// downloading, what the library holds and how much room is left, and the
// server's version, uptime and recent errors. A download waiting on you, a
// download client not answering, or a library folder unreadable or nearly
// full also count in the verdict.
// Below the verdict, the server's state: who is listening, what the
// library holds and how much room is left, and the server's version,
// uptime and recent errors. A library folder unreadable or nearly full also
// counts in the verdict.
const summaryStore = createAdminSummaryQuery();
const summaryQ = $derived($summaryStore);
@@ -44,18 +41,6 @@
const statusProblems = $derived.by((): Problem[] => {
if (!status) return [];
const out: Problem[] = [];
const dl = status.downloads;
if (dl.needs_you > 0) {
out.push({
key: 'downloads',
text: plural(dl.needs_you, 'download needs you', 'downloads need you'),
since: dl.needs_you_since,
href: '/collection/activity'
});
}
for (const c of dl.clients_down) {
out.push({ key: `client:${c.client}`, text: `${c.client} isn't answering: ${c.detail}`, since: c.since, href: '/admin/acquisition' });
}
if (status.server.dirty) {
out.push({ key: 'migration', text: `The database migration to version ${status.server.migration} stopped part way`, href: '/admin' });
}
@@ -67,10 +52,6 @@
return out;
});
// Worded as the wanted list words it; before the client reports, it is
// simply downloading, as the Downloads list says.
const downloadLine = (d: Download) => liveDownloadLine(d) ?? 'Downloading';
</script>
<svelte:head><title>{pageTitle('Admin · Overview')}</title></svelte:head>
@@ -148,7 +129,6 @@
</p>
{:else if status}
{@const l = status.listening}
{@const dl = status.downloads}
{@const lib = status.library}
{@const srv = status.server}
<section class="space-y-2" data-testid="overview-listening">
@@ -180,29 +160,6 @@
</p>
</section>
<section class="space-y-2" data-testid="overview-downloads">
<h2 class="text-sm font-medium text-text-primary">Downloads</h2>
<p class="text-sm text-text-secondary" data-testid="downloads-line">
{dl.running === 0 ? 'Nothing downloading' : `${dl.running} downloading`}.
In the last day, {dl.imported_day} imported{dl.given_up_day ? ` and ${dl.given_up_day} given up` : ''}.
<a href="/collection/activity" class="text-accent-fg hover:underline">Activity</a>
</p>
{#if dl.live.length > 0}
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
{#each dl.live as d (d.id)}
<li class="flex items-baseline gap-3 px-4 py-2" data-testid="download-row">
<span class="min-w-0 flex-1 truncate text-sm text-text-primary" title={d.name}>
{d.want_title ? `${d.want_title} · ${d.want_artist}` : d.name}
</span>
<span class="shrink-0 text-xs {d.import_state === 'review' || d.import_state === 'failed' ? 'text-text-primary' : 'text-text-muted'}"
>{downloadLine(d)} · {relativeTime(d.grabbed_at)}</span
>
</li>
{/each}
</ul>
{/if}
</section>
<section class="space-y-2" data-testid="overview-library">
<h2 class="text-sm font-medium text-text-primary">Library</h2>
<p class="text-sm text-text-secondary" data-testid="library-line">
@@ -1,25 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import AcquisitionCard from '#lib/components/AcquisitionCard.svelte';
import SearchSettingsCard from '#lib/components/SearchSettingsCard.svelte';
import ReacquisitionSettingsCard from '#lib/components/ReacquisitionSettingsCard.svelte';
import SettingsColumns from '#lib/components/settings/SettingsColumns.svelte';
// Admin › Acquisition: how Minstrel gets music. Where it searches
// and what downloads, how it searches and what it takes, and what happens
// to a file that goes missing.
</script>
<svelte:head><title>{pageTitle('Admin · Acquisition')}</title></svelte:head>
<h2 class="sr-only">Acquisition</h2>
<SettingsColumns>
{#snippet main()}
<AcquisitionCard />
<SearchSettingsCard />
{/snippet}
{#snippet side()}
<div id="reacquisition"><ReacquisitionSettingsCard /></div>
{/snippet}
</SettingsColumns>
+12 -51
View File
@@ -67,7 +67,7 @@ describe('admin/+layout.ts load gate', () => {
// Importing at module load means the mocks attach to the same handles the
// page binds against.
import { createAdminStatusQuery, createAdminSummaryQuery, createScanStatusQuery } from '#lib/api/admin.js';
import type { AdminStatus, AdminSummary, Download } from '#lib/api/types.js';
import type { AdminStatus, AdminSummary } from '#lib/api/types.js';
import OverviewPage from './+page.svelte';
import AdminLayout from './+layout.svelte';
import { createRawSnippet } from 'svelte';
@@ -78,7 +78,6 @@ const empty = { count: 0, since: null };
function summary(over: Partial<AdminSummary> = {}): AdminSummary {
return {
requests: empty,
reports: empty,
duplicates: empty,
suspect: empty,
@@ -103,9 +102,6 @@ const minutesAgo = (m: number) => new Date(Date.now() - m * 60_000).toISOString(
function status(over: Partial<AdminStatus> = {}): AdminStatus {
return {
listening: { now: [], plays_day: 0, listeners_day: 0, last_play_at: null },
downloads: {
running: 0, needs_you: 0, needs_you_since: null, imported_day: 0, given_up_day: 0, live: [], clients_down: []
},
library: {
tracks: 41_000, albums: 3_200, artists: 900, bytes: 1_400_000_000_000,
disks: [{ path: '/music', total_bytes: 4_000_000_000_000, free_bytes: 2_000_000_000_000 }]
@@ -127,24 +123,24 @@ describe('admin Overview page', () => {
render(OverviewPage);
expect(screen.getByTestId('verdict').textContent).toMatch(/nothing needs you/i);
expect(screen.queryAllByTestId('needs-you')).toHaveLength(0);
expect(screen.getByTestId('all-clear').textContent).toMatch(/no requests, reports, duplicates, suspect sources, missing files/i);
expect(screen.getByTestId('all-clear').textContent).toMatch(/no reports, duplicates, suspect sources, missing files/i);
});
test('each queue that waits on you is listed with how long its oldest has waited, and opens its page', () => {
setupOverview(summary({
requests: { count: 2, since: ago(3) },
reports: { count: 2, since: ago(3) },
missing: { count: 1, since: ago(10) }
}));
render(OverviewPage);
expect(screen.getByTestId('verdict').textContent).toMatch(/2 things need you/);
const rows = screen.getAllByTestId('needs-you').map((r) => r.textContent?.replace(/\s+/g, ' ').trim());
expect(rows).toEqual(['2 requests to decide oldest 3d ago Open', '1 missing file oldest 10d ago Open']);
expect(screen.getByRole('link', { name: /2 requests to decide/i }).getAttribute('href')).toBe('/admin/requests');
expect(screen.getByTestId('all-clear').textContent).not.toMatch(/requests/);
expect(rows).toEqual(['2 broken tracks reported oldest 3d ago Open', '1 missing file oldest 10d ago Open']);
expect(screen.getByRole('link', { name: /2 broken tracks reported/i }).getAttribute('href')).toBe('/collection/reports');
expect(screen.getByTestId('all-clear').textContent).not.toMatch(/reports/);
});
// The library's health queues live under Collection; the Overview
// still lists them, linking there.
// The health queues are worked under Collection; the Overview lists
// them, linking there.
test('a library queue that waits on you opens its Collection page', () => {
setupOverview(summary({ duplicates: { count: 5, since: ago(4) } }));
render(OverviewPage);
@@ -226,55 +222,22 @@ describe('admin Overview status', () => {
expect(screen.getAllByTestId('server-error')[0].textContent).toMatch(/admin: summary[\s\S]*err=boom/);
});
test('a download waiting on you, a client not answering and a nearly full disk count in the verdict', () => {
test('a nearly full disk counts in the verdict', () => {
setupOverview(summary(), vi.fn(), status({
downloads: {
running: 1, needs_you: 2, needs_you_since: minutesAgo(90), imported_day: 4, given_up_day: 0, live: [],
clients_down: [{ client: 'qbittorrent', detail: 'connection refused', since: minutesAgo(30) }]
},
library: {
tracks: 1, albums: 1, artists: 1, bytes: 1,
disks: [{ path: '/music', total_bytes: 1_000, free_bytes: 10 }]
}
}));
render(OverviewPage);
expect(screen.getByTestId('verdict').textContent).toMatch(/3 things need you/);
expect(screen.getByTestId('verdict').textContent).toMatch(/1 thing needs you/);
const needs = screen.getAllByTestId('needs-you').map((li) => li.textContent?.replace(/\s+/g, ' ').trim());
expect(needs).toEqual([
'2 downloads need you since 1h ago Open',
"qbittorrent isn't answering: connection refused since 30m ago Open",
'/music is nearly full: 10 B free Open'
]);
expect(textOf('downloads-line')).toBe('1 downloading. In the last day, 4 imported. Activity');
});
// Worded as the wanted list words a download.
test('each live download says what it is doing, as the wanted list says it', () => {
const d = (id: string, import_state: Download['import_state'], import_reason = ''): Download => ({
id, want_id: null, want_title: `Album ${id}`, want_artist: 'Blur', name: id, indexer: '', client: 'qbittorrent',
quality: 'FLAC', origin: 'schedule', grabbed_at: minutesAgo(5), ended_at: null, end_reason: '', progress: 0.42,
import_state, import_reason, imported_at: null, imported_files: 0, destination: '', files: [], skipped: 0,
end_detail: '', seeding: false, ratio: 0, seed_released_at: null, condition: null
});
setupOverview(summary(), vi.fn(), status({
downloads: {
running: 3, needs_you: 1, needs_you_since: minutesAgo(5), imported_day: 0, given_up_day: 0, clients_down: [],
live: [d('a', 'review', '9 files against 12 tracks'), d('b', 'downloading'), d('c', '')]
}
}));
render(OverviewPage);
const rows = screen.getAllByTestId('download-row').map((li) => li.textContent?.replace(/\s+/g, ' ').trim());
expect(rows).toEqual([
'Album a · Blur Needs you: 9 files against 12 tracks · 5m ago',
'Album b · Blur Downloading 42% · 5m ago',
'Album c · Blur Downloading · 5m ago'
]);
expect(needs).toEqual(['/music is nearly full: 10 B free Open']);
});
});
describe('admin layout', () => {
test('the sections run down a rail, each queue carrying how many wait on you', () => {
setupOverview(summary({ requests: { count: 2, since: ago(1) }, duplicates: { count: 5, since: ago(4) } }));
test('the sections run down a rail', () => {
const children = createRawSnippet(() => ({ render: () => '<p data-testid="admin-body">body</p>' }));
// eslint-disable-next-line @typescript-eslint/no-explicit-any
render(AdminLayout, { children } as any);
@@ -285,9 +248,7 @@ describe('admin layout', () => {
]);
expect(links).toEqual([
['/admin', 'Overview'],
['/admin/requests', 'Requests 2'],
['/admin/library', 'Library'],
['/admin/acquisition', 'Acquisition'],
['/admin/metadata', 'Metadata sources'],
['/admin/email', 'Email & network'],
['/admin/users', 'Users'],
+1 -7
View File
@@ -147,13 +147,7 @@
<SettingsColumns>
{#snippet main()}
<SettingsGroup title="Library" id="scan" hint="The folders Minstrel reads, and the scan that reads them.">
<!-- The import's folder picker reads the folders through search settings. -->
<LibraryFoldersSetting
onSaved={() => {
client.invalidateQueries({ queryKey: qk.scanStatus() });
client.invalidateQueries({ queryKey: qk.searchSettings() });
}}
/>
<LibraryFoldersSetting onSaved={() => client.invalidateQueries({ queryKey: qk.scanStatus() })} />
<SettingRow label="Scan" hint={scanLine}>
<button type="button" onclick={onRunScan} disabled={triggering || scanInFlight} class={button}>
{scanInFlight ? 'Scanning…' : triggering ? 'Starting…' : 'Run scan'}
-279
View File
@@ -1,279 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import { Check, X, SlidersHorizontal } from 'lucide-svelte';
import { useQueryClient } from '@tanstack/svelte-query';
import RowActionsMenu, { type RowAction } from '#lib/components/RowActionsMenu.svelte';
import TabStrip from '#lib/components/TabStrip.svelte';
import { createAdminRequestsQuery, approveRequest, rejectRequest } from '#lib/api/admin.js';
import { createReleaseProfilesQuery } from '#lib/api/wanted.js';
import { errMessage } from '#lib/api/errors.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import RequestRow, { requestName } from '#lib/components/RequestRow.svelte';
import Modal from '#lib/components/Modal.svelte';
import type { MusicRequest, RequestStatus } from '#lib/api/types.js';
// Approval queue. Tabs filter by status; rows expose Approve/Reject, and an
// artist request can be approved on a chosen release-type profile. Approving
// puts the request on the wanted list: an album or track wants
// its album, an artist is followed.
const client = useQueryClient();
// The four tab filters. "Pending" is default — that's the actionable bucket;
// the rest are review-only views.
const tabs: { status: RequestStatus; label: string }[] = [
{ status: 'pending', label: 'Pending' },
{ status: 'approved', label: 'Approved' },
{ status: 'completed', label: 'Completed' },
{ status: 'rejected', label: 'Rejected' }
];
let activeStatus = $state<RequestStatus>('pending');
// The query factory is re-created on every status flip so TanStack treats
// each status as its own cache key. We don't need a single shared store.
const queryStore = $derived(createAdminRequestsQuery(activeStatus));
const query = $derived($queryStore);
const rows = $derived((query.data ?? []) as MusicRequest[]);
// Release-type profiles for the "Approve on a profile" modal: which kinds of
// release following the artist will want.
const profilesStore = createReleaseProfilesQuery();
const profiles = $derived($profilesStore.data?.profiles ?? []);
// Modal state. `profileOpen` and `rejectOpen` carry the request id when
// open; null otherwise. The current row is looked up by id at render time.
let profileOpen = $state<string | null>(null);
let profileChoice = $state<string>('');
let rejectOpen = $state<string | null>(null);
let rejectNotes = $state<string>('');
// Names the requester. The id is the fallback for a list that came back
// without names; its first 8 characters are enough to tell users apart.
function rowMeta(r: MusicRequest): string {
const when = new Date(r.requested_at).toLocaleDateString();
const who = r.username || `user ${r.user_id.slice(0, 8)}`;
return `by ${who} · ${when}`;
}
async function invalidate() {
// Invalidate every status bucket so e.g. an approve flips a row from the
// pending list to the approved list once an admin switches tabs.
await client.invalidateQueries({ queryKey: ['adminRequests'] });
await client.invalidateQueries({ queryKey: ['adminWants'] });
}
async function onApprove(r: MusicRequest, profileId?: string) {
try {
await approveRequest(r.id, profileId);
await invalidate();
} catch (e) {
pushToast(errMessage(e), 'error');
}
}
function openProfile(r: MusicRequest) {
profileOpen = r.id;
// Start from the default each time, not the previous row's choice.
profileChoice = profiles.find((p) => p.is_default)?.id ?? '';
}
function cancelProfile() {
profileOpen = null;
}
async function confirmProfile(r: MusicRequest) {
const choice = profileChoice;
profileOpen = null;
await onApprove(r, choice || undefined);
}
function openReject(r: MusicRequest) {
rejectOpen = r.id;
rejectNotes = '';
}
function cancelReject() {
rejectOpen = null;
}
async function confirmReject(r: MusicRequest) {
const notes = rejectNotes.trim();
rejectOpen = null;
try {
await rejectRequest(r.id, notes ? notes : undefined);
await invalidate();
} catch (e) {
pushToast(errMessage(e), 'error');
}
}
// Modal lookups: if the active tab has been refetched while a modal is
// open, the row may no longer be in `rows`. Guard against that by treating
// missing-row as closed.
const profileRow = $derived(
profileOpen ? rows.find((r) => r.id === profileOpen) ?? null : null
);
const rejectRow = $derived(
rejectOpen ? rows.find((r) => r.id === rejectOpen) ?? null : null
);
</script>
<svelte:head><title>{pageTitle('Admin · Requests')}</title></svelte:head>
<div class="space-y-6">
<header class="space-y-1">
<h2 class="font-display text-2xl font-medium text-text-primary">Requests</h2>
<p class="text-text-secondary">
Approve or set aside what users have asked for. An approved album or track goes on the
<a href="/collection/wanted" class="text-accent-fg hover:underline">wanted list</a>; an approved
artist is followed, wanting what they've released and what they release next.
</p>
</header>
<TabStrip
ariaLabel="Request status filters"
bind:value={activeStatus}
items={tabs.map((tab) => ({
id: tab.status,
label: tab.label,
count: activeStatus === tab.status ? rows.length : undefined
}))}
/>
{#if query.isPending}
<p class="text-text-secondary">Reading the queue…</p>
{:else if query.isError}
<p class="text-sm text-error-fg">
Couldn't load the requests.
<button type="button" class="underline hover:no-underline" onclick={() => query.refetch()}>Try again</button>
</p>
{:else if rows.length === 0}
<p class="text-text-secondary">Nothing here.</p>
{:else}
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
{#each rows as r (r.id)}
<RequestRow request={r} meta={rowMeta(r)} testid="admin-request-row">
{#snippet details()}
{#if r.kind === 'track' && r.album_title}
<div class="text-sm text-text-secondary" data-testid="track-disclosure">
Approving wants the album <em class="font-medium text-text-primary">{r.album_title}</em>.
</div>
{/if}
{#if r.notes}
<div class="text-sm text-text-secondary">{r.notes}</div>
{/if}
{/snippet}
{#snippet actions()}
{#if r.status === 'pending'}
{@const primary: RowAction = {
icon: Check,
label: 'Approve',
ariaLabel: `Approve ${requestName(r)}`,
onclick: () => onApprove(r)
}}
{@const secondary: RowAction[] = [
...(r.kind === 'artist'
? [
{
icon: SlidersHorizontal,
label: 'Approve on a profile',
ariaLabel: `Approve ${requestName(r)} on a profile`,
onclick: () => openProfile(r)
}
]
: []),
{
icon: X,
label: 'Reject',
ariaLabel: `Reject ${requestName(r)}`,
onclick: () => openReject(r),
danger: true
}
]}
<RowActionsMenu {primary} {secondary} />
{/if}
{/snippet}
</RequestRow>
{/each}
</ul>
{/if}
</div>
<Modal
title="Approve on a profile"
open={profileRow !== null}
onClose={cancelProfile}
>
<p class="-mt-2 text-sm text-text-secondary">
The profile says which kinds of release following
{profileRow?.artist_name ?? 'this artist'} wants. Profiles are edited under <a href="/collection/following" class="underline hover:no-underline">Collection › Following</a>.
</p>
<label class="mt-4 block">
<span class="block text-sm text-text-secondary">Release-type profile</span>
<select
bind:value={profileChoice}
class="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-text-primary focus:outline-hidden focus:ring-2 focus:ring-accent"
>
{#each profiles as p (p.id)}
<option value={p.id}>{p.name}{p.is_default ? ' (default)' : ''}</option>
{/each}
</select>
</label>
<div class="mt-5 flex justify-end gap-2">
<button
type="button"
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:text-text-primary"
onclick={cancelProfile}
>
Cancel
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-md bg-action-primary px-3 py-1.5 text-sm text-action-fg"
onclick={() => profileRow && confirmProfile(profileRow)}
>
<Check size={14} strokeWidth={2} />
Approve and follow
</button>
</div>
</Modal>
<Modal
title="Reject request?"
open={rejectRow !== null}
onClose={cancelReject}
>
<p class="-mt-2 text-sm text-text-secondary">
Notes are shown to the requester.
</p>
<label class="mt-3 block">
<span class="block text-sm text-text-secondary">Notes</span>
<textarea
bind:value={rejectNotes}
rows="3"
placeholder="Optional — why this is being set aside"
class="mt-1 w-full rounded-md border border-border bg-background px-3 py-2 text-sm text-text-primary placeholder:text-text-muted focus:outline-hidden focus:ring-2 focus:ring-accent"
></textarea>
</label>
<div class="mt-5 flex justify-end gap-2">
<button
type="button"
class="rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:text-text-primary"
onclick={cancelReject}
>
Cancel
</button>
<button
type="button"
class="inline-flex items-center gap-1 rounded-md bg-action-secondary px-3 py-1.5 text-sm text-action-fg"
onclick={() => rejectRow && confirmReject(rejectRow)}
>
<X size={14} strokeWidth={2} />
Confirm reject
</button>
</div>
</Modal>
@@ -1,139 +0,0 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { mockQuery } from '../../../test-utils/query';
import type { MusicRequest } from '#lib/api/types.js';
// Wrap useQueryClient so the page can call invalidateQueries() without a
// real QueryClient context. Everything else from svelte-query passes through.
vi.mock('#lib/api/admin.js', () => ({
createAdminRequestsQuery: vi.fn(),
approveRequest: vi.fn(),
rejectRequest: vi.fn()
}));
vi.mock('#lib/api/wanted.js', () => ({
createReleaseProfilesQuery: vi.fn()
}));
import AdminRequestsPage from './+page.svelte';
import { createAdminRequestsQuery, approveRequest, rejectRequest } from '#lib/api/admin.js';
import { createReleaseProfilesQuery } from '#lib/api/wanted.js';
const baseRow: MusicRequest = {
id: 'r1',
user_id: 'u1234567-aaaa-bbbb-cccc-deadbeef0001',
status: 'pending',
kind: 'album',
artist_mbid: 'a-mbid',
album_mbid: 'al-mbid',
artist_name: 'Boards of Canada',
album_title: 'Geogaddi',
requested_at: '2026-04-29T10:00:00Z',
updated_at: '2026-04-29T10:00:00Z',
imported_album_count: 0,
imported_track_count: 0
};
afterEach(() => vi.clearAllMocks());
function setup(rows: MusicRequest[] = [baseRow]) {
(createAdminRequestsQuery as ReturnType<typeof vi.fn>).mockReturnValue(
mockQuery({ data: rows })
);
(createReleaseProfilesQuery as ReturnType<typeof vi.fn>).mockReturnValue(
mockQuery({
data: {
profiles: [
{ id: 'p-std', name: 'Standard', primary_types: ['Album'], secondary_types: [], is_default: true, follow_count: 0 },
{ id: 'p-live', name: 'With live', primary_types: ['Album'], secondary_types: ['Live'], is_default: false, follow_count: 0 }
],
primary_types: ['Album'],
secondary_types: ['Live']
}
})
);
return render(AdminRequestsPage);
}
describe('/admin/requests', () => {
test('Tab switch refetches with new status filter', async () => {
setup();
await fireEvent.click(screen.getByRole('tab', { name: /approved/i }));
expect(createAdminRequestsQuery).toHaveBeenCalledWith('approved');
});
test('Approve sends no profile', async () => {
setup();
(approveRequest as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
await fireEvent.click(screen.getByRole('button', { name: /approve geogaddi/i }));
expect(approveRequest).toHaveBeenCalledWith('r1', undefined);
});
test('An album request has no profile choice', () => {
setup();
expect(screen.queryByRole('button', { name: /on a profile/i })).toBeNull();
});
test('An artist request is approved on the chosen profile', async () => {
setup([{ ...baseRow, kind: 'artist', album_mbid: undefined, album_title: undefined }]);
await fireEvent.click(
screen.getByRole('button', { name: /approve boards of canada on a profile/i })
);
const select = screen.getByLabelText(/release-type profile/i) as HTMLSelectElement;
expect(select.value).toBe('p-std');
await fireEvent.change(select, { target: { value: 'p-live' } });
(approveRequest as ReturnType<typeof vi.fn>).mockResolvedValueOnce(baseRow);
await fireEvent.click(screen.getByRole('button', { name: /approve and follow/i }));
expect(approveRequest).toHaveBeenCalledWith('r1', 'p-live');
});
test('Reject opens notes textarea; confirm sends notes', async () => {
setup();
await fireEvent.click(screen.getByRole('button', { name: /reject geogaddi/i }));
const textarea = screen.getByLabelText(/notes/i) as HTMLTextAreaElement;
await fireEvent.input(textarea, { target: { value: 'duplicate' } });
(rejectRequest as ReturnType<typeof vi.fn>).mockResolvedValueOnce({
...baseRow,
status: 'rejected'
});
await fireEvent.click(
screen.getByRole('button', { name: /confirm reject/i })
);
expect(rejectRequest).toHaveBeenCalledWith('r1', 'duplicate');
});
test('An approve error shows a toast', async () => {
setup();
(approveRequest as ReturnType<typeof vi.fn>).mockRejectedValueOnce({
code: 'request_not_pending',
message: 'not pending',
status: 409
});
await fireEvent.click(screen.getByRole('button', { name: /approve geogaddi/i }));
await waitFor(() =>
expect(screen.getByText(/no longer pending/i)).toBeInTheDocument()
);
});
test('Track-kind row renders disclosure copy about adding the album', () => {
setup([
{
...baseRow,
kind: 'track',
track_title: 'Roygbiv',
album_title: 'Geogaddi'
}
]);
expect(screen.getByText(/wants the album/i)).toBeInTheDocument();
});
test('A row names who asked for it', () => {
setup([{ ...baseRow, username: 'alice' }]);
expect(screen.getByText(/^by alice · /)).toBeInTheDocument();
expect(screen.queryByText(/u1234567/)).not.toBeInTheDocument();
});
test('A row without a name falls back to the user id', () => {
setup();
expect(screen.getByText(/^by user u1234567 · /)).toBeInTheDocument();
});
});
+1 -25
View File
@@ -10,7 +10,6 @@
type TuningSnapshot,
type WeightProfile,
type TasteTuning,
type DiscoverTuning,
type TrendsResponse,
type TrendSeries,
type TrendMarker
@@ -47,11 +46,6 @@
{ key: 'mood_scale', label: 'Mood weight', hint: 'How much the mood counts. 0 ignores it.' }
];
const discoverFields: { key: keyof DiscoverTuning; label: string; hint: string }[] = [
{ key: 'tag_overlap_weight', label: 'Taste-tag weight', hint: 'Boost for a suggestion whose tags fit your taste. 0 ranks on likeness alone.' },
{ key: 'snooze_days', label: 'Snooze length (days)', hint: 'How long "not right now" hides a suggestion.' }
];
const profileScopes: { scope: WeightProfileScope; label: string; blurb: string }[] = [
{ scope: 'radio', label: 'Radio', blurb: 'Listening that starts from a seed.' },
{ scope: 'daily_mix', label: 'Daily mixes', blurb: 'For You, the discovery mixes and "You might like".' },
@@ -73,14 +67,12 @@
radio: {},
daily_mix: {},
songs_like: {},
taste: {},
discover: {}
taste: {}
};
for (const p of profileScopes.map((s) => s.scope)) {
for (const { key } of weightFields) f[p][key] = String(snap.profiles[p][key]);
}
for (const { key } of tasteFields) f.taste[key] = String(snap.taste[key]);
for (const { key } of discoverFields) f.discover[key] = String(snap.discover[key]);
form = f;
}
@@ -104,12 +96,6 @@
if (scope === 'taste') {
return snapshot.taste[key as keyof TasteTuning] !== snapshot.shipped.taste[key as keyof TasteTuning];
}
if (scope === 'discover') {
return (
snapshot.discover[key as keyof DiscoverTuning] !==
snapshot.shipped.discover[key as keyof DiscoverTuning]
);
}
return (
snapshot.profiles[scope][key as keyof WeightProfile] !==
snapshot.shipped.profiles[scope][key as keyof WeightProfile]
@@ -119,7 +105,6 @@
function currentValue(scope: TuningScope, key: string): number {
if (!snapshot) return 0;
if (scope === 'taste') return snapshot.taste[key as keyof TasteTuning];
if (scope === 'discover') return snapshot.discover[key as keyof DiscoverTuning];
return snapshot.profiles[scope][key as keyof WeightProfile];
}
@@ -277,7 +262,6 @@
id="{scope}-{f.key}"
type="number"
step={step(f.key)}
min={scope === 'discover' ? '0' : undefined}
bind:value={form[scope][f.key]}
class="w-24 rounded-md border border-border bg-background px-2 py-1.5 text-right text-sm tabular-nums"
/>
@@ -327,14 +311,6 @@
(k) => (k === 'half_life_days' ? '1' : '0.05'),
(k) => snap.shipped.taste[k as keyof TasteTuning]
)}
{@render knobs(
'discover',
'Discover requests',
"How Discover ranks artists you don't have.",
discoverFields,
(k) => (k === 'snooze_days' ? '1' : '0.1'),
(k) => snap.shipped.discover[k as keyof DiscoverTuning]
)}
</div>
{/if}
+1 -67
View File
@@ -43,12 +43,6 @@ const taste = (over: Partial<Record<string, number>> = {}) => ({
...over
});
const discover = (over: Partial<Record<string, number>> = {}) => ({
tag_overlap_weight: 1,
snooze_days: 90,
...over
});
// NOTE the `as TuningSnapshot` cast below: it silences the type error when the
// server snapshot grows a field, so a missing key here surfaces as every test
// on this page throwing inside fillForm rather than as a compile failure. Add
@@ -61,15 +55,13 @@ function snapshot(over: Partial<TuningSnapshot> = {}): TuningSnapshot {
songs_like: weights({ similarity_weight: 4, like_boost: 0.5, taste_weight: 0.25 })
},
taste: taste(),
discover: discover(),
shipped: {
profiles: {
radio: weights({ taste_weight: 1 }),
daily_mix: weights(),
songs_like: weights({ similarity_weight: 4, like_boost: 0.5, taste_weight: 0.25 })
},
taste: taste(),
discover: discover()
taste: taste()
},
...over
} as TuningSnapshot;
@@ -262,62 +254,4 @@ describe('Admin tuning page', () => {
expect(screen.getByText(/trends appear once listening accumulates/i)).toBeInTheDocument()
);
});
// --- Discover scope ---
test('renders the Discover card with its two knobs', async () => {
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
render(TuningPage);
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
expect(screen.getByLabelText(/taste-tag weight/i)).toBeInTheDocument();
expect(screen.getByLabelText(/snooze length/i)).toBeInTheDocument();
});
test('saving Discover patches only the changed field under the discover scope', async () => {
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
(patchTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
render(TuningPage);
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
await fireEvent.input(screen.getByLabelText(/taste-tag weight/i), {
target: { value: '2.5' }
});
await fireEvent.click(screen.getByRole('button', { name: /save discover/i }));
await waitFor(() =>
expect(patchTuning).toHaveBeenCalledWith('discover', { tag_overlap_weight: 2.5 })
);
});
// 0 is an admin's off switch for the whole tag term, so the form must be
// able to send it — a falsy-value bug here would silently make the feature
// impossible to disable.
test('a Discover weight of 0 is sent, not dropped as falsy', async () => {
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
(patchTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
render(TuningPage);
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
await fireEvent.input(screen.getByLabelText(/taste-tag weight/i), { target: { value: '0' } });
await fireEvent.click(screen.getByRole('button', { name: /save discover/i }));
await waitFor(() =>
expect(patchTuning).toHaveBeenCalledWith('discover', { tag_overlap_weight: 0 })
);
});
test('reset targets the discover scope', async () => {
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
(resetTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snapshot());
render(TuningPage);
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
await fireEvent.click(
screen.getByRole('button', { name: /reset discover requests to defaults/i })
);
await waitFor(() => expect(resetTuning).toHaveBeenCalledWith('discover'));
});
test('a deviating Discover knob is dotted', async () => {
const snap = snapshot();
snap.discover = discover({ tag_overlap_weight: 3 });
(getTuning as ReturnType<typeof vi.fn>).mockResolvedValue(snap);
render(TuningPage);
await waitFor(() => expect(screen.getByText('Discover requests')).toBeInTheDocument());
expect(screen.getByTitle(/deviates from the shipped default \(1\)/i)).toBeInTheDocument();
});
});
+1 -32
View File
@@ -10,7 +10,6 @@
createUser,
deleteUser,
resetUserPassword,
updateUserAutoApprove,
updateUserDebugMode,
createAdminUsersQuery,
createAdminInvitesQuery,
@@ -22,7 +21,7 @@
import { pushToast } from '#lib/stores/toast.svelte.js';
import Modal from '#lib/components/Modal.svelte';
import RowActionsMenu, { type RowAction } from '#lib/components/RowActionsMenu.svelte';
import { Shield, ShieldOff, CheckCircle2, XCircle, KeyRound, Trash2, Copy, Bug, BugOff } from 'lucide-svelte';
import { Shield, ShieldOff, KeyRound, Trash2, Copy, Bug, BugOff } from 'lucide-svelte';
const client = useQueryClient();
@@ -150,21 +149,6 @@
}
}
async function onToggleAutoApprove(u: AdminUser) {
saving = true;
try {
await updateUserAutoApprove(u.id, !u.auto_approve_requests);
await client.invalidateQueries({ queryKey: qk.adminUsers() });
pushToast(u.auto_approve_requests
? `Auto-approve disabled for ${u.username}.`
: `Auto-approve enabled for ${u.username}.`);
} catch (e: unknown) {
pushToast(`Toggle failed: ${errCode(e)}`, 'error');
} finally {
saving = false;
}
}
// Debug mode makes the account's devices report diagnostics: a
// row action here, with the badge linking to that account's events.
async function onToggleDebug(u: AdminUser) {
@@ -267,15 +251,6 @@
disabled: saving
}}
{@const secondary: RowAction[] = [
{
icon: u.auto_approve_requests ? XCircle : CheckCircle2,
label: u.auto_approve_requests ? 'Disable auto-approve' : 'Enable auto-approve',
ariaLabel: u.auto_approve_requests
? `Disable auto-approve for ${u.username}`
: `Enable auto-approve for ${u.username}`,
onclick: () => onToggleAutoApprove(u),
disabled: saving
},
{
icon: u.debug_mode_enabled ? BugOff : Bug,
label: u.debug_mode_enabled ? 'Turn off debug mode' : 'Turn on debug mode',
@@ -318,12 +293,6 @@
data-testid="debug-badge"
>debug on</a>
{/if}
{#if u.auto_approve_requests}
<span
class="inline-flex items-center rounded-full border border-border px-2 py-0.5 text-xs text-text-secondary"
data-testid="auto-approve-badge"
>auto-approve</span>
{/if}
</div>
<div class="text-sm text-text-secondary">
{#if u.display_name}{u.display_name} · {/if}created {formatDate(u.created_at)}
-13
View File
@@ -16,7 +16,6 @@ vi.mock('#lib/api/admin.js', () => ({
createUser: vi.fn(),
deleteUser: vi.fn(),
resetUserPassword: vi.fn(),
updateUserAutoApprove: vi.fn(),
updateUserDebugMode: vi.fn()
}));
@@ -30,7 +29,6 @@ import {
createUser,
deleteUser,
resetUserPassword,
updateUserAutoApprove,
updateUserDebugMode
} from '#lib/api/admin.js';
@@ -39,7 +37,6 @@ const alice: AdminUser = {
username: 'alice',
display_name: null,
is_admin: true,
auto_approve_requests: false,
debug_mode_enabled: false,
created_at: '2026-05-01T00:00:00Z'
};
@@ -49,7 +46,6 @@ const bob: AdminUser = {
username: 'bob',
display_name: 'Bob B',
is_admin: false,
auto_approve_requests: false,
debug_mode_enabled: false,
created_at: '2026-05-02T00:00:00Z'
};
@@ -201,15 +197,6 @@ describe('/admin/users', () => {
expect(resetUserPassword).toHaveBeenCalledWith(expect.any(String), 'abcd1234');
});
test('toggle-auto-approve calls updateUserAutoApprove', async () => {
(updateUserAutoApprove as ReturnType<typeof vi.fn>).mockResolvedValue({});
setup();
await waitFor(() => screen.getByText('alice'));
await fireEvent.click(screen.getAllByRole('button', { name: /Enable auto-approve/i })[0]);
expect(updateUserAutoApprove).toHaveBeenCalledWith(expect.any(String), true);
});
test('debug mode is a row action, and an account with it on links to its events', async () => {
(updateUserDebugMode as ReturnType<typeof vi.fn>).mockResolvedValue({});
setup([alice, { ...bob, debug_mode_enabled: true }]);
-8
View File
@@ -14,8 +14,6 @@
import CompactTrackCard from '#lib/components/CompactTrackCard.svelte';
import HorizontalScrollRow from '#lib/components/HorizontalScrollRow.svelte';
import LikeButton from '#lib/components/LikeButton.svelte';
import FollowControl from '#lib/components/FollowControl.svelte';
import { user } from '#lib/auth/store.svelte.js';
import LibrarySkeleton from '#lib/components/LibrarySkeleton.svelte';
import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
import { useDelayed } from '#lib/utils/useDelayed.svelte.js';
@@ -25,7 +23,6 @@
import type { ArtistRef, TrackRef } from '#lib/api/types.js';
const id = $derived(page.params.id ?? '');
const isAdmin = $derived(user.value?.is_admin === true);
const queryStore = $derived(createArtistQuery(id));
const query = $derived($queryStore);
const showSkeleton = useDelayed(() => query.isPending);
@@ -114,11 +111,6 @@
{onPlay}
{onShuffle}
/>
<!-- Following is keyed by MusicBrainz id, so an artist whose tags
never named one can't be followed. -->
{#if isAdmin && detail.mbid}
<FollowControl artistMbid={detail.mbid} artistName={detail.name} />
{/if}
</div>
</div>
</header>
@@ -25,24 +25,6 @@ vi.mock('#lib/api/queries.js', () => ({
vi.mock('#lib/api/likes.js', () => emptyLikesMock());
const userState = vi.hoisted(() => ({
current: null as { id: string; username: string; is_admin: boolean } | null
}));
vi.mock('#lib/auth/store.svelte.js', () => ({
user: { get value() { return userState.current; } }
}));
vi.mock('#lib/api/wanted.js', async () => {
const { mockQuery } = await import('../../../test-utils/query');
return {
createFollowQuery: vi.fn(() => mockQuery({ data: { following: false } })),
createReleaseProfilesQuery: vi.fn(() => mockQuery({ data: { profiles: [], primary_types: [], secondary_types: [] } })),
putFollow: vi.fn(),
deleteFollow: vi.fn()
};
});
vi.mock('#lib/api/client.js', () => apiClientMock());
vi.mock('#lib/player/store.svelte.js', () => ({
@@ -77,7 +59,6 @@ function album(id: string, title: string, year?: number): AlbumRef {
afterEach(() => {
vi.clearAllMocks();
state.pageParams = { id: 'abc' };
userState.current = null;
});
beforeEach(() => {
@@ -194,34 +175,4 @@ describe('artist detail page', () => {
expect(queued.map((t: { id: string }) => t.id).sort()).toEqual(tracks.map((t) => t.id).sort());
});
});
// Following is for the wanted list: an admin control, keyed by
// the artist's MusicBrainz id.
describe('Follow', () => {
const detail = (mbid: string): ArtistDetail => ({
id: 'abc', name: 'Alice', sort_name: 'Alice', album_count: 1, cover_url: '',
albums: [album('a1', 'First', 2020)], genres: [], mbid
});
test('an admin can follow an artist with a MusicBrainz id', () => {
userState.current = { id: 'u1', username: 'admin', is_admin: true };
(createArtistQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail('mb-alice') }));
render(ArtistPage);
expect(screen.getByRole('button', { name: /^follow$/i })).toBeInTheDocument();
});
test('no follow control without a MusicBrainz id', () => {
userState.current = { id: 'u1', username: 'admin', is_admin: true };
(createArtistQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail('') }));
render(ArtistPage);
expect(screen.queryByRole('button', { name: /^follow$/i })).toBeNull();
});
test('no follow control for a non-admin', () => {
userState.current = { id: 'u2', username: 'sam', is_admin: false };
(createArtistQuery as ReturnType<typeof vi.fn>).mockReturnValue(mockQuery({ data: detail('mb-alice') }));
render(ArtistPage);
expect(screen.queryByRole('button', { name: /^follow$/i })).toBeNull();
});
});
});
+20 -58
View File
@@ -1,82 +1,44 @@
<script lang="ts">
import { plural } from '#lib/utils/plural.js';
import { createWantArtistsQuery } from '#lib/api/wanted.js';
import { createAdminSummaryQuery } from '#lib/api/admin.js';
import { QUEUES, countOf, queueLabel } from '#lib/admin/queues.js';
import CollectionRail from '#lib/components/wanted/CollectionRail.svelte';
import CollectionRail from '#lib/components/CollectionRail.svelte';
let { children } = $props<{ children: import('svelte').Snippet }>();
// The Collection: what the library holds and wants, and what
// Minstrel is fetching for it. Web-only and admin-only. The catalogue of
// artists is the main section, and the sections down the left show state. The
// catalogue's first page carries every section's count; the Catalogue
// shares it, so this costs no extra request there.
const artistsStore = createWantArtistsQuery();
const counts = $derived($artistsStore.data?.pages?.[0]?.counts);
// The one line that answers "does anything need me?"
const verdict = $derived.by(() => {
if (!counts) return '';
if (counts.attention) {
return `${plural(counts.attention, 'download needs', 'downloads need')} you.`;
}
const parts = [plural(counts.wanted, 'album wanted', 'albums wanted')];
if (counts.activity) parts.push(`${counts.activity} downloading`);
// Library albums no MusicBrainz album matched wait on a person too.
if (counts.unmatched) {
const n = plural(counts.unmatched, 'album in your library needs', 'albums in your library need');
return parts.join(', ') + `. ${n} matching.`;
}
return parts.join(', ') + '. Nothing needs you.';
});
const needsYou = $derived(!!counts?.attention || !!counts?.unmatched);
// The library's health queues count from the admin summary, the
// same read Admin's Overview makes. The line under the verdict names the
// ones with something in them; each links to its page.
// The Collection: the library's health. Web-only and admin-only. The
// queues count from the admin summary, the same read Admin's Overview
// makes, so a queue that needs you is counted the same in both places.
const summaryStore = createAdminSummaryQuery();
const summary = $derived($summaryStore.data);
const health = $derived(
QUEUES.filter((d) => d.href.startsWith('/collection/') && countOf(summary, d.key) > 0)
);
const waiting = $derived(QUEUES.filter((d) => countOf(summary, d.key) > 0));
</script>
<div class="space-y-4">
<header class="space-y-1">
<h1 class="font-display text-2xl font-medium text-text-primary">Collection</h1>
<p class="text-sm text-text-secondary">
Every artist and album in your collection: what the library holds, and what Minstrel is
getting for it, from user requests, new releases of the artists it follows, and albums whose
files went missing. It searches your indexers on a schedule, checks each download against
MusicBrainz, and files what's right into the library. Searching and quality are set under
<a href="/admin/acquisition" class="text-accent-fg hover:underline">Acquisition</a>.
What in the library needs looking at: tracks people reported, songs held twice, files from
doubtful sources, and files that went missing.
</p>
{#if verdict}
<p class="text-sm {needsYou ? 'text-text-primary' : 'text-text-secondary'}" data-testid="collection-verdict">
{verdict}
{#if counts?.attention}
<a href="/collection/activity" class="ml-1 text-accent-fg hover:underline">See Activity</a>
{:else if counts?.unmatched}
<a href="/collection/unmatched" class="ml-1 text-accent-fg hover:underline">See Unmatched</a>
{/if}
</p>
{/if}
{#if health.length > 0}
<p class="text-sm text-text-primary" data-testid="collection-health">
To look at:
{#each health as d, i (d.key)}<a href={d.href} class="text-accent-fg hover:underline"
>{queueLabel(d, countOf(summary, d.key))}</a
>{i < health.length - 1 ? ', ' : '.'}
{/each}
</p>
{#if summary}
{#if waiting.length > 0}
<p class="text-sm text-text-primary" data-testid="collection-health">
To look at:
{#each waiting as d, i (d.key)}<a href={d.href} class="text-accent-fg hover:underline"
>{queueLabel(d, countOf(summary, d.key))}</a
>{i < waiting.length - 1 ? ', ' : '.'}
{/each}
</p>
{:else}
<p class="text-sm text-text-secondary" data-testid="collection-health">Nothing needs you.</p>
{/if}
{/if}
</header>
<div class="md:grid md:grid-cols-[11rem_minmax(0,1fr)] md:gap-6">
<div class="mb-4 md:mb-0">
<div class="md:sticky md:top-4">
<CollectionRail {counts} {summary} />
<CollectionRail {summary} />
</div>
</div>
<div class="min-w-0">
+43 -2
View File
@@ -1,8 +1,49 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import CatalogueGrid from '#lib/components/wanted/CatalogueGrid.svelte';
import { createAdminSummaryQuery } from '#lib/api/admin.js';
import { relativeTime } from '#lib/utils/relativeTime.js';
import { QUEUES, countOf, queueLabel } from '#lib/admin/queues.js';
// The Collection's overview: each health queue with something in it and
// how long its oldest has waited, then the empty ones on one line.
const summaryStore = createAdminSummaryQuery();
const summaryQ = $derived($summaryStore);
const summary = $derived(summaryQ.data);
const waiting = $derived(QUEUES.filter((d) => countOf(summary, d.key) > 0));
const clear = $derived(QUEUES.filter((d) => countOf(summary, d.key) === 0));
</script>
<svelte:head><title>{pageTitle('Collection')}</title></svelte:head>
<CatalogueGrid />
<section class="space-y-3" data-testid="collection-overview">
{#if summaryQ.isPending}
<p class="text-sm text-text-secondary">Reading the queues…</p>
{:else if summaryQ.isError}
<p class="text-sm text-error-fg">
Couldn't read the queues.
<button type="button" class="underline hover:no-underline" onclick={() => summaryQ.refetch()}>Try again</button>
</p>
{:else}
{#if waiting.length > 0}
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
{#each waiting as d (d.key)}
{@const q = summary?.[d.key]}
<li data-testid="collection-queue">
<a href={d.href} class="flex flex-wrap items-baseline gap-x-3 gap-y-1 px-4 py-3 hover:bg-surface-hover">
<span class="text-sm text-text-primary">{queueLabel(d, countOf(summary, d.key))}</span>
{#if q?.since}
<span class="text-xs text-text-muted">oldest {relativeTime(q.since)}</span>
{/if}
<span class="ml-auto text-sm text-accent-fg">Open</span>
</a>
</li>
{/each}
</ul>
{/if}
{#if clear.length > 0}
<p class="text-xs text-text-muted" data-testid="collection-clear">
No {clear.map((d) => d.none).join(', ')}.
</p>
{/if}
{/if}
</section>
@@ -1,8 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import DownloadList from '#lib/components/wanted/DownloadList.svelte';
</script>
<svelte:head><title>{pageTitle('Collection · Activity')}</title></svelte:head>
<DownloadList />
@@ -1,15 +0,0 @@
<script lang="ts">
import { page } from '$app/state';
import { pageTitle } from '#lib/branding.js';
import WantList from '#lib/components/wanted/WantList.svelte';
// One artist in the Collection's catalogue: every album of theirs
// on the list, held or not, with its tracks a click away.
const mbid = $derived(page.params.mbid ?? '');
</script>
<svelte:head><title>{pageTitle('Collection · Artist')}</title></svelte:head>
{#key mbid}
<WantList artist={mbid} />
{/key}
@@ -1,8 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import BlockList from '#lib/components/wanted/BlockList.svelte';
</script>
<svelte:head><title>{pageTitle('Collection · Blocked')}</title></svelte:head>
<BlockList />
+30 -63
View File
@@ -1,97 +1,57 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen } from '@testing-library/svelte';
import { createRawSnippet } from 'svelte';
import { mockInfiniteQuery } from '../../test-utils/query';
import { pageUrlModule } from '#test-utils/mocks/appState.js';
import { mockQuery } from '../../test-utils/query';
import type { AdminSummary, WantArtistsPage, WantCounts } from '#lib/api/types.js';
import type { AdminSummary } from '#lib/api/types.js';
const state = vi.hoisted(() => ({ pageUrl: new URL('http://localhost/collection') }));
vi.mock('$app/state', () => pageUrlModule(state));
vi.mock('#lib/api/wanted.js', () => ({ createWantArtistsQuery: vi.fn() }));
vi.mock('#lib/api/admin.js', () => ({ createAdminSummaryQuery: vi.fn() }));
import WantedLayout from './+layout.svelte';
import { createWantArtistsQuery } from '#lib/api/wanted.js';
import CollectionLayout from './+layout.svelte';
import CollectionPage from './+page.svelte';
import { createAdminSummaryQuery } from '#lib/api/admin.js';
const counts: WantCounts = { artists: 7, wanted: 5, missing: 1, held: 9, upgrades: 6, following: 2, activity: 3, attention: 0, blocked: 4, unmatched: 3 };
const children = createRawSnippet(() => ({ render: () => `<p data-testid="tab-body">body</p>` }));
afterEach(() => vi.clearAllMocks());
const none = { count: 0, since: null };
const clear: AdminSummary = { requests: none, reports: none, duplicates: none, suspect: none, missing: none };
const clear: AdminSummary = { reports: none, duplicates: none, suspect: none, missing: none };
function setup(c: WantCounts = counts, path = '/collection', summary: AdminSummary = clear) {
state.pageUrl = new URL(`http://localhost${path}`);
function mockSummary(summary: AdminSummary) {
vi.mocked(createAdminSummaryQuery).mockReturnValue(
mockQuery({ data: summary }) as unknown as ReturnType<typeof createAdminSummaryQuery>
);
const page: WantArtistsPage = {
items: [],
total: 0,
limit: 50,
offset: 0,
counts: c,
library: { listed_at: null, unlisted: 0 }
};
vi.mocked(createWantArtistsQuery).mockReturnValue(
mockInfiniteQuery({ pages: [page] }) as unknown as ReturnType<typeof createWantArtistsQuery>
);
}
function setup(path = '/collection', summary: AdminSummary = clear) {
state.pageUrl = new URL(`http://localhost${path}`);
mockSummary(summary);
// eslint-disable-next-line @typescript-eslint/no-explicit-any
return render(WantedLayout, { children } as any);
return render(CollectionLayout, { children } as any);
}
describe('/collection layout', () => {
test('the sections down the left carry their counts, the current one marked', () => {
setup(counts, '/collection/activity');
test('the sections down the left are the overview and the health queues, the current one marked', () => {
setup('/collection/missing');
const nav = screen.getByRole('navigation', { name: /collection sections/i });
const links = Array.from(nav.querySelectorAll('a')).map((a) => [a.getAttribute('href'), a.textContent?.replace(/\s+/g, ' ').trim()]);
expect(links).toEqual([
['/collection', 'Catalogue 7'],
['/collection/wanted', 'Wanted 5'],
['/collection/upgrades', 'Upgrades 6'],
['/collection/activity', 'Activity 3'],
['/collection/following', 'Following 2'],
['/collection/blocked', 'Blocked 4'],
['/collection/unmatched', 'Unmatched 3'],
['/collection', 'Overview'],
['/collection/reports', 'Reports'],
['/collection/duplicates', 'Duplicates'],
['/collection/suspect-sources', 'Suspect sources'],
['/collection/missing', 'Missing files']
]);
expect(screen.getByRole('link', { name: /activity/i })).toHaveAttribute('aria-current', 'page');
expect(screen.getByRole('link', { name: /^catalogue/i })).not.toHaveAttribute('aria-current');
expect(screen.getByRole('link', { name: /missing files/i })).toHaveAttribute('aria-current', 'page');
expect(screen.getByRole('link', { name: /^overview/i })).not.toHaveAttribute('aria-current');
expect(screen.getByTestId('tab-body')).toBeTruthy();
});
test('when nothing needs a person the verdict says so', () => {
setup({ ...counts, unmatched: 0 });
expect(screen.getByTestId('collection-verdict').textContent).toMatch(/5 albums wanted, 3 downloading\. Nothing needs you\./);
expect(screen.queryByTestId('tab-attention')).toBeNull();
});
test('downloads waiting on a person lead the page and mark Activity', () => {
setup({ ...counts, attention: 2 });
const verdict = screen.getByTestId('collection-verdict');
expect(verdict.textContent).toMatch(/2 downloads need you/);
expect(screen.getByRole('link', { name: /see activity/i }).getAttribute('href')).toBe('/collection/activity');
expect(screen.getByTestId('tab-attention').textContent).toBe('2');
});
test('library albums waiting to be matched need a person, and link to Unmatched', () => {
setup();
expect(screen.getByTestId('collection-verdict').textContent).toMatch(
/5 albums wanted, 3 downloading\. 3 albums in your library need matching\./
);
expect(screen.getByRole('link', { name: /see unmatched/i }).getAttribute('href')).toBe('/collection/unmatched');
});
// The library's health queues moved here from Admin: their counts
// come from the admin summary, accented, and a line names the ones waiting.
test('the library health queues carry what waits on you, and a line links to each', () => {
setup(counts, '/collection', {
test('the health queues carry what waits on you, and a line links to each', () => {
setup('/collection', {
...clear,
reports: { count: 2, since: null },
duplicates: { count: 5, since: null },
@@ -111,13 +71,20 @@ describe('/collection layout', () => {
]);
});
test('with nothing waiting there is no health line', () => {
test('with nothing waiting the line says nothing needs you', () => {
setup();
expect(screen.queryByTestId('collection-health')).toBeNull();
expect(screen.getByTestId('collection-health').textContent?.trim()).toBe('Nothing needs you.');
});
});
test("an artist's page sits under Catalogue", () => {
setup(counts, '/collection/artist/blur');
expect(screen.getByRole('link', { name: /^catalogue/i })).toHaveAttribute('aria-current', 'page');
describe('/collection overview', () => {
test('lists each queue with something in it, then the empty ones on one line', () => {
mockSummary({ ...clear, missing: { count: 3, since: new Date().toISOString() } });
render(CollectionPage);
const rows = screen.getAllByTestId('collection-queue');
expect(rows).toHaveLength(1);
expect(rows[0].textContent).toMatch(/3 missing files/);
expect(rows[0].querySelector('a')?.getAttribute('href')).toBe('/collection/missing');
expect(screen.getByTestId('collection-clear').textContent?.trim()).toBe('No reports, duplicates, suspect sources.');
});
});
@@ -42,11 +42,10 @@
//
// Except for one recording filling several of an album's slots (class
// mismatch), where a merge is the wrong answer: it keeps one copy's
// title whether or not it is the audio's, and fetches nothing. There an
// admin says which song the recording is, or that they can't tell, and the
// group settles as the resolver would have: copies in other songs' slots are
// removed, the release they came from is set aside, and the album is fetched
// again.
// title whether or not it is the audio's. There an admin says which song the
// recording is, or that they can't tell, and the group settles as the
// resolver would have: copies in other songs' slots are removed, and those
// slots show as missing until a good copy is in the library folder.
type Tab = DuplicatesView | 'resolved';
const fromUrl = page.url.searchParams.get('view');
@@ -172,11 +171,7 @@
try {
const result = await refetchDuplicateGroup(group.id, { keep_track_id: slotPick[group.id] ?? '' });
const removed = `Removed ${plural(result.removed_paths.length, 'file', 'files')}`;
pushToast(
result.blocked.length > 0
? `${removed} and set aside the release they came from. The album will be fetched again.`
: `${removed}. The album will be fetched again, but Minstrel didn't download these files, so the same ones may come back.`
);
pushToast(`${removed}. Their slots show as missing until a good copy is in the library.`);
query.refetch();
} catch (e: unknown) {
pushToast(errMessage(e), 'error');
@@ -283,8 +278,8 @@
<p class="text-text-secondary">
Tracks that hold the same recording more than once. Most settle on their own: a song held twice
on one album is merged, copies on different releases count as one song, two versions of a song
are left alone, and a file filling another song's track slot is removed so the album is fetched
again. What's left here needs you.
are left alone, and a file filling another song's track slot is removed, leaving that slot
missing. What's left here needs you.
</p>
</header>
@@ -344,12 +339,12 @@
{:else if item.action === 'duplicate_wrong_file' && !item.details.kept_title}
<p class="text-text-primary">
{item.details.artist}: one recording was filed as {removed.map((r) => r.title).join(' and ')},
and it is none of them. Removed; the album will be fetched again.
and it is none of them. Removed; those slots show as missing.
</p>
{:else if item.action === 'duplicate_wrong_file'}
<p class="text-text-primary">
{item.details.artist}: the recording of {item.details.kept_title} was also filed as
{removed.map((r) => r.title).join(', ')}. Removed from there; the album will be fetched again.
{removed.map((r) => r.title).join(', ')}. Removed from there; those slots show as missing.
</p>
{:else}
<p class="text-text-primary">
@@ -455,11 +450,11 @@
{#if refetching === group.id}
Removing…
{:else if confirmingRefetch === group.id}
Remove {plural(refetchRemoves(group).length, 'file', 'files')} and get it again
Remove {plural(refetchRemoves(group).length, 'file', 'files')}
{:else if picked}
Keep “{picked.title}”…
{:else}
Get it again…
Remove the copies…
{/if}
</button>
{:else}
@@ -527,8 +522,8 @@
{:else}
All {plural(group.members.length, 'copy', 'copies')} will be deleted from disk.
{/if}
Their tracks stay, marked missing, with their likes and plays. The release the files came
from is set aside, and the album is fetched again from another one.
Their tracks stay, marked missing, with their likes and plays, until a good copy is in the
library folder.
</p>
<button
type="button"
@@ -18,8 +18,7 @@ vi.mock('#lib/api/admin.js', () => ({
}),
refetchDuplicateGroup: vi.fn().mockResolvedValue({
kept_track_id: null,
removed_paths: ['/music/Moe Shop/WWW (2020)/www-01.mp3', '/music/Moe Shop/WWW (2020)/www-02.mp3'],
blocked: ['Moe Shop - WWW [WEB]']
removed_paths: ['/music/Moe Shop/WWW (2020)/www-01.mp3', '/music/Moe Shop/WWW (2020)/www-02.mp3']
})
}));
vi.mock('#lib/player/store.svelte.js', () => ({ playQueue: vi.fn() }));
@@ -282,23 +281,23 @@ describe('admin duplicates', () => {
return r;
}
test('offers Get it again instead of Merge, with no copy proposed', () => {
test('offers Remove the copies instead of Merge, with no copy proposed', () => {
renderWith(slots());
expect(screen.queryByRole('button', { name: 'Merge…' })).toBeNull();
expect(screen.getByRole('button', { name: 'Get it again…' })).toBeTruthy();
expect(screen.getByRole('button', { name: 'Remove the copies…' })).toBeTruthy();
expect(screen.getAllByRole('radio').some((r) => (r as HTMLInputElement).checked)).toBe(false);
expect(screen.queryByTestId('survivor-badge')).toBeNull();
});
test("can't tell: every copy goes, after a second click", async () => {
renderWith(slots());
await fireEvent.click(screen.getByRole('button', { name: 'Get it again…' }));
await fireEvent.click(screen.getByRole('button', { name: 'Remove the copies…' }));
expect(refetchDuplicateGroup).not.toHaveBeenCalled();
const confirm = text(screen.getByTestId('refetch-confirm'));
expect(confirm).toContain('All 2 copies will be deleted from disk');
expect(confirm).toContain('the album is fetched again from another one');
expect(confirm).toContain('until a good copy is in the library folder');
await fireEvent.click(screen.getByRole('button', { name: 'Remove 2 files and get it again' }));
await fireEvent.click(screen.getByRole('button', { name: 'Remove 2 files' }));
expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: '' });
});
@@ -310,7 +309,7 @@ describe('admin duplicates', () => {
expect(text(screen.getByTestId('refetch-confirm'))).toContain(
'The copy titled “WWW (instrumental)” stays, and 1 copy under other titles will be deleted from disk'
);
await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file and get it again' }));
await fireEvent.click(screen.getByRole('button', { name: 'Remove 1 file' }));
expect(refetchDuplicateGroup).toHaveBeenCalledWith('g-1', { keep_track_id: 'www-02' });
});
@@ -318,7 +317,7 @@ describe('admin duplicates', () => {
renderWith(slots());
await fireEvent.click(screen.getAllByRole('radio')[0]);
await fireEvent.click(screen.getByRole('button', { name: "I can't tell which song it is" }));
expect(screen.getByRole('button', { name: 'Get it again…' })).toBeTruthy();
expect(screen.getByRole('button', { name: 'Remove the copies…' })).toBeTruthy();
expect(screen.queryByTestId('song-badge')).toBeNull();
});
});
@@ -491,11 +490,11 @@ describe('admin duplicates', () => {
const items = screen.getAllByTestId('resolved-item').map(text);
expect(items[0]).toContain('Moe Shop: Lovesick and Lovesick (Instrumental) are different versions, not duplicates. Both kept.');
expect(items[1]).toContain(
'Savant: the recording of Void was also filed as Reach. Removed from there; the album will be fetched again.'
'Savant: the recording of Void was also filed as Reach. Removed from there; those slots show as missing.'
);
expect(items[1]).toContain('/data/Music/Savant/Void/17 - Reach.m4a');
expect(items[2]).toContain(
'Shnabubula: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; the album will be fetched again.'
'Shnabubula: one recording was filed as Fading Light and Looking for Answers, and it is none of them. Removed; those slots show as missing.'
);
});
});
@@ -1,12 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import FollowList from '#lib/components/wanted/FollowList.svelte';
import ReleaseProfilesCard from '#lib/components/ReleaseProfilesCard.svelte';
</script>
<svelte:head><title>{pageTitle('Collection · Following')}</title></svelte:head>
<div class="space-y-6">
<FollowList />
<ReleaseProfilesCard />
</div>
+9 -149
View File
@@ -1,31 +1,17 @@
<script lang="ts">
import { plural } from '#lib/utils/plural.js';
import { pageTitle } from '#lib/branding.js';
import { ChevronDown, FolderX, Music2, Search, X } from 'lucide-svelte';
import { useQueryClient } from '@tanstack/svelte-query';
import {
createMissingFilesQuery,
getReacquisitionSettings,
type ReacquisitionSettings
} from '#lib/api/admin.js';
import { removeWant, searchWant } from '#lib/api/wanted.js';
import { qk } from '#lib/api/queries.js';
import { errMessage } from '#lib/api/errors.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
import { FolderX, Music2 } from 'lucide-svelte';
import { createMissingFilesQuery } from '#lib/api/admin.js';
import { relativeTime } from '#lib/utils/relativeTime.js';
import { formatDuration } from '#lib/media/duration.js';
import { coverUrl } from '#lib/media/covers.js';
import { needsYou, searched, wantStatus } from '#lib/wanted/wantStatus.js';
import WantCandidates from '#lib/components/WantCandidates.svelte';
import { onMount } from 'svelte';
import type { AdminMissingGroup, Want } from '#lib/api/types.js';
import type { AdminMissingGroup } from '#lib/api/types.js';
// Files the scan looked for and could not find, by folder, with where each
// folder's album stands on the wanted list. A
// missing file keeps its track row, its play history and its likes,
// because the file may come back: the scanner clears the mark by itself,
// and adopts the row if it returns under a new name. Nothing on
// this page deletes a track; its actions are the wanted list's own.
// Files the scan looked for and could not find, by folder. A missing file
// keeps its track row, its play history and its likes, because the file may
// come back: the scanner clears the mark by itself, and adopts the row if it
// returns under a new name. Nothing on this page deletes a track.
const PAGE_SIZE = 50;
@@ -39,56 +25,6 @@
const total = $derived(query.data?.total ?? 0);
const shown = $derived(groups.reduce((n, g) => n + g.tracks.length, 0));
const hasMore = $derived(offset + shown < total);
// What happens to these is set under Acquisition; the line above
// the list says what it is now, since this is where the question comes up.
let policy = $state<ReacquisitionSettings | null>(null);
onMount(async () => {
try {
policy = await getReacquisitionSettings();
} catch {
policy = null;
}
});
// A folder's want, acted on here as on the wanted list.
const client = useQueryClient();
let busy = $state<string | null>(null);
let searching = $state<string | null>(null);
let open = $state<string | null>(null);
const refresh = () =>
Promise.all([
client.invalidateQueries({ queryKey: ['adminMissingFiles'] }),
client.invalidateQueries({ queryKey: ['adminWants'] })
]);
async function onSearch(w: Want) {
searching = w.id;
try {
const r = await searchWant(w.id);
pushToast(searched(w, r), r.outcome === 'error' ? 'error' : 'info');
await Promise.all([refresh(), client.invalidateQueries({ queryKey: qk.wantCandidates(w.id) })]);
} catch (e) {
pushToast(errMessage(e), 'error');
} finally {
searching = null;
}
}
async function onRemove(w: Want) {
busy = w.id;
try {
await removeWant(w.id);
pushToast(`${w.title} is off the wanted list, and won't be fetched back.`);
await refresh();
} catch (e) {
pushToast(errMessage(e), 'error');
} finally {
busy = null;
}
}
</script>
<svelte:head><title>{pageTitle('Collection · Missing files')}</title></svelte:head>
@@ -108,21 +44,11 @@
</div>
<p class="text-text-secondary">
Tracks whose audio file the last scan couldn't find. They keep their play
history and likes, and stop being offered anywhere until the file returns.
history and likes, and stop being offered anywhere until a file is back in the library
folder.
</p>
</header>
<p class="text-sm text-text-secondary" data-testid="reacquisition-policy">
{#if policy}
{policy.enabled
? `Albums missing for ${policy.grace_hours} hours go back on the wanted list by themselves.`
: 'Missing albums are not wanted back automatically.'}
{/if}
<a href="/admin/acquisition#reacquisition" class="text-accent-fg hover:underline">
{policy ? 'Change' : 'Set what happens to missing files'}
</a>
</p>
{#if query.isPending}
<p class="text-text-secondary">Checking what's missing…</p>
{:else if query.isError}
@@ -158,72 +84,6 @@
</span>
</div>
<!-- Where this folder's album stands on the wanted list. Without it
the only way to tell "not wanted yet" from "wanted, nothing has
come" is to go and read the wanted list. -->
{#if group.reacquisition}
{@const r = group.reacquisition}
{@const w = r.want}
<div class="space-y-1.5 border-b border-border px-4 py-2" data-testid="reacquisition-state">
<div class="flex flex-wrap items-center justify-between gap-2">
<div class="min-w-0 space-y-0.5 text-xs">
<p class="text-text-secondary">
{#if r.held_at}
Held again {relativeTime(r.held_at)}. The rows here clear on the next scan.
{:else if r.wanted_at}
Wanted back since {relativeTime(r.wanted_at)}.
{/if}
</p>
{#if w && !r.held_at}
<p
class={needsYou(w) ? 'text-text-primary' : 'text-text-secondary'}
data-testid="missing-want-status"
>
{wantStatus(w)}
{#if needsYou(w)}
<a href="/collection/activity" class="ml-1 text-accent-fg hover:underline">Decide on Activity</a>
{/if}
</p>
{/if}
</div>
{#if w && !r.held_at}
<div class="flex shrink-0 flex-wrap justify-end gap-1.5">
<button
type="button"
onclick={() => onSearch(w)}
disabled={searching !== null || !!w.grab?.live}
aria-label="Search for {w.title} now"
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
>
<Search size={12} strokeWidth={2} /> {searching === w.id ? 'Searching…' : 'Search'}
</button>
<button
type="button"
onclick={() => (open = open === w.id ? null : w.id)}
aria-expanded={open === w.id}
aria-label="Releases found for {w.title}"
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary"
>
Releases <ChevronDown size={12} strokeWidth={2} class={open === w.id ? 'rotate-180' : ''} />
</button>
<button
type="button"
onclick={() => onRemove(w)}
disabled={busy === w.id}
aria-label="Stop wanting {w.title}"
class="inline-flex items-center gap-1 rounded-md border border-border px-2.5 py-1 text-xs text-text-secondary hover:bg-surface-hover hover:text-text-primary disabled:opacity-50"
>
<X size={12} strokeWidth={2} /> Remove
</button>
</div>
{/if}
</div>
{#if w && open === w.id}
<WantCandidates wantId={w.id} title={w.title} />
{/if}
</div>
{/if}
<ul class="divide-y divide-border">
{#each group.tracks as t (t.track_id)}
<li class="flex items-center gap-3 px-4 py-2" data-testid="missing-track-row">
@@ -1,36 +1,12 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { fireEvent, render, screen, waitFor } from '@testing-library/svelte';
import { render, screen } from '@testing-library/svelte';
import { mockQuery } from '../../../test-utils/query';
import type { AdminMissingResponse, Want } from '#lib/api/types.js';
import type { AdminMissingResponse } from '#lib/api/types.js';
// The page reads the re-acquisition policy to say what happens to these;
// the settings themselves are on Admin › Acquisition.
vi.mock('#lib/api/admin.js', () => ({
createMissingFilesQuery: vi.fn(),
getReacquisitionSettings: vi.fn().mockResolvedValue({
enabled: true,
grace_hours: 24,
max_per_pass: 20,
unnameable_albums: 0
})
}));
// A folder's want is acted on here as on the wanted list.
vi.mock('#lib/api/wanted.js', () => ({
removeWant: vi.fn().mockResolvedValue(undefined),
searchWant: vi.fn().mockResolvedValue({
outcome: 'nothing', considered: 0, best_release: '', best_verdict: '', narrowed: []
}),
createCandidatesQuery: vi.fn(),
grabCandidate: vi.fn(),
blockCandidate: vi.fn(),
unblockRelease: vi.fn()
}));
vi.mock('#lib/stores/toast.svelte.js', () => ({ pushToast: vi.fn() }));
vi.mock('#lib/api/admin.js', () => ({ createMissingFilesQuery: vi.fn() }));
import MissingPage from './+page.svelte';
import { createMissingFilesQuery } from '#lib/api/admin.js';
import { removeWant, searchWant } from '#lib/api/wanted.js';
import { pushToast } from '#lib/stores/toast.svelte.js';
const DAY = 24 * 3_600_000;
@@ -57,7 +33,6 @@ const response: AdminMissingResponse = {
{
directory: '/music/Linkin Park/Minutes to Midnight',
missing_since: new Date(Date.now() - 3 * DAY).toISOString(),
reacquisition: null,
tracks: [
track('Given Up', { lastPlayed: new Date(Date.now() - 2 * DAY).toISOString() }),
track('Bleed It Out')
@@ -66,7 +41,6 @@ const response: AdminMissingResponse = {
{
directory: '/music/Boards of Canada/Geogaddi',
missing_since: new Date(Date.now() - 9 * DAY).toISOString(),
reacquisition: null,
tracks: [track('1969')]
}
]
@@ -74,13 +48,6 @@ const response: AdminMissingResponse = {
afterEach(() => vi.clearAllMocks());
// Whitespace-normalised text of a testid'd element. Svelte templates wrap
// mid-sentence, so raw textContent has newlines where the rendered page has
// single spaces — asserting on it directly makes tests fail on reflow.
function text(testId: string): string {
return (screen.getByTestId(testId).textContent ?? '').replace(/\s+/g, ' ').trim();
}
function renderWith(data: AdminMissingResponse | undefined, extra = {}) {
vi.mocked(createMissingFilesQuery).mockReturnValue(
mockQuery({ data, ...extra }) as ReturnType<typeof createMissingFilesQuery>
@@ -88,46 +55,7 @@ function renderWith(data: AdminMissingResponse | undefined, extra = {}) {
return render(MissingPage);
}
function want(extra: Partial<Want> = {}): Want {
return {
id: 'w-1',
release_group_mbid: 'rg-1',
title: 'Minutes to Midnight',
artist_mbid: 'lp',
artist_name: 'Linkin Park',
primary_type: 'Album',
secondary_types: [],
year: '2007',
reason: 'missing',
wanted_at: new Date(Date.now() - 2 * DAY).toISOString(),
held_at: null,
image_url: '',
search: {
searched_at: new Date(Date.now() - 3_600_000).toISOString(),
outcome: 'nothing',
considered: 0,
best_release: '',
best_verdict: '',
error: ''
},
...extra
};
}
function wantedBack(w: Want | null = want()): AdminMissingResponse {
const withState = structuredClone(response);
withState.groups[0].reacquisition = { wanted_at: new Date(Date.now() - 2 * DAY).toISOString(), held_at: null, want: w };
return withState;
}
describe('/collection/missing', () => {
test('says what happens to missing files, and links to where it is set', async () => {
renderWith(response);
const line = screen.getByTestId('reacquisition-policy');
await screen.findByText(/missing for 24 hours go back on the wanted list/i);
expect(line.querySelector('a')?.getAttribute('href')).toBe('/admin/acquisition#reacquisition');
});
test('groups rows under their directory', () => {
renderWith(response);
expect(screen.getByText('/music/Linkin Park/Minutes to Midnight')).toBeTruthy();
@@ -185,63 +113,6 @@ describe('/collection/missing', () => {
expect(screen.getByText(/couldn't load the missing files/i)).toBeTruthy();
});
// Not wanted yet is the common case for a folder that just went missing;
// a line saying so would be noise on every row.
test('no re-acquisition line before the album is wanted', () => {
renderWith(response);
expect(screen.queryByTestId('reacquisition-state')).toBeNull();
});
test('an album wanted back says since when, and what its last search found', () => {
renderWith(wantedBack());
expect(text('reacquisition-state')).toMatch(/wanted back since 2d ago/i);
expect(text('missing-want-status')).toBe('Searched 1h ago: nothing found');
});
test('its download, when one is running, is the line', () => {
renderWith(
wantedBack(
want({
grab: {
id: 'g', name: 'LP - MtM [FLAC]', grabbed_at: new Date().toISOString(), origin: 'schedule', quality: 'FLAC',
live: true, end_reason: '', progress: 0.42, import_state: 'downloading', import_reason: '', end_detail: '',
imported_at: null, imported_files: 0
}
})
)
);
expect(text('missing-want-status')).toBe('Downloading 42% · LP - MtM [FLAC]');
expect(screen.getByRole('button', { name: /search for minutes to midnight now/i })).toHaveProperty('disabled', true);
});
test('Search runs one now and says what it found', async () => {
renderWith(wantedBack());
await fireEvent.click(screen.getByRole('button', { name: /search for minutes to midnight now/i }));
await waitFor(() => expect(searchWant).toHaveBeenCalledWith('w-1'));
await waitFor(() => expect(pushToast).toHaveBeenCalledWith('Nothing found for Minutes to Midnight.', 'info'));
});
test('Remove takes it off the wanted list', async () => {
renderWith(wantedBack());
await fireEvent.click(screen.getByRole('button', { name: /stop wanting minutes to midnight/i }));
await waitFor(() => expect(removeWant).toHaveBeenCalledWith('w-1'));
expect(pushToast).toHaveBeenCalledWith("Minutes to Midnight is off the wanted list, and won't be fetched back.");
});
test('an album held again says so', () => {
const withState = structuredClone(response);
withState.groups[0].reacquisition = {
wanted_at: new Date(Date.now() - 5 * DAY).toISOString(),
held_at: new Date(Date.now() - DAY).toISOString(),
want: want({ held_at: new Date(Date.now() - DAY).toISOString() })
};
renderWith(withState);
expect(text('reacquisition-state')).toMatch(/held again 1d ago/i);
// Nothing left to search for.
expect(screen.queryByTestId('missing-want-status')).toBeNull();
expect(screen.queryByRole('button', { name: /search for/i })).toBeNull();
});
// Paging only appears when it can do something: a single page of results
// should not render dead Previous/Next buttons.
test('no pager when everything fits on one page', () => {
@@ -17,9 +17,7 @@
// The duplicate resolver holds each one back from radio and the mixes, and
// merges it away where the library has a clean copy. A marker
// is a reason to look, not proof, so each row says what was done and offers
// the undo: "This one is fine" lets the track back for good. A rip's album
// stays wanted for a clean copy, searched for weekly and filed over the rip
// when it comes.
// the undo: "This one is fine" lets the track back for good.
const queryStore = createSuspectSourcesQuery();
const query = $derived($queryStore);
@@ -99,9 +97,7 @@
a video site, and can be the wrong audio: a live take, a music-video edit, or
something else entirely. Each one is kept out of radio and the mixes, though it still
plays when you choose it, and it is merged away where the library has a clean copy of the
same song. Where it is the only copy, its album is searched for a clean copy once a week,
under <a href="/collection/upgrades" class="text-accent-fg hover:underline">Upgrades</a>. If one
is fine, say so and it goes back in.
same song. If one is fine, say so and it goes back in.
</p>
</header>
@@ -181,13 +177,6 @@
<span class="text-xs text-text-secondary" data-testid="suspect-verdict">
Held back{#if t.verdict_at && !changed[t.track_id]}&nbsp;{relativeTime(t.verdict_at)}{/if}
</span>
{#if t.replacing}
<a href="/collection/upgrades" class="text-xs text-text-muted hover:underline" data-testid="suspect-searched">
{t.searched_at
? `Looked for a clean copy ${relativeTime(t.searched_at)}`
: 'A clean copy is wanted'}
</a>
{/if}
<button
type="button"
onclick={() => setVerdict(t, 'fine')}
@@ -30,8 +30,6 @@ function track(title: string, file: string, markers: string[], disc: number | nu
markers,
verdict: 'suspect',
verdict_at: new Date(Date.now() - 3_600_000).toISOString(),
replacing: false,
searched_at: null
};
}
@@ -138,17 +136,4 @@ describe('Suspect sources page', () => {
expect(await screen.findByText('Marked fine')).toBeInTheDocument();
expect(screen.getByRole('button', { name: 'Hold back again' })).toBeInTheDocument();
});
// A rip's album is wanted for a clean copy, and the row says when
// one was last looked for.
test('shows that a clean copy is wanted, and when it was looked for', () => {
const t = track('Strobelite', 'Gorillaz - Strobelite (Official Video).mp3', ['music video']);
t.replacing = true;
t.searched_at = new Date(Date.now() - 7_200_000).toISOString();
mocked.mockReturnValue(infinite([page(0, 1, [{ directory: HUMANZ, tracks: [t] }])]));
render(SuspectSourcesPage);
const line = screen.getByTestId('suspect-searched');
expect(line).toHaveTextContent(/Looked for a clean copy/);
expect(line).toHaveAttribute('href', '/collection/upgrades');
});
});
@@ -1,8 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import UnmatchedList from '#lib/components/wanted/UnmatchedList.svelte';
</script>
<svelte:head><title>{pageTitle('Collection · Unmatched')}</title></svelte:head>
<UnmatchedList />
@@ -1,8 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import WantList from '#lib/components/wanted/WantList.svelte';
</script>
<svelte:head><title>{pageTitle('Collection · Upgrades')}</title></svelte:head>
<WantList list="upgrade" />
@@ -1,8 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import WantList from '#lib/components/wanted/WantList.svelte';
</script>
<svelte:head><title>{pageTitle('Collection · Wanted')}</title></svelte:head>
<WantList list="wanted" />
-232
View File
@@ -1,232 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import { createCatalogueSearchQuery } from '#lib/api/catalogue.js';
import { createRequest } from '#lib/api/requests.js';
import { qk } from '#lib/api/queries.js';
import { useQueryClient } from '@tanstack/svelte-query';
import DiscoverResultCard from '#lib/components/DiscoverResultCard.svelte';
import DiscoverTabs from '#lib/components/DiscoverTabs.svelte';
import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
import SuggestionFeed from '#lib/components/SuggestionFeed.svelte';
import Modal from '#lib/components/Modal.svelte';
import type {
CatalogueSearchResult,
RequestKind
} from '#lib/api/types.js';
const queryClient = useQueryClient();
// Local input is the source of truth for the discover query — Shell's global
// SearchInput targets /search, not /discover. We debounce by 250ms before
// pushing into `debouncedQ`, which is what the query factory observes.
let inputValue = $state('');
let debouncedQ = $state('');
let activeKind: RequestKind = $state('artist');
let debounceTimer: ReturnType<typeof setTimeout> | null = null;
$effect(() => {
const v = inputValue;
if (debounceTimer) clearTimeout(debounceTimer);
debounceTimer = setTimeout(() => {
debouncedQ = v.trim();
}, 250);
return () => {
if (debounceTimer) clearTimeout(debounceTimer);
};
});
const queryStore = $derived(createCatalogueSearchQuery(debouncedQ, activeKind));
const query = $derived($queryStore);
const results = $derived((query.data ?? []) as CatalogueSearchResult[]);
// Track-kind confirm modal: nulled out = closed.
let modalResult: CatalogueSearchResult | null = $state(null);
// In-session optimistic flip — once a Request goes through, we flip the
// card to 'requested' immediately. Cleared only on full page reload, which
// is fine for a short-lived discover session.
let optimisticRequested: Set<string> = $state(new Set());
function cardState(r: CatalogueSearchResult) {
if (r.in_library) return 'kept' as const;
if (r.requested || optimisticRequested.has(r.mbid)) return 'requested' as const;
return 'requestable' as const;
}
// Backend validates kind→required-MBID-fields, not the human strings, so
// imperfect derivations of artist_name from secondary_text won't block the
// request. We pass the data we have and let the server take care of the rest.
function buildRequestParams(r: CatalogueSearchResult, kind: RequestKind) {
if (kind === 'artist') {
return {
kind,
artist_mbid: r.artist_mbid || r.mbid,
artist_name: r.name
};
}
if (kind === 'album') {
return {
kind,
artist_mbid: r.artist_mbid,
album_mbid: r.album_mbid || r.mbid,
artist_name: r.secondary_text,
album_title: r.name
};
}
// track
return {
kind,
artist_mbid: r.artist_mbid,
album_mbid: r.album_mbid,
track_mbid: r.mbid,
artist_name: r.secondary_text,
album_title: r.secondary_text,
track_title: r.name
};
}
async function submitRequest(r: CatalogueSearchResult) {
try {
await createRequest(buildRequestParams(r, activeKind));
const next = new Set(optimisticRequested);
next.add(r.mbid);
optimisticRequested = next;
// Surface the new request on /requests right away (+ start its poll).
queryClient.invalidateQueries({ queryKey: qk.myRequests() });
} catch {
// Swallowed, with no toast: the card stays in 'requestable' so the
// user can retry.
}
}
function handleRequestClick(r: CatalogueSearchResult) {
if (activeKind === 'track') {
modalResult = r;
} else {
submitRequest(r);
}
}
function confirmModal() {
if (modalResult) submitRequest(modalResult);
modalResult = null;
}
function cancelModal() {
modalResult = null;
}
const tabs: { kind: RequestKind; label: string }[] = [
{ kind: 'artist', label: 'Artists' },
{ kind: 'album', label: 'Albums' },
{ kind: 'track', label: 'Tracks' }
];
</script>
<svelte:head><title>{pageTitle('Discover')}</title></svelte:head>
<!--
Page layout: a full-height flex column so the persistent chrome
(DiscoverTabs, search input, facet tabs) stays anchored at the top
while only the result grid scrolls. Main has overflow-y-auto, but
with h-full + flex-col + min-h-0 on the scroll region, this page
contains its own overflow and main's scroll never triggers.
-->
<div class="flex h-full flex-col gap-4">
<DiscoverTabs />
<input
type="search"
aria-label="Search MusicBrainz"
placeholder="Search artists, albums, or tracks"
bind:value={inputValue}
class="w-full rounded-md border border-border bg-background px-3 py-2 text-text-primary placeholder:text-text-muted focus:outline-hidden focus:ring-2 focus:ring-accent"
/>
{#if debouncedQ === ''}
<div class="min-h-0 flex-1 overflow-y-auto pb-4">
<SuggestionFeed />
</div>
{:else}
<header class="space-y-1">
<h2 class="font-display text-2xl font-medium text-text-primary">
Add music to the library
</h2>
<p class="text-text-secondary">
Search MusicBrainz to add new artists, albums, or tracks.
</p>
</header>
<nav aria-label="Result kind" class="border-b border-border">
<ul class="flex gap-2">
{#each tabs as tab (tab.kind)}
<li>
<button
type="button"
aria-pressed={activeKind === tab.kind}
class="border-b-2 px-3 py-2 text-sm {activeKind === tab.kind
? 'border-accent text-text-primary'
: 'border-transparent text-text-secondary hover:text-text-primary'}"
onclick={() => (activeKind = tab.kind)}
>
{tab.label}
</button>
</li>
{/each}
</ul>
</nav>
<div class="min-h-0 flex-1 overflow-y-auto pb-4">
{#if query.isError}
<ApiErrorBanner error={query.error} onRetry={query.refetch} />
{:else if query.isPending}
<p class="text-text-secondary">Searching…</p>
{:else if results.length === 0}
<p class="text-text-secondary">Nothing to add for that search yet.</p>
{:else}
<div class="grid grid-cols-2 gap-4 sm:grid-cols-3 lg:grid-cols-4 xl:grid-cols-5">
{#each results as r (r.mbid)}
<DiscoverResultCard
kind={activeKind}
title={r.name}
subtitle={r.secondary_text}
imageUrl={r.image_url || undefined}
state={cardState(r)}
onRequest={() => handleRequestClick(r)}
/>
{/each}
</div>
{/if}
</div>
{/if}
</div>
<Modal
title="Add the album?"
open={modalResult !== null}
onClose={cancelModal}
>
{#if modalResult}
<p class="-mt-2 text-text-secondary">
Requesting <em class="font-medium text-text-primary">{modalResult.name}</em>
will add <em class="font-medium text-text-primary">{modalResult.secondary_text}</em>.
Continue?
</p>
<div class="mt-5 flex justify-end gap-2">
<button
type="button"
class="rounded-md bg-action-secondary px-3 py-1.5 text-sm text-action-fg"
onclick={cancelModal}
>
Cancel
</button>
<button
type="button"
class="rounded-md bg-action-primary px-3 py-1.5 text-sm text-action-fg"
onclick={confirmModal}
>
Add the album
</button>
</div>
{/if}
</Modal>
-319
View File
@@ -1,319 +0,0 @@
import { afterEach, beforeEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { mockQuery } from '../../test-utils/query';
import { apiClientMock } from '../../test-utils/mocks/client';
import type { CatalogueSearchResult } from '#lib/api/types.js';
import { pageUrlModule } from '../../test-utils/mocks/appState';
// $app/state / $app/navigation must be mocked or rendering the page
// pulls in SvelteKit's client runtime (`notifiable_store is not a
// function`) at module load. Same pattern as the other route tests.
const pageState = vi.hoisted(() => ({
pageUrl: new URL('http://localhost/discover')
}));
vi.mock('$app/state', () => pageUrlModule(pageState));
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
// The catalogue search query factory and createRequest are mocked at the module
// level so each test can shape what the page sees without standing up a
// real QueryClient + network.
vi.mock('#lib/api/catalogue.js', () => ({
createCatalogueSearchQuery: vi.fn()
}));
// SuggestionFeed reaches for the snooze surface too. These are
// stubbed here even though this page-level suite asserts nothing about
// snoozing: a factory-shaped module mock must export everything the
// component tree imports, or rendering the feed throws before any
// assertion runs.
vi.mock('#lib/api/suggestions.js', () => ({
createSuggestionsQuery: vi.fn(),
createSnoozesQuery: vi.fn(),
snoozeSuggestion: vi.fn().mockResolvedValue(undefined),
unsnoozeSuggestion: vi.fn().mockResolvedValue(undefined)
}));
vi.mock('#lib/api/requests.js', () => ({
createRequest: vi.fn().mockResolvedValue({ id: 'r1' })
}));
vi.mock('#lib/api/client.js', () => apiClientMock());
// The page calls useQueryClient() to invalidate qk.myRequests() after a
// submit; stub it so rendering doesn't require a real QueryClient and
// we can assert the invalidation fires.
const queryClientMock = vi.hoisted(() => ({ invalidateQueries: vi.fn() }));
vi.mock('@tanstack/svelte-query', async (importOriginal) => {
const actual = await importOriginal<typeof import('@tanstack/svelte-query')>();
return { ...actual, useQueryClient: () => queryClientMock };
});
import DiscoverPage from './+page.svelte';
import { createCatalogueSearchQuery } from '#lib/api/catalogue.js';
import { createSuggestionsQuery, createSnoozesQuery } from '#lib/api/suggestions.js';
import { createRequest } from '#lib/api/requests.js';
const mockedCreateQuery = createCatalogueSearchQuery as ReturnType<typeof vi.fn>;
const mockedCreateSuggestionsQuery = createSuggestionsQuery as ReturnType<typeof vi.fn>;
const mockedCreateSnoozesQuery = createSnoozesQuery as ReturnType<typeof vi.fn>;
const mockedCreateRequest = createRequest as ReturnType<typeof vi.fn>;
function result(over: Partial<CatalogueSearchResult> = {}): CatalogueSearchResult {
return {
mbid: 'mbid-1',
name: 'Boards of Canada',
secondary_text: 'Electronic',
image_url: '',
artist_mbid: 'art-1',
album_mbid: '',
in_library: false,
requested: false,
...over
};
}
beforeEach(() => {
// Default: empty results, non-pending. Tests override per-case.
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [] }));
// Default: empty suggestion feed so its empty-state copy renders without
// interfering with search-mode tests.
mockedCreateSuggestionsQuery.mockReturnValue(mockQuery({ data: [] }));
// Nothing parked, which keeps the feed's empty-state copy on the
// "no signal yet" branch that this suite's assertions expect.
mockedCreateSnoozesQuery.mockReturnValue(mockQuery({ data: [] }));
});
afterEach(() => {
vi.clearAllMocks();
});
describe('Discover page', () => {
test('initial state (no query) shows the suggestion feed', () => {
render(DiscoverPage);
expect(screen.getByText(/suggested for you/i)).toBeInTheDocument();
});
test('empty input shows the suggestion feed', () => {
render(DiscoverPage);
expect(screen.getByText(/suggested for you/i)).toBeInTheDocument();
// Kind tabs should NOT be visible when input is empty.
expect(
screen.queryByRole('button', { name: 'Artists' })
).not.toBeInTheDocument();
});
test('typing replaces feed with search', async () => {
vi.useFakeTimers();
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'miles' } });
await vi.advanceTimersByTimeAsync(250);
expect(screen.queryByText(/suggested for you/i)).not.toBeInTheDocument();
expect(screen.getByText(/add music to the library/i)).toBeInTheDocument();
// Kind tabs visible when searching.
expect(screen.getByRole('button', { name: 'Artists' })).toBeInTheDocument();
vi.useRealTimers();
});
test('debounced input fires query factory with typed value after 250ms', async () => {
vi.useFakeTimers();
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'boards' } });
// Before the timer elapses, the factory was called only with the
// initial empty string — never with 'boards'.
expect(mockedCreateQuery).not.toHaveBeenCalledWith('boards', 'artist');
await vi.advanceTimersByTimeAsync(250);
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'artist');
vi.useRealTimers();
});
test('switching tabs refetches with the new kind', async () => {
vi.useFakeTimers();
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'boards' } });
await vi.advanceTimersByTimeAsync(250);
// Switch to Albums.
await fireEvent.click(screen.getByRole('button', { name: 'Albums' }));
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'album');
// Then to Tracks.
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
expect(mockedCreateQuery).toHaveBeenLastCalledWith('boards', 'track');
vi.useRealTimers();
});
test('empty results state renders the voice-rule copy', async () => {
vi.useFakeTimers();
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'zzz' } });
await vi.advanceTimersByTimeAsync(250);
await waitFor(() =>
expect(
screen.getByText(/nothing to add for that search yet\./i)
).toBeInTheDocument()
);
vi.useRealTimers();
});
test('artist-kind Request click calls createRequest immediately (no modal)', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'art-mbid',
artist_mbid: 'art-mbid',
name: 'Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'boards' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request boards of canada/i
});
await fireEvent.click(requestBtn);
expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
expect(mockedCreateRequest).toHaveBeenCalledWith(
expect.objectContaining({ kind: 'artist' })
);
// Modal must not be present for non-track kinds.
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('requestable card flips to "Requested" after a successful request', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'art-mbid',
artist_mbid: 'art-mbid',
name: 'Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'boards' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request boards of canada/i
});
await fireEvent.click(requestBtn);
await waitFor(() => {
const flipped = screen.getByRole('button', { name: /already requested/i });
expect(flipped).toBeDisabled();
});
});
test('submitting a request invalidates myRequests so /requests updates (#369)', async () => {
vi.useFakeTimers();
const r = result({ mbid: 'art-mbid', artist_mbid: 'art-mbid', name: 'Boards of Canada' });
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'boards' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request boards of canada/i
});
await fireEvent.click(requestBtn);
await waitFor(() => {
expect(queryClientMock.invalidateQueries).toHaveBeenCalledWith({
queryKey: ['myRequests']
});
});
});
test('track-kind Request click opens confirm modal; Confirm calls createRequest', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'tr-mbid',
artist_mbid: 'art-mbid',
album_mbid: 'al-mbid',
name: 'Roygbiv',
secondary_text: 'Music Has The Right To Children · Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
render(DiscoverPage);
// Type first so the kind tabs become visible (empty-input mode shows the
// suggestion feed and hides tabs).
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'roy' } });
await vi.advanceTimersByTimeAsync(250);
// Switch to track kind.
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request roygbiv/i
});
await fireEvent.click(requestBtn);
// Modal opens with the explanation copy.
const dialog = await screen.findByRole('dialog');
expect(dialog).toBeInTheDocument();
expect(dialog.textContent).toMatch(/continue/i);
// Confirm fires createRequest with kind=track.
await fireEvent.click(screen.getByRole('button', { name: /add the album/i }));
expect(mockedCreateRequest).toHaveBeenCalledTimes(1);
expect(mockedCreateRequest).toHaveBeenCalledWith(
expect.objectContaining({
kind: 'track',
track_mbid: 'tr-mbid',
album_mbid: 'al-mbid',
artist_mbid: 'art-mbid'
})
);
});
test('track-kind modal Cancel does not call createRequest', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'tr-mbid',
artist_mbid: 'art-mbid',
album_mbid: 'al-mbid',
name: 'Roygbiv',
secondary_text: 'Music Has The Right To Children · Boards of Canada'
});
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'roy' } });
await vi.advanceTimersByTimeAsync(250);
await fireEvent.click(screen.getByRole('button', { name: 'Tracks' }));
vi.useRealTimers();
const requestBtn = await screen.findByRole('button', {
name: /request roygbiv/i
});
await fireEvent.click(requestBtn);
await screen.findByRole('dialog');
await fireEvent.click(screen.getByRole('button', { name: /^cancel$/i }));
expect(mockedCreateRequest).not.toHaveBeenCalled();
expect(screen.queryByRole('dialog')).not.toBeInTheDocument();
});
test('in_library result renders kept state regardless of requested', async () => {
vi.useFakeTimers();
const r = result({
mbid: 'kept-1',
name: 'Kind of Blue',
in_library: true,
requested: true
});
mockedCreateQuery.mockReturnValue(mockQuery<CatalogueSearchResult[]>({ data: [r] }));
render(DiscoverPage);
const input = screen.getByLabelText(/search musicbrainz/i);
await fireEvent.input(input, { target: { value: 'kind' } });
await vi.advanceTimersByTimeAsync(250);
vi.useRealTimers();
await waitFor(() => {
expect(screen.getByRole('button', { name: /in library/i })).toBeDisabled();
});
});
});
-101
View File
@@ -1,101 +0,0 @@
<script lang="ts">
import { pageTitle } from '#lib/branding.js';
import { Music2, X } from 'lucide-svelte';
import { useQueryClient } from '@tanstack/svelte-query';
import { createMyRequestsQuery, cancelRequest } from '#lib/api/requests.js';
import { qk } from '#lib/api/queries.js';
import RequestRow, { requestName } from '#lib/components/RequestRow.svelte';
import ApiErrorBanner from '#lib/components/ApiErrorBanner.svelte';
import DiscoverTabs from '#lib/components/DiscoverTabs.svelte';
import type { MusicRequest } from '#lib/api/types.js';
const queryStore = createMyRequestsQuery();
const query = $derived($queryStore);
const requests = $derived((query.data ?? []) as MusicRequest[]);
const client = useQueryClient();
async function onCancel(id: string) {
try {
await cancelRequest(id);
await client.invalidateQueries({ queryKey: qk.myRequests() });
} catch {
// Swallow for v1; toast surface lands later. The row stays put so the
// user can retry — failed cancel doesn't lie about success.
}
}
// Keep the meta line short and readable. We always lead with the artist,
// then a relative-ish date — locale formatting is good enough for v1
// and keeps tests deterministic without pinning Intl.RelativeTimeFormat.
function rowMeta(r: MusicRequest): string {
const when = new Date(r.requested_at).toLocaleDateString();
if (r.kind === 'artist') return `Requested ${when}`;
return `by ${r.artist_name} · ${when}`;
}
function listenHref(r: MusicRequest): string | null {
if (r.matched_track_id) return `/tracks/${r.matched_track_id}`;
if (r.matched_album_id) return `/albums/${r.matched_album_id}`;
if (r.matched_artist_id) return `/artists/${r.matched_artist_id}`;
return null;
}
</script>
<svelte:head><title>{pageTitle('Requests')}</title></svelte:head>
<DiscoverTabs />
<div class="space-y-6 pt-6">
<header class="space-y-1">
<h2 class="font-display text-2xl font-medium text-text-primary">
Your requests
</h2>
<p class="text-text-secondary">
What you've asked Minstrel to add to the library.
</p>
</header>
{#if query.isError}
<ApiErrorBanner error={query.error} onRetry={query.refetch} />
{:else if query.isPending}
<p class="text-text-secondary">Reading the ledger…</p>
{:else if requests.length === 0}
<p class="text-text-secondary">Nothing requested yet.</p>
{:else}
<ul class="divide-y divide-border rounded-lg border border-border bg-surface">
{#each requests as r (r.id)}
{@const href = listenHref(r)}
<RequestRow request={r} meta={rowMeta(r)} testid="request-row">
{#snippet details()}
{#if r.status === 'rejected' && r.notes}
<div class="text-sm text-text-secondary" data-testid="rejection-notes">
{r.notes}
</div>
{/if}
{/snippet}
{#snippet actions()}
{#if r.status === 'pending'}
<button
type="button"
aria-label={`Cancel request for ${requestName(r)}`}
class="inline-flex items-center gap-1 rounded-md border border-border px-3 py-1.5 text-sm text-text-secondary hover:bg-surface-hover"
onclick={() => onCancel(r.id)}
>
<X size={16} strokeWidth={1} /> Cancel
</button>
{:else if r.status === 'completed' && href}
<a
{href}
aria-label={`Listen to ${requestName(r)}`}
class="inline-flex items-center gap-1 text-sm text-accent-fg hover:underline"
>
<Music2 size={16} strokeWidth={1} /> Listen
</a>
{/if}
{/snippet}
</RequestRow>
{/each}
</ul>
{/if}
</div>
-165
View File
@@ -1,165 +0,0 @@
import { afterEach, describe, expect, test, vi } from 'vitest';
import { render, screen, fireEvent, waitFor } from '@testing-library/svelte';
import { mockQuery } from '../../test-utils/query';
import { apiClientMock } from '../../test-utils/mocks/client';
import type { MusicRequest } from '#lib/api/types.js';
import { pageUrlModule } from '../../test-utils/mocks/appState';
// $app/state / $app/navigation must be mocked or rendering the page
// pulls in SvelteKit's client runtime (`notifiable_store is not a
// function`) at module load. Same pattern as the other route tests.
const pageState = vi.hoisted(() => ({
pageUrl: new URL('http://localhost/requests')
}));
vi.mock('$app/state', () => pageUrlModule(pageState));
vi.mock('$app/navigation', () => ({ goto: vi.fn() }));
// Capture invalidateQueries on the mocked QueryClient so the cancel test can
// assert against the same instance the page consumed. Per-file mock OVERRIDES
// the vitest.setup default so assertions see this named spy.
const invalidateQueries = vi.fn().mockResolvedValue(undefined);
vi.mock('@tanstack/svelte-query', async (orig) => {
const actual = (await orig()) as Record<string, unknown>;
return { ...actual, useQueryClient: () => ({ invalidateQueries }) };
});
vi.mock('#lib/api/requests.js', () => ({
createMyRequestsQuery: vi.fn(),
cancelRequest: vi.fn().mockResolvedValue({ id: 'r1' })
}));
vi.mock('#lib/api/queries.js', () => ({
qk: {
myRequests: () => ['myRequests']
}
}));
vi.mock('#lib/api/client.js', () => apiClientMock());
import RequestsPage from './+page.svelte';
import { createMyRequestsQuery, cancelRequest } from '#lib/api/requests.js';
import { qk } from '#lib/api/queries.js';
const mockedCreateMyRequestsQuery = createMyRequestsQuery as ReturnType<typeof vi.fn>;
const mockedCancelRequest = cancelRequest as ReturnType<typeof vi.fn>;
function req(over: Partial<MusicRequest> = {}): MusicRequest {
return {
id: 'r1',
user_id: 'u1',
status: 'pending',
kind: 'album',
artist_mbid: 'art-mbid',
album_mbid: 'al-mbid',
track_mbid: null,
artist_name: 'Boards of Canada',
album_title: 'Music Has The Right To Children',
track_title: null,
decided_at: null,
decided_by: null,
notes: null,
completed_at: null,
matched_track_id: null,
matched_album_id: null,
matched_artist_id: null,
requested_at: '2026-04-28T12:00:00Z',
updated_at: '2026-04-28T12:00:00Z',
imported_album_count: 0,
imported_track_count: 0,
...over
};
}
afterEach(() => {
vi.clearAllMocks();
});
describe('Requests page', () => {
test('renders one row per request from the API', () => {
const rows: MusicRequest[] = [
req({ id: 'r1', kind: 'artist', artist_name: 'Boards of Canada' }),
req({ id: 'r2', kind: 'album', album_title: 'Geogaddi', status: 'completed' }),
req({ id: 'r3', kind: 'track', track_title: 'Roygbiv', status: 'rejected', notes: 'Already in library' })
];
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
render(RequestsPage);
expect(screen.getAllByTestId('request-row')).toHaveLength(3);
expect(screen.getByText('Boards of Canada')).toBeInTheDocument();
expect(screen.getByText('Geogaddi')).toBeInTheDocument();
expect(screen.getByText('Roygbiv')).toBeInTheDocument();
});
test('pending row exposes Cancel; clicking calls cancelRequest and invalidates myRequests', async () => {
const rows: MusicRequest[] = [
req({ id: 'r-pending', status: 'pending', kind: 'album', album_title: 'Geogaddi' })
];
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
render(RequestsPage);
const cancelBtn = screen.getByRole('button', { name: /cancel request for geogaddi/i });
await fireEvent.click(cancelBtn);
await waitFor(() => {
expect(mockedCancelRequest).toHaveBeenCalledWith('r-pending');
expect(invalidateQueries).toHaveBeenCalledWith({ queryKey: qk.myRequests() });
});
});
test('completed row with matched_track_id renders Listen link to /tracks/<id>', () => {
const rows: MusicRequest[] = [
req({
id: 'r-track',
status: 'completed',
kind: 'track',
track_title: 'Roygbiv',
matched_track_id: 'tr-9',
matched_album_id: 'al-9',
matched_artist_id: 'art-9'
})
];
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
render(RequestsPage);
const link = screen.getByRole('link', { name: /listen to roygbiv/i });
expect(link).toHaveAttribute('href', '/tracks/tr-9');
});
test('completed row with only matched_album_id renders Listen link to /albums/<id>', () => {
const rows: MusicRequest[] = [
req({
id: 'r-album',
status: 'completed',
kind: 'album',
album_title: 'Geogaddi',
matched_track_id: null,
matched_album_id: 'al-7',
matched_artist_id: 'art-7'
})
];
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
render(RequestsPage);
const link = screen.getByRole('link', { name: /listen to geogaddi/i });
expect(link).toHaveAttribute('href', '/albums/al-7');
});
test('rejected row renders notes and hides Cancel and Listen', () => {
const rows: MusicRequest[] = [
req({
id: 'r-rej',
status: 'rejected',
kind: 'album',
album_title: 'Geogaddi',
notes: 'Already kept in the library.'
})
];
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: rows }));
render(RequestsPage);
expect(screen.getByTestId('rejection-notes')).toHaveTextContent('Already kept in the library.');
expect(screen.queryByRole('button', { name: /cancel request/i })).not.toBeInTheDocument();
expect(screen.queryByRole('link', { name: /listen to/i })).not.toBeInTheDocument();
});
test('empty list shows the voice-rule "Nothing requested yet." copy', () => {
mockedCreateMyRequestsQuery.mockReturnValue(mockQuery<MusicRequest[]>({ data: [] }));
render(RequestsPage);
expect(screen.getByText(/nothing requested yet\./i)).toBeInTheDocument();
expect(screen.queryAllByTestId('request-row')).toHaveLength(0);
});
});