feat(web): a Suggest a name button

- Where a playlist is renamed, and where a smart playlist is edited, a button asks the server for a name in the language of the page. It fills the name, fills the description when it is empty, and says if the name came from Claude or from this server. A failed request says why and changes nothing.
- The Claude card in the providers page has a key, a test and the switch, but no contact and no data to take back.
This commit is contained in:
tgiachi 2026-11-13 10:33:48 +01:00
commit 9e666d2b29
12 changed files with 369 additions and 8 deletions

16
web/src/api/naming.ts Normal file
View file

@ -0,0 +1,16 @@
import { useMutation } from '@tanstack/react-query'
import { useTranslation } from 'react-i18next'
import { api } from './client'
import type { components } from './schema'
export type NameSuggestion = components['schemas']['NameSuggestion']
/**
* Asks the server for a name for a playlist, a mix or a smart playlist (`path` is its own, like `/playlists/3`), in the
* language of the page. It changes nothing: the page decides what to do with the suggestion.
*/
export function useSuggestName(path: string) {
const { i18n } = useTranslation()
const lang = i18n.language.toLowerCase().startsWith('it') ? 'it' : 'en'
return useMutation({ mutationFn: () => api.post<NameSuggestion>(`${path}/suggest-name`, { lang }) })
}

View file

