diff --git a/web/src/api/naming.ts b/web/src/api/naming.ts new file mode 100644 index 0000000..deca5a8 --- /dev/null +++ b/web/src/api/naming.ts @@ -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(`${path}/suggest-name`, { lang }) }) +} diff --git a/web/src/api/schema.d.ts b/web/src/api/schema.d.ts index fc9dbbb..0b0a5e6 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -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:` (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:` (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; }; diff --git a/web/src/components/SuggestName.tsx b/web/src/components/SuggestName.tsx new file mode 100644 index 0000000..48762d9 --- /dev/null +++ b/web/src/components/SuggestName.tsx @@ -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 ( +
+ + {suggest.isSuccess && ( +

+ {t(suggest.data.source === 'claude' ? 'naming.claude' : 'naming.local')} +

+ )} + {suggest.isError && ( +

+ {t(errorMessageKey(suggest.error instanceof ApiError ? suggest.error.code : 'unknown'))} +

+ )} +
+ ) +} diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 6c7ac39..b8807e6 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -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" } } diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 358e2ba..bd71234 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -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" } } diff --git a/web/src/pages/PlaylistPage.tsx b/web/src/pages/PlaylistPage.tsx index 5fcdc06..c86c7b6 100644 --- a/web/src/pages/PlaylistPage.tsx +++ b/web/src/pages/PlaylistPage.tsx @@ -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: () = setDescription(e.target.value)} /> + { + setName(s.name) + if (description.trim() === '') setDescription(s.description) + }} + /> {update.isError && (

{errorLine(t, update.error)} diff --git a/web/src/pages/SmartEditorPage.tsx b/web/src/pages/SmartEditorPage.tsx index 48d6544..36895c7 100644 --- a/web/src/pages/SmartEditorPage.tsx +++ b/web/src/pages/SmartEditorPage.tsx @@ -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 }) { setDescription(e.target.value)} /> + {existing && ( + { + setName(s.name) + if (description.trim() === '') setDescription(s.description) + }} + /> + )} + set('genres', g)} /> set('notGenres', g)} /> diff --git a/web/src/pages/admin/ProviderCard.test.tsx b/web/src/pages/admin/ProviderCard.test.tsx index 8a26cd8..a64367e 100644 --- a/web/src/pages/admin/ProviderCard.test.tsx +++ b/web/src/pages/admin/ProviderCard.test.tsx @@ -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') diff --git a/web/src/pages/admin/ProviderFields.tsx b/web/src/pages/admin/ProviderFields.tsx index f9e93e6..14d2997 100644 --- a/web/src/pages/admin/ProviderFields.tsx +++ b/web/src/pages/admin/ProviderFields.tsx @@ -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 ( test.mutate(provider.name)}> {t('admin.providers.test')} - {provider.name !== 'lidarr' && ( + {provider.name !== 'lidarr' && provider.name !== 'anthropic' && ( diff --git a/web/src/pages/playlists.test.tsx b/web/src/pages/playlists.test.tsx index d1a9ed0..fbfb74c 100644 --- a/web/src/pages/playlists.test.tsx +++ b/web/src/pages/playlists.test.tsx @@ -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() diff --git a/web/src/pages/smart.test.tsx b/web/src/pages/smart.test.tsx index 21c2b53..adab783 100644 --- a/web/src/pages/smart.test.tsx +++ b/web/src/pages/smart.test.tsx @@ -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() +})