Create and delete genre mixes from the web UI

- Add a form to create a cluster mix rule: shown on first visit when there
  are no rules, and from a + in the sidebar for another Listenbrainz user.
  Backed by POST /api/discover/rules, which validates each setting and
  allows one rule per Listenbrainz user.
- Add deleting a user's mixes from a bin in the sidebar, optionally also
  deleting the mixes' playlists from Subsonic. Backed by
  DELETE /api/discover/rules/<id>?delete_playlists=true.
- Stop showing the previous user's mix while a new user's mixes build.
- Remove the per-account Listenbrainz token: LB Radio now always uses
  listenbrainz.token from the config. A migration drops the token columns
  from app_user, and PUT /api/auth/account/listenbrainz is gone.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
judeandClaude Opus 5.5 committed 2026-11-22 09:45:52 +00:00
1 parent f5cb5076ca
commit 93e12cfc72
23 files changed
+701 -344

No files matched your search

+6 -97
View File
@@ -1,44 +1,12 @@
import { FormEvent, useState } from "react";
import { useState } from "react";
import { Account, authApi } from "./api";
import * as Icon from "./icons";
export function AccountView(props: {
account: Account;
onChange: (account: Account) => void;
onLogout: () => void;
onToast: (message: string) => void;
}) {
export function AccountView(props: { account: Account; onLogout: () => void }) {
const { account } = props;
const [token, setToken] = useState("");
const [busy, setBusy] = useState<"save" | "remove" | "logout" | null>(null);
const [error, setError] = useState<string | null>(null);
const saveToken = async (value: string) => {
setBusy(value ? "save" : "remove");
setError(null);
try {
const updated = await authApi.setListenbrainzToken(value);
props.onChange(updated);
setToken("");
props.onToast(
updated.listenbrainz_user
? `Saved the token for ${updated.listenbrainz_user}`
: "Removed the Listenbrainz token",
);
} catch (e) {
setError((e as Error).message);
} finally {
setBusy(null);
}
};
const submit = (e: FormEvent) => {
e.preventDefault();
void saveToken(token.trim());
};
const [busy, setBusy] = useState(false);
const logout = async () => {
setBusy("logout");
setBusy(true);
try {
await authApi.logout();
} catch {
@@ -54,73 +22,14 @@ export function AccountView(props: {
<h1>{account.username}</h1>
</header>
<section className="panel" aria-labelledby="lb-heading">
<div className="panel-header">
<div>
<h2 id="lb-heading">Listenbrainz token</h2>
<p className="hint">
Lets playlistd find new songs for each mix's genres with LB Radio, on top of your
recommendations. Find yours at{" "}
<a href="https://listenbrainz.org/settings/" target="_blank" rel="noreferrer">
listenbrainz.org/settings <Icon.External size={12} />
</a>
. New songs are picked up the next time your mixes are rebuilt.
</p>
</div>
</div>
<p className="token-status">
{account.has_listenbrainz_token ? (
<>
<span className="status-dot ok" aria-hidden="true" />
Saved, for Listenbrainz user <strong>{account.listenbrainz_user}</strong>
</>
) : (
<>
<span className="status-dot" aria-hidden="true" />
No token saved
</>
)}
</p>
<form className="form" onSubmit={submit} aria-label="Listenbrainz token">
<label className="field">
<span>{account.has_listenbrainz_token ? "Replace token" : "Token"}</span>
<input
className="mono"
type="password"
required
value={token}
onChange={(e) => setToken(e.target.value)}
autoComplete="off"
spellCheck={false}
placeholder="xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx"
/>
</label>
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
{account.has_listenbrainz_token && (
<button type="button" className="btn" disabled={!!busy} onClick={() => saveToken("")}>
{busy === "remove" && <span className="spinner" />}
Remove token
</button>
)}
<button type="submit" className="btn primary" disabled={!!busy || !token.trim()}>
{busy === "save" && <span className="spinner light" />}
{busy === "save" ? "Checking…" : "Save token"}
</button>
</div>
</form>
</section>
<section className="panel" aria-labelledby="session-heading">
<div className="panel-header">
<div>
<h2 id="session-heading">Session</h2>
<p className="hint">Logged in as {account.username} in this browser.</p>
</div>
<button className="btn" onClick={logout} disabled={!!busy}>
{busy === "logout" && <span className="spinner" />}
<button className="btn" onClick={logout} disabled={busy}>
{busy && <span className="spinner" />}
Log out
</button>
</div>
+75 -30
View File
@@ -5,14 +5,16 @@ import { MixView, hue } from "./MixView";
import { LikedView } from "./LikedView";
import { TrackedView } from "./TrackedView";
import { AccountView } from "./AccountView";
import { NewMixesView } from "./NewMixesView";
import { DeleteMixesView } from "./DeleteMixesView";
import { PlayerBar } from "./PlayerBar";
import * as Icon from "./icons";
type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" } | { view: "account" };
type Route = { view: "mix"; id?: string } | { view: "liked" } | { view: "tracked" } | { view: "account" } | { view: "new-mixes" } | { view: "delete-mixes" };
function parseHash(): Route {
const [, view, id] = window.location.hash.split("/");
if (view === "liked" || view === "tracked" || view === "account") return { view };
if (view === "liked" || view === "tracked" || view === "account" || view === "new-mixes" || view === "delete-mixes") return { view };
return { view: "mix", id: id || undefined };
}
@@ -28,7 +30,6 @@ function storedRule() {
export function App(props: {
account: Account;
onAccountChange: (account: Account) => void;
onLogout: () => void;
}) {
const [rules, setRules] = useState<Rule[] | null>(null);
@@ -140,6 +141,42 @@ export function App(props: {
);
};
const selectRule = (id: string) => {
setRuleId(id);
setMixes(null);
setLiked([]);
try {
localStorage.setItem("discover.rule", id);
} catch {
/* not essential */
}
window.location.hash = "";
};
const onRuleCreated = (created: Rule) => {
setRules((rs) => [...(rs ?? []), created]);
selectRule(created.id);
setToast({ message: `Building mixes for ${created.tracking_user}. This takes a minute or two.` });
};
const onRuleDeleted = (deleted: Rule, playlistsDeleted: boolean) => {
const remaining = rules?.filter((r) => r.id !== deleted.id) ?? [];
setRules(remaining);
setDetail(null);
if (remaining.length) {
selectRule(remaining[0].id);
} else {
setMixes(null);
setLiked([]);
window.location.hash = "";
}
setToast({
message: playlistsDeleted
? `Deleted the mixes for ${deleted.tracking_user}`
: `Deleted the mixes for ${deleted.tracking_user}. Their playlists stay in Subsonic.`,
});
};
const rebuild = () => {
if (!rule) return;
api.rebuild(rule.id).then(() => {
@@ -160,16 +197,7 @@ export function App(props: {
className="rule-select"
value={rule?.id}
aria-label="Listenbrainz user"
onChange={(e) => {
setRuleId(e.target.value);
setMixes(null);
try {
localStorage.setItem("discover.rule", e.target.value);
} catch {
/* not essential */
}
window.location.hash = "";
}}
onChange={(e) => selectRule(e.target.value)}
>
{rules.map((r) => <option key={r.id} value={r.id}>{r.tracking_user}</option>)}
</select>
@@ -177,9 +205,19 @@ export function App(props: {
{rule && (
<p className="rule-info">
{rule.tracking_user} · last {rule.months} months
<button className="icon-button small" onClick={rebuild} title="Rebuild mixes" aria-label="Rebuild mixes">
<Icon.Refresh size={15} />
</button>
<span className="rule-actions">
<button className="icon-button small" onClick={rebuild} title="Rebuild mixes" aria-label="Rebuild mixes">
<Icon.Refresh size={15} />
</button>
<a href="#/new-mixes" className="icon-button small" title="Mixes for another Listenbrainz user"
aria-label="New mixes for another Listenbrainz user">
<Icon.Plus size={15} />
</a>
<a href="#/delete-mixes" className="icon-button small" title={`Delete the mixes for ${rule.tracking_user}`}
aria-label={`Delete the mixes for ${rule.tracking_user}`}>
<Icon.Trash size={15} />
</a>
</span>
</p>
)}
<ul className="mix-list">
@@ -217,28 +255,35 @@ export function App(props: {
<main className="content">
{error && <div className="notice error">{error}</div>}
{(route.view === "mix" || route.view === "liked") && rules && rules.length === 0 && (
<div className="notice">
<h1>No mix rules yet</h1>
<p>Create one, and playlistd will cluster your listens into genre mixes:</p>
<pre>{`curl -c cookies -X POST ${location.origin}/api/auth/login -H 'Content-Type: application/json' \\\n -d '{"username": "${props.account.username}", "password": "…"}'\ncurl -b cookies -X POST ${location.origin}/api/playlist/mix -H 'Content-Type: application/json' \\\n -d '{"tracking_user": "your-listenbrainz-name"}'`}</pre>
</div>
)}
{(route.view === "mix" || route.view === "liked") && pending && mixes?.length === 0 && (
<div className="notice"><span className="spinner" /> Building mixes from your recent listens…</div>
)}
{route.view === "account" ? (
<AccountView
account={props.account}
onChange={props.onAccountChange}
onLogout={props.onLogout}
onToast={(message) => setToast({ message })}
{route.view === "new-mixes" || ((route.view === "mix" || route.view === "liked") && rules?.length === 0) ? (
<NewMixesView
// remount when switching between the first-run and "another user" forms
key={rules?.length ? "another" : "first"}
first={rules?.length === 0}
onCancel={() => (window.location.hash = "")}
onCreated={onRuleCreated}
/>
) : route.view === "delete-mixes" ? (
rule && (
<DeleteMixesView
key={rule.id}
rule={rule}
mixes={mixes}
likedCount={liked.length}
onCancel={() => (window.location.hash = "")}
onDeleted={onRuleDeleted}
/>
)
) : route.view === "account" ? (
<AccountView account={props.account} onLogout={props.onLogout} />
) : route.view === "tracked" ? (
<TrackedView defaultUser={rule?.tracking_user} onToast={(message) => setToast({ message })} />
) : route.view === "liked" ? (
<LikedView liked={liked} player={player} onStatus={onStatus} />
) : detail ? (
) : detail && detail.id === mixId ? (
<MixView mix={detail} knownRatio={rule?.familiar_ratio ?? 0.3} player={player} onStatus={onStatus} />
) : (
mixId && <div className="notice"><span className="spinner" /> Loading…</div>
-1
View File
@@ -64,7 +64,6 @@ export function AuthGate() {
return (
<App
account={state.account}
onAccountChange={(account) => setState({ kind: "ready", account })}
onLogout={() => setState({ kind: "login" })}
/>
);
+92
View File
@@ -0,0 +1,92 @@
import { useState } from "react";
import { api, MixSummary, mixTitle, Rule } from "./api";
import * as Icon from "./icons";
/** Confirm deleting a cluster mix rule, and with it all of its mixes */
export function DeleteMixesView(props: {
rule: Rule;
mixes: MixSummary[] | null;
likedCount: number;
onCancel: () => void;
onDeleted: (rule: Rule, playlistsDeleted: boolean) => void;
}) {
const { rule, mixes } = props;
const [deletePlaylists, setDeletePlaylists] = useState(true);
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const remove = async () => {
setBusy(true);
setError(null);
try {
await api.deleteRule(rule.id, deletePlaylists);
props.onDeleted(rule, deletePlaylists);
} catch (e) {
setError((e as Error).message);
setBusy(false);
}
};
const count = mixes?.length ?? 0;
const playlists = count === 1 ? "playlist" : `${count} playlists`;
return (
<article className="manage">
<header className="manage-header">
<p className="eyebrow">Discover</p>
<h1>Delete mixes for {rule.tracking_user}?</h1>
<p className="mix-counts">
playlistd stops building genre mixes for {rule.tracking_user}. You can set them up again later, but
they'll start from scratch.
</p>
</header>
<section className="panel" aria-labelledby="delete-mixes-heading">
<div className="panel-header">
<div>
<h2 id="delete-mixes-heading"><Icon.Trash size={17} /> Mixes</h2>
<p className="hint">
{mixes === null
? "Loading…"
: count === 0
? "No mixes have been built yet."
: `${count} ${count === 1 ? "mix" : "mixes"}, each a playlist in Subsonic.`}
</p>
</div>
</div>
{count > 0 && (
<ul className="delete-list">
{mixes!.map((m) => <li key={m.id}>{m.name ?? mixTitle(m)}</li>)}
</ul>
)}
<div className="confirm" role="alertdialog" aria-labelledby="delete-mixes-heading">
{count > 0 && (
<label className="checkbox">
<input type="checkbox" checked={deletePlaylists} onChange={(e) => setDeletePlaylists(e.target.checked)} />
Also delete the {playlists} from Subsonic
</label>
)}
{count > 0 && !deletePlaylists && (
<p className="hint">The {playlists} stay in Subsonic as they are now, and won't be updated.</p>
)}
{props.likedCount > 0 && (
<p className="hint">
<Icon.Warning size={13} /> Your {props.likedCount} liked new{" "}
{props.likedCount === 1 ? "song is" : "songs are"} deleted too, along with the rest of the
suggestions.
</p>
)}
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
<button className="btn" onClick={props.onCancel} autoFocus>Cancel</button>
<button className="btn danger" onClick={remove} disabled={busy || mixes === null}>
{busy ? <span className="spinner light" /> : <Icon.Trash size={15} />} Delete mixes
</button>
</div>
</div>
</section>
</article>
);
}
+202
View File
@@ -0,0 +1,202 @@
import { FormEvent, useState } from "react";
import { api, NewRule, Rule } from "./api";
import * as Icon from "./icons";
const HISTORY: [number, string][] = [
[1, "Last month"],
[3, "Last 3 months"],
[6, "Last 6 months"],
[12, "Last year"],
];
const REFRESH: [number, string][] = [
[6, "Every 6 hours"],
[12, "Every 12 hours"],
[24, "Every day"],
[72, "Every 3 days"],
[168, "Every week"],
];
/** Create a cluster mix rule: genre mixes for a Listenbrainz user */
export function NewMixesView(props: {
/** No rules exist yet, so this is the first thing the user sees */
first: boolean;
onCancel: () => void;
onCreated: (rule: Rule) => void;
}) {
const [rule, setRule] = useState<NewRule>({
tracking_user: "",
months: 3,
playlist_size: 50,
cluster_count: null,
familiar_ratio: 0.3,
discovery_count: 15,
name_template: "Mix: {label}",
refresh_hours: 24,
});
const [busy, setBusy] = useState(false);
const [error, setError] = useState<string | null>(null);
const set = (change: Partial<NewRule>) => setRule((r) => ({ ...r, ...change }));
const templateError = rule.name_template.includes("{label}")
? null
: "Include {label}, so each mix gets its own name";
const submit = async (e: FormEvent) => {
e.preventDefault();
setBusy(true);
setError(null);
try {
props.onCreated(await api.createRule({ ...rule, tracking_user: rule.tracking_user.trim() }));
} catch (err) {
setError((err as Error).message);
setBusy(false);
}
};
return (
<article className="manage">
<header className="manage-header">
<p className="eyebrow">Discover</p>
<h1>{props.first ? "Set up your mixes" : "New mixes"}</h1>
<p className="mix-counts">
playlistd groups what you've listened to recently by genre, and keeps a Subsonic playlist for
each group: songs you love, songs from your library you haven't played lately, and new songs
to try.
</p>
</header>
<section className="panel" aria-labelledby="new-mixes-heading">
<div className="panel-header">
<div>
<h2 id="new-mixes-heading"><Icon.Sparkle size={17} /> Mixes</h2>
<p className="hint">The first build takes a minute or two. After that, mixes are rebuilt on a schedule.</p>
</div>
</div>
<form className="form" onSubmit={submit} aria-label="New mixes">
<div className="form-grid">
<label className="field">
<span>Listenbrainz user</span>
<input
required
value={rule.tracking_user}
onChange={(e) => set({ tracking_user: e.target.value })}
autoComplete="off"
spellCheck={false}
autoFocus
/>
</label>
<label className="field">
<span>Listens from</span>
<select value={rule.months} onChange={(e) => set({ months: Number(e.target.value) })}>
{HISTORY.map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select>
</label>
<label className="field narrow">
<span>Songs</span>
<input
type="number"
required
min={1}
max={500}
value={rule.playlist_size}
onChange={(e) => set({ playlist_size: Number(e.target.value) })}
aria-describedby="songs-help"
/>
</label>
<label className="field">
<span>Number of mixes</span>
<select
value={rule.cluster_count ?? ""}
onChange={(e) => set({ cluster_count: e.target.value ? Number(e.target.value) : null })}
>
<option value="">Automatic</option>
{Array.from({ length: 11 }, (_, i) => i + 2).map((n) => (
<option key={n} value={n}>{n}</option>
))}
</select>
</label>
<div className="field">
<label htmlFor="familiar-ratio">
Songs you know <output htmlFor="familiar-ratio">{Math.round(rule.familiar_ratio * 100)}%</output>
</label>
<input
id="familiar-ratio"
type="range"
min={0}
max={1}
step={0.05}
value={rule.familiar_ratio}
onChange={(e) => set({ familiar_ratio: Number(e.target.value) })}
aria-describedby="familiar-help"
/>
</div>
<label className="field narrow">
<span>New songs</span>
<input
type="number"
required
min={0}
max={100}
value={rule.discovery_count}
onChange={(e) => set({ discovery_count: Number(e.target.value) })}
aria-describedby="new-help"
/>
</label>
</div>
<ul className="field-help hint">
<li id="songs-help"><strong>Songs</strong> per mix, from your library.</li>
<li id="familiar-help"><strong>Songs you know</strong>: the share of each mix taken from what you've played recently. The rest are songs from your library in the same genres.</li>
<li id="new-help"><strong>New songs</strong> not in your library to suggest for each mix, to listen to here.</li>
</ul>
<details className="advanced">
<summary>More options</summary>
<div className="form-grid">
<div className="field">
<label htmlFor="mix-template">Playlist name</label>
<input
id="mix-template"
className="mono"
required
value={rule.name_template}
onChange={(e) => set({ name_template: e.target.value })}
spellCheck={false}
aria-describedby="mix-template-help"
aria-invalid={!!templateError}
/>
<small className="hint" id="mix-template-help" aria-live="polite">
{templateError ? (
<span className="warning-text">{templateError}</span>
) : (
<>
<code>{"{label}"}</code> becomes the mix's top genres, e.g.{" "}
<strong>{rule.name_template.replace("{label}", "Shoegaze / Dream Pop")}</strong>
</>
)}
</small>
</div>
<label className="field">
<span>Rebuild</span>
<select value={rule.refresh_hours} onChange={(e) => set({ refresh_hours: Number(e.target.value) })}>
{REFRESH.map(([v, label]) => <option key={v} value={v}>{label}</option>)}
</select>
</label>
</div>
</details>
{error && <p className="form-error" role="alert">{error}</p>}
<div className="form-actions">
{!props.first && <button type="button" className="btn" onClick={props.onCancel}>Cancel</button>}
<button type="submit" className="btn primary" disabled={busy || !!templateError}>
{busy ? <span className="spinner light" /> : <Icon.Plus size={16} />} Create mixes
</button>
</div>
</form>
</section>
</article>
);
}
+11 -5
View File
@@ -2,13 +2,20 @@ export type Rule = {
id: string;
tracking_user: string;
months: number;
/** null: chosen automatically */
cluster_count: number | null;
playlist_size: number;
discovery_count: number;
/** Share of a mix made of songs the user already knows */
familiar_ratio: number;
/** `{label}` becomes the mix's top genres */
name_template: string;
refresh_hours: number;
last_run: string | null;
};
export type NewRule = Omit<Rule, "id" | "last_run">;
export type MixSummary = {
id: string;
playlist_id: string;
@@ -75,6 +82,10 @@ const json = (method: string, body: unknown): RequestInit => ({
export const api = {
rules: () => request<Rule[]>("/rules"),
createRule: (rule: NewRule) => request<Rule>("/rules", json("POST", rule)),
/** Deletes the rule's mixes and suggestions, and optionally their playlists in Subsonic */
deleteRule: (id: string, deletePlaylists: boolean) =>
request<void>(`/rules/${id}?delete_playlists=${deletePlaylists}`, { method: "DELETE" }),
mixes: (ruleId: string) => request<MixSummary[]>(`/rules/${ruleId}/mixes`),
mix: (mixId: string) => request<MixDetail>(`/mixes/${mixId}`),
liked: (ruleId: string) => request<Suggestion[]>(`/rules/${ruleId}/liked`),
@@ -161,9 +172,6 @@ export const trackedApi = {
export type Account = {
username: string;
/** The Listenbrainz user the saved token belongs to */
listenbrainz_user: string | null;
has_listenbrainz_token: boolean;
};
export type AuthStatus = {
@@ -179,6 +187,4 @@ export const authApi = {
setup: (username: string, password: string) => auth<Account>("/setup", json("POST", { username, password })),
login: (username: string, password: string) => auth<Account>("/login", json("POST", { username, password })),
logout: () => auth<void>("/logout", { method: "POST" }),
/** An empty token removes the saved one */
setListenbrainzToken: (token: string) => auth<Account>("/account/listenbrainz", json("PUT", { token })),
};
+68 -20
View File
@@ -136,6 +136,11 @@ a {
font-size: 0.85rem;
}
.rule-actions {
display: flex;
gap: 2px;
}
.mix-list {
list-style: none;
margin: 0;
@@ -1005,6 +1010,69 @@ h2 {
color: var(--accent-text);
}
.field output {
margin-left: 4px;
color: var(--muted);
font-weight: 600;
font-variant-numeric: tabular-nums;
}
.field input[type="range"] {
min-height: 38px;
padding: 0;
border: 0;
background: none;
accent-color: var(--accent);
}
.field input[aria-invalid="true"] {
border-color: var(--youtube);
}
.field-help {
display: grid;
gap: 3px;
margin: -2px 0 0;
padding: 0;
list-style: none;
}
.advanced summary {
width: fit-content;
color: var(--muted);
font-size: 0.88rem;
font-weight: 600;
cursor: pointer;
}
.advanced[open] summary {
margin-bottom: 12px;
}
.advanced .form-grid {
grid-template-columns: minmax(0, 1.4fr) minmax(0, 1.2fr);
}
.delete-list {
display: flex;
flex-wrap: wrap;
gap: 6px;
margin: 0 0 14px;
padding: 0;
list-style: none;
}
.delete-list li {
padding: 3px 10px;
border: 1px solid var(--border);
border-radius: 999px;
font-size: 0.85rem;
}
.confirm .hint svg {
vertical-align: -2px;
}
/* ---------- login & account ---------- */
.auth-page {
@@ -1053,26 +1121,6 @@ h2 {
color: var(--muted);
}
.token-status {
display: flex;
align-items: center;
gap: 8px;
margin: 0 0 4px;
font-size: 0.92rem;
}
.status-dot {
flex: none;
width: 8px;
height: 8px;
border-radius: 50%;
background: var(--muted);
}
.status-dot.ok {
background: var(--library);
}
.hint a {
color: var(--accent);
}