@ -1170,6 +1170,91 @@ export interface paths {
patch: operations["updatePlaylist"];
trace?: never;
};
"/playlists/{id}/suggest-name": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
get?: never;
put?: never;
/**
* Suggest a name for a playlist
* @description Makes a suggestion and changes nothing: the client decides what to do with it. When an admin turned the
* `anthropic` provider on with an API key, Claude is asked for the name, with only a few facts: up to 5 genres,
* up to 8 artist names, how many songs there are, for a smart playlist a few words about its rules, and the
* language. Never the user, a listen, a track title or a file path. What Claude answers is kept, so the same facts
* are not asked twice. With the provider off, or when it fails or declines, a name is made on this server from the
* genres and the artists and nothing leaves it: `source` says which it was. The body is optional.
* The facts come from the first 200 songs of the playlist that can be played.
*/
post: operations["suggestPlaylistName"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/mixes/{id}/suggest-name": {
parameters: {
query?: never;
header?: never;
path: {
/** @description `favourites`, `rediscover`, `unheard` or `genre:<name>` (percent-encoded). */
id: components["parameters"]["MixId"];
};
cookie?: never;
};
get?: never;
put?: never;
/**
* Suggest a name for a mix
* @description Makes a suggestion and changes nothing: the client decides what to do with it. When an admin turned the
* `anthropic` provider on with an API key, Claude is asked for the name, with only a few facts: up to 5 genres,
* up to 8 artist names, how many songs there are, for a smart playlist a few words about its rules, and the
* language. Never the user, a listen, a track title or a file path. What Claude answers is kept, so the same facts
* are not asked twice. With the provider off, or when it fails or declines, a name is made on this server from the
* genres and the artists and nothing leaves it: `source` says which it was. The body is optional.
* The facts come from the songs that `variant` of the mix has.
*/
post: operations["suggestMixName"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/smart-playlists/{id}/suggest-name": {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
get?: never;
put?: never;
/**
* Suggest a name for a smart playlist
* @description Makes a suggestion and changes nothing: the client decides what to do with it. When an admin turned the
* `anthropic` provider on with an API key, Claude is asked for the name, with only a few facts: up to 5 genres,
* up to 8 artist names, how many songs there are, for a smart playlist a few words about its rules, and the
* language. Never the user, a listen, a track title or a file path. What Claude answers is kept, so the same facts
* are not asked twice. With the provider off, or when it fails or declines, a name is made on this server from the
* genres and the artists and nothing leaves it: `source` says which it was. The body is optional.
* The facts come from the rules and from the songs that `variant` of it gives now.
*/
post: operations["suggestSmartPlaylistName"];
delete?: never;
options?: never;
head?: never;
patch?: never;
trace?: never;
};
"/playlists/{id}/tracks": {
parameters: {
query?: never;
@ -1712,7 +1797,7 @@ export interface paths {
query?: never;
header?: never;
path: {
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr";
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr" | "anthropic";
};
cookie?: never;
};
@ -1739,7 +1824,7 @@ export interface paths {
query?: never;
header?: never;
path: {
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr";
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr" | "anthropic";
};
cookie?: never;
};
@ -1768,7 +1853,7 @@ export interface paths {
query?: never;
header?: never;
path: {
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr";
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr" | "anthropic";
};
cookie?: never;
};
@ -2039,7 +2124,7 @@ export interface components {
};
Provider: {
/** @enum {string} */
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr";
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr" | "anthropic";
/** @description Whether Sonda may contact this provider. */
enabled: boolean;
needs_api_key: boolean;
@ -2348,6 +2433,25 @@ export interface components {
tracks: number;
}[];
};
SuggestName: {
/** @description The language of the name: `en` or `it`. Absent or another: English. */
lang?: string;
/**
* @description For a mix or a smart playlist: the variant that is on screen.
* @default 0
*/
variant: number;
};
NameSuggestion: {
name: string;
/** @description One short sentence. */
description: string;
/**
* @description `claude` when the Claude provider made it, `local` when it was made on this server.
* @enum {string}
*/
source: "claude" | "local";
};
/**
* @description Every rule that is set must hold; one that is absent, empty, false or 0 does not count. Of a list rule a
* song needs to match one item.
@ -4801,6 +4905,94 @@ export interface operations {
404: components["responses"]["PlaylistNotFound"];
};
};
suggestPlaylistName: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: {
content: {
"application/json": components["schemas"]["SuggestName"];
};
};
responses: {
/** @description A name and a line of description. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["NameSuggestion"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
404: components["responses"]["PlaylistNotFound"];
};
};
suggestMixName: {
parameters: {
query?: never;
header?: never;
path: {
/** @description `favourites`, `rediscover`, `unheard` or `genre:<name>` (percent-encoded). */
id: components["parameters"]["MixId"];
};
cookie?: never;
};
requestBody?: {
content: {
"application/json": components["schemas"]["SuggestName"];
};
};
responses: {
/** @description A name and a line of description. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["NameSuggestion"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
404: components["responses"]["MixNotFound"];
};
};
suggestSmartPlaylistName: {
parameters: {
query?: never;
header?: never;
path: {
id: components["parameters"]["Id"];
};
cookie?: never;
};
requestBody?: {
content: {
"application/json": components["schemas"]["SuggestName"];
};
};
responses: {
/** @description A name and a line of description. */
200: {
headers: {
[name: string]: unknown;
};
content: {
"application/json": components["schemas"]["NameSuggestion"];
};
};
400: components["responses"]["InvalidInput"];
401: components["responses"]["Unauthorized"];
404: components["responses"]["SmartPlaylistNotFound"];
};
};
listPlaylistTracks: {
parameters: {
query?: {
@ -5904,7 +6096,7 @@ export interface operations {
query?: never;
header?: never;
path: {
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr";
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr" | "anthropic";
};
cookie?: never;
};
@ -5942,7 +6134,7 @@ export interface operations {
query?: never;
header?: never;
path: {
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr";
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr" | "anthropic";
};
cookie?: never;
};
@ -5976,7 +6168,7 @@ export interface operations {
query?: never;
header?: never;
path: {
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr";
name: "lastfm" | "musicbrainz" | "wikipedia" | "commons" | "coverartarchive" | "lidarr" | "anthropic";
};
cookie?: never;
};

View file

@ -0,0 +1,33 @@
import { Sparkles } from 'lucide-react'
import { useTranslation } from 'react-i18next'
import { ApiError } from '@/api/client'
import { useSuggestName, type NameSuggestion } from '@/api/naming'
import { Button } from '@/components/ui/button'
import { errorMessageKey } from '@/i18n'
/**
* A button that asks for a name and hands it to the page, with a line that says where it came from. A failed
* request says why and changes nothing.
*/
export default function SuggestName({ path, onSuggestion }: { path: string; onSuggestion: (s: NameSuggestion) => void }) {
const { t } = useTranslation()
const suggest = useSuggestName(path)
return (
<div className="flex flex-col items-start gap-2">
<Button type="button" variant="outline" className="gap-2" disabled={suggest.isPending} onClick={() => suggest.mutate(undefined, { onSuccess: onSuggestion })}>
<Sparkles />
{t('naming.suggest')}
</Button>
{suggest.isSuccess && (
<p role="status" className="text-sm text-muted-foreground">
{t(suggest.data.source === 'claude' ? 'naming.claude' : 'naming.local')}
</p>
)}
{suggest.isError && (
<p role="alert" className="text-sm text-destructive">
{t(errorMessageKey(suggest.error instanceof ApiError ? suggest.error.code : 'unknown'))}
</p>
)}
</div>
)
}

View file

@ -455,6 +455,7 @@
"commons": "Wikimedia Commons",
"coverartarchive": "Cover Art Archive",
"lidarr": "Lidarr",
"anthropic": "Claude (Anthropic)",
"files": "your files"
},
"empty": {
@ -691,5 +692,10 @@
"cancel": "Cancel",
"blank": "Leave a number blank for no rule."
}
},
"naming": {
"suggest": "Suggest a name",
"claude": "Suggested by Claude",
"local": "Suggested on this server"
}
}

