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
+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" />