View file

@ -455,6 +455,7 @@
"commons": "Wikimedia Commons",
"coverartarchive": "Cover Art Archive",
"lidarr": "Lidarr",
"anthropic": "Claude (Anthropic)",
"files": "i tuoi file"
},
"empty": {
@ -691,5 +692,10 @@
"cancel": "Annulla",
"blank": "Lascia vuoto un numero per nessuna regola."
}
},
"naming": {
"suggest": "Suggerisci un nome",
"claude": "Suggerito da Claude",
"local": "Suggerito da questo server"
}
}

View file

@ -14,6 +14,7 @@ import {
type PlaylistItem,
} from '@/api/playlists'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import SuggestName from '@/components/SuggestName'
import TrackRow from '@/components/TrackRow'
import { Button } from '@/components/ui/button'
import { Dialog, DialogContent, DialogFooter, DialogHeader, DialogTitle } from '@/components/ui/dialog'
@ -191,6 +192,13 @@ function RenameDialog({ playlist, onClose }: { playlist: Playlist; onClose: () =
<Label htmlFor="playlist-description">{t('playlists.descriptionField')}</Label>
<Input id="playlist-description" value={description} maxLength={2000} autoComplete="off" onChange={(e) => setDescription(e.target.value)} />
</div>
<SuggestName
path={`/playlists/${playlist.id}`}
onSuggestion={(s) => {
setName(s.name)
if (description.trim() === '') setDescription(s.description)
}}
/>
{update.isError && (
<p role="alert" className="text-sm text-destructive">
{errorLine(t, update.error)}

View file

@ -17,6 +17,7 @@ import {
} from '@/api/smart'
import ChoiceGroup from '@/components/ChoiceGroup'
import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status'
import SuggestName from '@/components/SuggestName'
import { Button, buttonVariants } from '@/components/ui/button'
import { Input } from '@/components/ui/input'
import { Label } from '@/components/ui/label'
@ -104,6 +105,16 @@ function SmartEditor({ existing }: { existing: SmartPlaylist | null }) {
<Input id="smart-description" value={description} maxLength={2000} autoComplete="off" onChange={(e) => setDescription(e.target.value)} />
</div>
{existing && (
<SuggestName
path={`/smart-playlists/${existing.id}`}
onSuggestion={(s) => {
setName(s.name)
if (description.trim() === '') setDescription(s.description)
}}
/>
)}
<GenreField label={t('smart.editor.genres')} hint={t('smart.editor.genresHint')} genres={form.genres} onChange={(g) => set('genres', g)} />
<GenreField label={t('smart.editor.notGenres')} genres={form.notGenres} onChange={(g) => set('notGenres', g)} />

View file

@ -80,6 +80,17 @@ test('a card names the provider, says what it is sent and the terms, and shows w
expect(within(c).getByRole('switch', { name: 'Last.fm' })).toHaveAttribute('aria-checked', 'false')
})
test('Claude has a key, a test and the switch, but no contact and no data to take back', async () => {
server(base('anthropic', { needs_api_key: true, sends: 'A few genres and artist names go to Anthropic.' }))
renderCard('anthropic')
const c = await card('Claude (Anthropic)')
expect(c).toHaveTextContent('A few genres and artist names go to Anthropic.')
expect(within(c).getByRole('switch', { name: 'Claude (Anthropic)' })).toBeInTheDocument()
expect(within(c).getByRole('button', { name: /Test/ })).toBeInTheDocument()
expect(within(c).queryByRole('textbox')).not.toBeInTheDocument()
expect(within(c).queryByRole('button', { name: /Remove data/ })).not.toBeInTheDocument()
})
test('turning a provider on asks first and repeats what it will be sent', async () => {
const { calls } = server(lastfm({ has_api_key: true }))
renderCard('lastfm')

View file

@ -62,6 +62,8 @@ function TextSetting({ provider, setting }: { provider: Provider; setting: Setti
*/
export default function ProviderFields({ provider, name }: { provider: Provider; name: string }) {
const { t } = useTranslation()
// Claude is asked with a User-Agent that says what the software is: there is no contact to give it.
if (provider.name === 'anthropic') return null
if (provider.needs_url) {
return (
<TextSetting

View file

@ -35,7 +35,7 @@ export default function ProviderTools({ provider, name }: { provider: Provider;
<Button variant="outline" disabled={test.isPending} aria-label={t('admin.providers.testOne', { name })} onClick={() => test.mutate(provider.name)}>
{t('admin.providers.test')}
</Button>
{provider.name !== 'lidarr' && (
{provider.name !== 'lidarr' && provider.name !== 'anthropic' && (
<Button variant="outline" disabled={purge.isPending} aria-label={t('admin.providers.purgeOne', { name })} onClick={() => setAsking(true)}>
{t('admin.providers.purge')}
</Button>

View file

@ -227,6 +227,59 @@ test('a playlist is renamed from a window, and an empty name is not sent', async
expect(JSON.parse(calls.find((c) => c.key === 'PATCH /api/v1/playlists/3')!.init.body as string)).toEqual({ name: 'Long drive', description: 'for the car' })
})
test('Suggest a name fills the name, keeps a description that is there, and says where it came from', async () => {
const { calls } = mockFetch(
onePlaylist({
'POST /api/v1/playlists/3/suggest-name': () => ({ name: 'Riff senza sosta', description: 'Hard rock.', source: 'claude' }),
'PATCH /api/v1/playlists/3': () => playlist(3, 'Riff senza sosta'),
}),
)
open()
await userEvent.click(await screen.findByRole('button', { name: 'Rename' }))
const dialog = await screen.findByRole('dialog')
await userEvent.click(within(dialog).getByRole('button', { name: 'Suggest a name' }))
expect(await within(dialog).findByDisplayValue('Riff senza sosta')).toBeInTheDocument()
expect(within(dialog).getByRole('textbox', { name: 'Description' })).toHaveValue('for the car')
expect(within(dialog).getByRole('status')).toHaveTextContent('Suggested by Claude')
expect(JSON.parse(calls.find((c) => c.key === 'POST /api/v1/playlists/3/suggest-name')!.init.body as string)).toEqual({ lang: 'en' })
await userEvent.click(within(dialog).getByRole('button', { name: 'Save' }))
await waitFor(() => expect(calls.some((c) => c.key === 'PATCH /api/v1/playlists/3')).toBe(true))
expect(JSON.parse(calls.find((c) => c.key === 'PATCH /api/v1/playlists/3')!.init.body as string)).toEqual({ name: 'Riff senza sosta', description: 'for the car' })
})
test('an empty description gets the suggested one', async () => {
mockFetch(
onePlaylist(
{ 'POST /api/v1/playlists/3/suggest-name': () => ({ name: 'Rock', description: 'With Queen.', source: 'local' }) },
[item(0, 1), item(1, 2), item(2, 3)],
),
)
open()
await userEvent.click(await screen.findByRole('button', { name: 'Rename' }))
const dialog = await screen.findByRole('dialog')
await userEvent.clear(within(dialog).getByRole('textbox', { name: 'Description' }))
await userEvent.click(within(dialog).getByRole('button', { name: 'Suggest a name' }))
await waitFor(() => expect(within(dialog).getByRole('textbox', { name: 'Description' })).toHaveValue('With Queen.'))
})
test('a name made on the server says so, and a failed suggestion changes nothing', async () => {
let answer: () => Response | object = () => ({ name: 'Rock & Metal', description: 'With Queen.', source: 'local' })
mockFetch(onePlaylist({ 'POST /api/v1/playlists/3/suggest-name': () => answer() }))
open()
await userEvent.click(await screen.findByRole('button', { name: 'Rename' }))
const dialog = await screen.findByRole('dialog')
await userEvent.click(within(dialog).getByRole('button', { name: 'Suggest a name' }))
expect(await within(dialog).findByRole('status')).toHaveTextContent('Suggested on this server')
expect(within(dialog).getByRole('textbox', { name: 'Name' })).toHaveValue('Rock & Metal')
answer = () => apiError(500, 'unknown')
await userEvent.clear(within(dialog).getByRole('textbox', { name: 'Name' }))
await userEvent.type(within(dialog).getByRole('textbox', { name: 'Name' }), 'Mine')
await userEvent.click(within(dialog).getByRole('button', { name: 'Suggest a name' }))
expect(await within(dialog).findByRole('alert')).toBeInTheDocument()
expect(within(dialog).getByRole('textbox', { name: 'Name' })).toHaveValue('Mine')
})
test('deleting a playlist asks first, then goes back to the list', async () => {
const { calls } = mockFetch(onePlaylist({ 'DELETE /api/v1/playlists/3': () => new Response(null, { status: 204 }) }))
open()

View file

@ -464,3 +464,26 @@ test('a suggested one that does not exist says so', async () => {
renderApp('/smart-playlists/suggested/nonsense')
expect(await screen.findByText('This suggested smart playlist does not exist.')).toBeInTheDocument()
})
test('editing a smart playlist can ask for a name, sending the language of the page', async () => {
const existing = smart(3, 'Fresh rock', { rules: { genres: ['rock'] } })
const { calls } = mockFetch(
editorRoutes({
'GET /api/v1/smart-playlists/3': () => existing,
'POST /api/v1/smart-playlists/3/suggest-name': () => ({ name: 'Rock mai sentito', description: 'Rock nuovo.', source: 'claude' }),
}),
)
renderApp('/smart-playlists/3/edit')
await userEvent.click(await screen.findByRole('button', { name: 'Suggest a name' }))
expect(await screen.findByDisplayValue('Rock mai sentito')).toBeInTheDocument()
expect(screen.getByRole('textbox', { name: 'Description' })).toHaveValue('Rock nuovo.')
expect(screen.getByRole('status')).toHaveTextContent('Suggested by Claude')
expect(JSON.parse(calls.find((c) => c.key === 'POST /api/v1/smart-playlists/3/suggest-name')!.init.body as string)).toEqual({ lang: 'en' })
})
test('a new smart playlist has no name to suggest yet: it is not kept', async () => {
mockFetch(editorRoutes())
renderApp('/smart-playlists/new')
await screen.findByRole('textbox', { name: 'Name' })
expect(screen.queryByRole('button', { name: 'Suggest a name' })).not.toBeInTheDocument()
})