From 0d8fadadf639822565a4f0d6db0bed0d807b7066 Mon Sep 17 00:00:00 2001 From: tgiachi Date: Fri, 13 Nov 2026 11:00:23 +0100 Subject: [PATCH] feat(naming): playlists named by Claude by themselves when it is on - Keeping a mix, a smart playlist or a suggested smart playlist as a playlist with auto_name gives it the name and the line of description that Claude makes from its songs. The name sent stays the fallback when the provider is off, or Claude fails or declines, so a failure never stops a playlist from being made. - A smart playlist can be made with no name when Claude is on: it names it from the songs the rules give. Without Claude a name is still needed. - GET /naming says whether names are automatic, so the editor does not ask for a name that Claude will make. - The web app always asks for an automatic name and sends the language of the page. --- README.md | 3 +- internal/api/http/contract_test.go | 9 ++ internal/api/http/handlers_mixes.go | 10 +- internal/api/http/handlers_naming.go | 24 ++++ internal/api/http/handlers_playlists.go | 4 +- internal/api/http/handlers_smart.go | 32 ++++-- internal/api/http/naming_test.go | 139 ++++++++++++++++++++++++ internal/api/http/router.go | 6 +- internal/api/openapi/openapi.yaml | 31 +++++- internal/naming/naming.go | 7 ++ web/src/api/mixes.ts | 6 +- web/src/api/naming.ts | 21 +++- web/src/api/schema.d.ts | 65 ++++++++++- web/src/api/smart.ts | 12 +- web/src/i18n/locales/en.json | 1 + web/src/i18n/locales/it.json | 1 + web/src/pages/SmartEditorPage.tsx | 6 +- web/src/pages/mixes.test.tsx | 2 +- web/src/pages/smart.test.tsx | 47 +++++++- 19 files changed, 393 insertions(+), 33 deletions(-) diff --git a/README.md b/README.md index 877d113..8d32786 100644 --- a/README.md +++ b/README.md @@ -258,7 +258,7 @@ The address can have a path if Lidarr runs under a URL base, and it cannot carry The key is stored in the database, in clear text, and is never returned by the API or written to the log: the list only says `has_api_key`. Because the database holds it, treat database backups like secrets. Removing the key turns the provider off, and each provider describes in the list exactly what it sends. -**Claude (Anthropic)** is the one provider that names things: with it on, a playlist, a mix or a smart playlist can get a name and a line of description that fit its songs. An admin turns it on with an Anthropic API key (`PUT /providers/anthropic`, the key is write-only, and `POST /providers/anthropic/test` reads one model, which costs nothing and sends no text). `POST /playlists/{id}/suggest-name`, `POST /mixes/{id}/suggest-name` and `POST /smart-playlists/{id}/suggest-name` answer with a name, a description and a `source`. They are a pipeline: the facts about the list (up to 5 genres, up to 8 artist names, how many songs, for a smart playlist a few words about its rules, and the language) go to a namer. With the provider off, or when Claude fails or declines, the local namer builds a name from the genres and the artists on this server, and nothing leaves it. When Claude answers, the name is kept (under a hash of the facts, which holds no artist name), so the same facts are not asked, or paid, twice. A suggestion changes nothing: the client decides what to do with it, and the web app offers it where a playlist is renamed. The model is `claude-opus-5-5`, at low effort; the key is never taken from the environment of the server, and a redirect is never followed. +**Claude (Anthropic)** is the one provider that names things: with it on, a playlist, a mix or a smart playlist can get a name and a line of description that fit its songs. An admin turns it on with an Anthropic API key (`PUT /providers/anthropic`, the key is write-only, and `POST /providers/anthropic/test` reads one model, which costs nothing and sends no text). `POST /playlists/{id}/suggest-name`, `POST /mixes/{id}/suggest-name` and `POST /smart-playlists/{id}/suggest-name` answer with a name, a description and a `source`. They are a pipeline: the facts about the list (up to 5 genres, up to 8 artist names, how many songs, for a smart playlist a few words about its rules, and the language) go to a namer. With the provider off, or when Claude fails or declines, the local namer builds a name from the genres and the artists on this server, and nothing leaves it. When Claude answers, the name is kept (under a hash of the facts, which holds no artist name), so the same facts are not asked, or paid, twice. A suggestion changes nothing: the client decides what to do with it, and the web app offers it where a playlist is renamed. With the provider on, names are also made by themselves: a mix, a smart playlist or a suggested smart playlist that is kept as a playlist with `auto_name` (the web app always sends it) gets Claude's name and line of description, with `name` as the fallback when Claude is off, fails or declines; a smart playlist can be made with no name at all and Claude names it from the songs its rules give (without Claude that is `invalid_input`); and `GET /naming` says whether names are automatic, so that the editor does not ask for one. The model is `claude-opus-5-5`, at low effort; the key is never taken from the environment of the server, and a redirect is never followed. **What leaves your server, when a provider is on:** to Anthropic, only when someone asks for a name, up to 5 genres and 8 artist names of that list, how many songs it has, a few words about the rules of a smart playlist, the language, your API key, your IP address and a User-Agent (never your users, your listens, track titles or file paths); to Last.fm, the artist name (or MusicBrainz id) being looked up, your API key, your IP address and the `User-Agent`; to MusicBrainz, the MusicBrainz id of the artist (and, only for the covers of albums that have no id, the artist's name and the album's title: see **Covers**), your IP address and a `User-Agent` that carries your contact. Never your users, your listens or file paths. Requests only happen when someone asks for them, never as a bulk pass over your library (the exceptions are the three jobs that an admin starts on purpose, each of them one request that goes through the whole library, one item after the other, spaced out, and each stops when its providers keep failing: `POST /library/covers`, with the Cover Art Archive on, sends the release group id of every album that has no picture in its files (and, for the albums whose files have no id, with MusicBrainz on, the artist and the title, one request a second); `POST /library/artist-images`, with Commons and MusicBrainz on, sends the MusicBrainz id of every artist that has one, to MusicBrainz, Wikidata and Commons; `POST /library/descriptions`, with Wikipedia and MusicBrainz on, sends it to MusicBrainz, Wikidata and Wikipedia), and they are spaced out, retried with backoff, and stopped by a circuit breaker if a provider is down. When MusicBrainz answers that an id was merged into another, Sonda follows that one redirect, and only to an artist or a release group of musicbrainz.org over https; the new id is used for that request and is not stored, and any other redirect is refused. **Descriptions** (the Wikipedia provider, which also needs MusicBrainz on) send the MusicBrainz id to MusicBrainz, the Wikidata item to Wikidata and the title of the page to Wikipedia, with your IP address and a `User-Agent` that carries a contact (the one set for each provider; Wikimedia refuses requests without one), and never a name. **Photos** (the Commons provider, which also needs MusicBrainz on) send the MusicBrainz id to MusicBrainz, the Wikidata item to Wikidata, the name of the picture to Commons and the address of a copy to Wikimedia, with your IP address and a `User-Agent` with a contact, and never a name. **Covers** (the Cover Art Archive provider) send the MusicBrainz release group id of an album, read from the tags of its own files, and only when the files have no picture. When the files have no id either and the MusicBrainz provider is on too, the name of the album's artist and its title go to MusicBrainz, which is asked for the release group: a result is taken only when MusicBrainz scores it 95 or more and its title and artist are the ones asked for (compared without case, accents or punctuation), and anything doubtful is no cover. A title that ends with a note about the disc or the edition (`(disc 2)`, `(bonus disc)`, `(Deluxe Edition)`) is asked as it is first and, if MusicBrainz is not sure, once more without the note, because a release group is named after the album and not after a disc. The id that comes back is used for that request and is not stored: it is not what your files say, and it is never used to read an artist or to send anything to Lidarr; the redirects of the archive are followed only to archive.org, over https. Its covers have no licence of their own: Sonda keeps a copy for your library and never treats it as free. **Discover** asks Last.fm for the similar artists of each seed (the seed's name or MusicBrainz id) and, for the best suggestions that have no tags yet, for the tags of that suggestion (its name); never MusicBrainz. Seeds you name are sent when you ask. Seeds taken from your listening, which are the names of the artists you play most, are sent only if you turned on `discover_from_listening` yourself; otherwise Discover refuses to run without a `seed`. **Lidarr** (your own server, at the address an admin set) gets the MusicBrainz id of an artist an admin sends, or of an artist someone opens `GET /artists/{id}/lidarr` for, and the API key, nothing else; asking it what it offers and testing the key send only the key. Never a name, your users, your listens or your files. What Lidarr then does is up to its own indexers and download clients. Besides the three jobs, the other exception to "only when someone asks" is `POST /providers/{name}/test`, which an admin sends to check a key (or, for Lidarr, the address and the key); it sends nothing but the key. @@ -299,6 +299,7 @@ Everything lives under `/api/v1`. Bodies are JSON. Errors always look like `{"er | signed in | `GET /mixes`, `GET /mixes/{id}`, `POST /mixes/{id}/playlist` | Your mixes: list them, read one (query `variant`), keep one as a playlist. Made for you alone, from your history and your genres; nothing is stored. | | signed in | `GET /genres` | The genres of the library with their number of songs, the biggest first, spellings merged: what the rules of a smart playlist choose from. | | signed in | `GET /smart-playlists`, `POST /smart-playlists`, `GET`, `PATCH`, `DELETE /smart-playlists/{id}` | Your smart playlists: list them (query `limit`, `offset`), make one from rules, read, change or delete one. Never anybody else's. | +| signed in | `GET /naming` | Whether names are made by themselves (`auto`): true when the `anthropic` provider is on. | | signed in | `POST /playlists/{id}/suggest-name`, `POST /mixes/{id}/suggest-name`, `POST /smart-playlists/{id}/suggest-name` | A name and a line of description for a list of songs (body: `lang`, `variant`): Claude's when an admin turned the `anthropic` provider on, a local one otherwise (`source`). | | signed in | `GET /smart-playlists/suggested`, `GET /smart-playlists/suggested/{key}/tracks`, `POST /smart-playlists/suggested/{key}/playlist` | The smart playlists Sonda makes for everybody (a fixed set), their songs for you now (query `variant`), and one kept as a normal playlist. | | signed in | `GET /smart-playlists/{id}/tracks`, `POST /smart-playlists/preview`, `POST /smart-playlists/{id}/playlist` | The songs the rules give now (query `variant`), a preview of rules that are not kept, and a smart playlist kept as a normal playlist. | diff --git a/internal/api/http/contract_test.go b/internal/api/http/contract_test.go index 0168825..c2fe3c2 100644 --- a/internal/api/http/contract_test.go +++ b/internal/api/http/contract_test.go @@ -1085,6 +1085,15 @@ func (c *contract) smartPlaylists(t *testing.T, token string) { // names asks for names with the Claude provider off, so that the local ones answer. func (c *contract) names(t *testing.T, token string) { t.Helper() + c.expect(c.call("GET", "/naming", "", nil), 401, "naming status without a token", "unauthorized") + if st := c.expect(c.call("GET", "/naming", token, nil), 200, "naming status"); st["auto"] != false { + t.Fatalf("naming status = %v, want off", st) + } + named := c.expect(c.call("POST", "/mixes/genre%3Asynthwave/playlist", token, map[string]any{"name": "Synth mix", "auto_name": true, "lang": "it"}), 201, "keep a mix with an automatic name, Claude off") + if named["name"] != "Synth mix" { + t.Fatalf("playlist = %v: with Claude off the given name stays", named) + } + c.expect(c.call("POST", "/smart-playlists", token, map[string]any{"name": "", "rules": map[string]any{}, "lang": "it"}), 400, "a smart playlist with no name and Claude off", "invalid_input") c.expect(c.call("POST", "/mixes/genre%3Asynthwave/suggest-name", "", nil), 401, "a name without a token", "unauthorized") mix := c.expect(c.call("POST", "/mixes/genre%3Asynthwave/suggest-name", token, map[string]any{"lang": "it", "variant": 1}), 200, "a name for a mix") if mix["source"] != "local" || mix["name"] != "Mix Synthwave" { diff --git a/internal/api/http/handlers_mixes.go b/internal/api/http/handlers_mixes.go index 268bf03..e49c29d 100644 --- a/internal/api/http/handlers_mixes.go +++ b/internal/api/http/handlers_mixes.go @@ -16,6 +16,7 @@ import ( type mixHandlers struct { svc mixService playlists playlistService + naming namingService } type mixJSON struct { @@ -109,8 +110,10 @@ func (h *mixHandlers) get(c *gin.Context) { } type saveMixRequest struct { - Name string `json:"name"` // blank: the title of the mix - Variant *int `json:"variant"` // absent: the mix of the day + Name string `json:"name"` // blank: the title of the mix + Variant *int `json:"variant"` // absent: the mix of the day + AutoName bool `json:"auto_name"` // Claude names the playlist when it is on, and name is only the fallback + Lang string `json:"lang"` } // save makes a playlist of the songs of a mix, the ones that variant shows. A save that fails @@ -138,5 +141,6 @@ func (h *mixHandlers) save(c *gin.Context) { if strings.TrimSpace(name) == "" { name = m.Title } - keepAsPlaylist(c, h.playlists, user, name, tracks) + name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "mix", tracks, "", name) + keepAsPlaylist(c, h.playlists, user, name, description, tracks) } diff --git a/internal/api/http/handlers_naming.go b/internal/api/http/handlers_naming.go index a0392c8..2ce52e9 100644 --- a/internal/api/http/handlers_naming.go +++ b/internal/api/http/handlers_naming.go @@ -6,6 +6,7 @@ import ( "github.com/gin-gonic/gin" "codeberg.org/squidd/sonda/internal/catalog" + "codeberg.org/squidd/sonda/internal/naming" "codeberg.org/squidd/sonda/internal/playlists" ) @@ -116,3 +117,26 @@ func (h *namingHandlers) smartName(c *gin.Context) { } h.answer(c, "smart", tracks, p.Rules.Summary(), req.Lang) } + +// status says whether names are made by themselves, so that a page does not ask for a name that Claude will make. +func (h *namingHandlers) status(c *gin.Context) { + c.JSON(http.StatusOK, gin.H{"auto": h.svc.Auto(c.Request.Context())}) +} + +// automaticName gives the name and the line of description that Claude makes for the songs, when the page asked for it +// and the provider is on and answered. Otherwise it gives the name the page chose, with no description: a failure of the +// provider never stops a playlist from being made. +func automaticName(c *gin.Context, svc namingService, auto bool, lang, kind string, tracks []catalog.Track, hint, fallback string) (name, description string) { + if !auto || !svc.Auto(c.Request.Context()) { + return fallback, "" + } + facts, err := svc.FactsOf(c.Request.Context(), kind, tracks, hint) + if err != nil { + return fallback, "" + } + s, err := svc.Suggest(c.Request.Context(), facts, lang) + if err != nil || s.Source != naming.SourceClaude { + return fallback, "" + } + return s.Name, s.Description +} diff --git a/internal/api/http/handlers_playlists.go b/internal/api/http/handlers_playlists.go index 52a83b8..2627a3c 100644 --- a/internal/api/http/handlers_playlists.go +++ b/internal/api/http/handlers_playlists.go @@ -270,9 +270,9 @@ func (h *playlistHandlers) moveItem(c *gin.Context) { // keepAsPlaylist makes a playlist of the user with the songs, in order, and answers with it. A save that // fails half way leaves no playlist behind. -func keepAsPlaylist(c *gin.Context, svc playlistService, user int64, name string, tracks []catalog.Track) { +func keepAsPlaylist(c *gin.Context, svc playlistService, user int64, name, description string, tracks []catalog.Track) { ctx := c.Request.Context() - pl, err := svc.Create(ctx, user, name, "") + pl, err := svc.Create(ctx, user, name, description) if err != nil { writePlaylistError(c, err) return diff --git a/internal/api/http/handlers_smart.go b/internal/api/http/handlers_smart.go index aac6162..ce1d489 100644 --- a/internal/api/http/handlers_smart.go +++ b/internal/api/http/handlers_smart.go @@ -16,6 +16,7 @@ import ( type smartHandlers struct { svc smartService playlists playlistService + naming namingService } type smartJSON struct { @@ -63,6 +64,7 @@ func writeSmartError(c *gin.Context, err error) { } type createSmartRequest struct { + Lang string `json:"lang"` // for a name that Claude makes Name string `json:"name"` Description string `json:"description"` Rules smart.Rules `json:"rules"` @@ -75,9 +77,19 @@ func (h *smartHandlers) create(c *gin.Context) { if !bindJSON(c, &req) { return } - p, err := h.svc.Create(c.Request.Context(), currentUserID(c), smart.Input{ - Name: req.Name, Description: req.Description, Rules: req.Rules, Sort: smart.Sort(req.Sort), Limit: req.Limit, - }) + in := smart.Input{Name: req.Name, Description: req.Description, Rules: req.Rules, Sort: smart.Sort(req.Sort), Limit: req.Limit} + if strings.TrimSpace(in.Name) == "" && h.naming.Auto(c.Request.Context()) { + // No name, and Claude is on: it names the playlist from the songs the rules give. + if tracks, err := h.svc.Preview(c.Request.Context(), currentUserID(c), in, 0); err == nil { + if name, desc := automaticName(c, h.naming, true, req.Lang, "smart", tracks, in.Rules.Summary(), ""); name != "" { + in.Name = name + if strings.TrimSpace(in.Description) == "" { + in.Description = desc + } + } + } + } + p, err := h.svc.Create(c.Request.Context(), currentUserID(c), in) if err != nil { writeSmartError(c, err) return @@ -199,8 +211,10 @@ func (h *smartHandlers) preview(c *gin.Context) { } type saveSmartRequest struct { - Name string `json:"name"` // blank: the name of the smart playlist - Variant *int `json:"variant"` // absent: the songs of the day + Name string `json:"name"` // blank: the name of the smart playlist + Variant *int `json:"variant"` // absent: the songs of the day + AutoName bool `json:"auto_name"` // Claude names the playlist when it is on, and name is only the fallback + Lang string `json:"lang"` } // save makes a normal playlist of the songs the smart playlist gives now (the ones that variant shows). @@ -231,7 +245,8 @@ func (h *smartHandlers) save(c *gin.Context) { if strings.TrimSpace(name) == "" { name = p.Name } - keepAsPlaylist(c, h.playlists, user, name, tracks) + name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "smart", tracks, p.Rules.Summary(), name) + keepAsPlaylist(c, h.playlists, user, name, description, tracks) } // genres lists the genres of the library, to choose from in a rule: each with the number of songs, the @@ -304,7 +319,7 @@ func (h *smartHandlers) suggestedSave(c *gin.Context) { } user := currentUserID(c) key := c.Param("key") - _, tracks, err := h.svc.SuggestedTracks(c.Request.Context(), user, key, variant) + sg, tracks, err := h.svc.SuggestedTracks(c.Request.Context(), user, key, variant) if err != nil { writeSuggestedError(c, err) return @@ -317,5 +332,6 @@ func (h *smartHandlers) suggestedSave(c *gin.Context) { if name == "" { name = key // a client says the name in its language; this is only for one that does not } - keepAsPlaylist(c, h.playlists, user, name, tracks) + name, description := automaticName(c, h.naming, req.AutoName, req.Lang, "smart", tracks, sg.Rules.Summary(), name) + keepAsPlaylist(c, h.playlists, user, name, description, tracks) } diff --git a/internal/api/http/naming_test.go b/internal/api/http/naming_test.go index a212494..a336d0b 100644 --- a/internal/api/http/naming_test.go +++ b/internal/api/http/naming_test.go @@ -186,3 +186,142 @@ func TestNameErrorsAreTheOnesOfWhatIsNamed(t *testing.T) { t.Errorf("bad variant: %d", r.Code) } } + +// ---- names made by themselves ---- + +func playlistNamed(t *testing.T, m *mixAPI, id any) map[string]any { + t.Helper() + r := do(t, m.h, "GET", fmt.Sprintf("/api/v1/playlists/%v", id), m.alice, nil) + if r.Code != http.StatusOK { + t.Fatalf("playlist %v: %d %v", id, r.Code, r.Body) + } + return r.Body +} + +func TestWhenClaudeIsOnAKeptMixIsNamedByClaude(t *testing.T) { + c := &askedClaude{} + m := newNamingAPI(t, c, true) + r := do(t, m.h, "POST", "/api/v1/mixes/genre%3Ahard%20rock/playlist", m.alice, map[string]any{"name": "Mix Hard Rock", "auto_name": true, "lang": "it", "variant": 1}) + if r.Code != http.StatusCreated || r.Body["name"] != "Riff senza sosta" { + t.Fatalf("%d %v", r.Code, r.Body) + } + if got := playlistNamed(t, m, r.Body["id"]); got["description"] != "Hard rock che non hai ancora ascoltato." { + t.Errorf("playlist = %v: the line of description is kept too", got) + } + if len(c.asked) != 1 || c.asked[0].Kind != "mix" || c.asked[0].Language != "it" || c.asked[0].Tracks != 36 { + t.Errorf("asked %+v", c.asked) + } +} + +func TestTheNameGivenIsKeptWhenNothingAsksForAnAutomaticOne(t *testing.T) { + c := &askedClaude{} + m := newNamingAPI(t, c, true) + for name, body := range map[string]map[string]any{ + "auto_name false": {"name": "My own", "variant": 1}, + "auto_name absent": {"name": "My own"}, + } { + r := do(t, m.h, "POST", "/api/v1/mixes/genre%3Ahard%20rock/playlist", m.alice, body) + if r.Code != http.StatusCreated || r.Body["name"] != "My own" { + t.Errorf("%s: %d %v", name, r.Code, r.Body) + } + } + if len(c.asked) != 0 { + t.Errorf("Claude was asked for a name nobody wanted: %v", c.asked) + } +} + +func TestWithoutClaudeAnAutomaticNameIsTheOneGiven(t *testing.T) { + for name, tc := range map[string]struct { + claude *askedClaude + on bool + }{ + "the provider is off": {&askedClaude{}, false}, + "Claude fails": {&askedClaude{err: providers.ErrUnreachable}, true}, + "Claude declines": {&askedClaude{err: anthropic.ErrNoName}, true}, + } { + t.Run(name, func(t *testing.T) { + m := newNamingAPI(t, tc.claude, tc.on) + r := do(t, m.h, "POST", "/api/v1/mixes/genre%3Ahard%20rock/playlist", m.alice, map[string]any{"name": "Hard Rock Mix", "auto_name": true}) + if r.Code != http.StatusCreated || r.Body["name"] != "Hard Rock Mix" { + t.Fatalf("%d %v", r.Code, r.Body) + } + if got := playlistNamed(t, m, r.Body["id"]); got["description"] != "" { + t.Errorf("a description came from nowhere: %v", got) + } + if !tc.on && len(tc.claude.asked) != 0 { + t.Error("Claude was asked with the provider off") + } + }) + } +} + +func TestASmartAndASuggestedPlaylistAreNamedByClaudeWhenKept(t *testing.T) { + c := &askedClaude{} + m := newNamingAPI(t, c, true) + id := smartMade(t, m, map[string]any{"name": "Fresh", "limit": 8, "rules": map[string]any{"genres": []string{"rock"}, "never_played": true}}) + r := do(t, m.h, "POST", fmt.Sprintf("%s/%d/playlist", sp, id), m.alice, map[string]any{"name": "Fresh", "auto_name": true, "lang": "en"}) + if r.Code != http.StatusCreated || r.Body["name"] != "Riff senza sosta" { + t.Fatalf("smart: %d %v", r.Code, r.Body) + } + if got := c.asked[0]; got.Kind != "smart" || got.Hint != "genres: rock; never played" { + t.Errorf("smart facts = %+v", got) + } + s := do(t, m.h, "POST", sp+"/suggested/never-played/playlist", m.alice, map[string]any{"name": "Never played", "auto_name": true, "lang": "en"}) + if s.Code != http.StatusCreated || s.Body["name"] != "Riff senza sosta" { + t.Fatalf("suggested: %d %v", s.Code, s.Body) + } + if got := c.asked[1]; got.Kind != "smart" || got.Hint != "never played" { + t.Errorf("suggested facts = %+v", got) + } + // Without the request for it, the name stays. + n := do(t, m.h, "POST", sp+"/suggested/never-played/playlist", m.alice, map[string]any{"name": "Never played"}) + if n.Body["name"] != "Never played" || len(c.asked) != 2 { + t.Errorf("%v with %d questions", n.Body, len(c.asked)) + } +} + +func TestASmartPlaylistWithNoNameIsNamedByClaudeWhenItIsOn(t *testing.T) { + c := &askedClaude{} + m := newNamingAPI(t, c, true) + r := do(t, m.h, "POST", sp, m.alice, map[string]any{"name": " ", "rules": map[string]any{"genres": []string{"hard rock"}}, "limit": 12, "lang": "it"}) + if r.Code != http.StatusCreated || r.Body["name"] != "Riff senza sosta" || r.Body["description"] != "Hard rock che non hai ancora ascoltato." { + t.Fatalf("%d %v", r.Code, r.Body) + } + if got := c.asked[0]; got.Kind != "smart" || got.Tracks != 12 || got.Language != "it" || got.Hint != "genres: hard rock" { + t.Errorf("facts = %+v", got) + } + // A name that was given is the name, even with Claude on. + own := do(t, m.h, "POST", sp, m.alice, map[string]any{"name": "Mine", "rules": map[string]any{}}) + if own.Body["name"] != "Mine" || len(c.asked) != 1 { + t.Errorf("%v after %d questions", own.Body, len(c.asked)) + } +} + +func TestASmartPlaylistWithNoNameNeedsOneWhenClaudeCannotMakeIt(t *testing.T) { + for name, m := range map[string]*mixAPI{ + "off": newNamingAPI(t, &askedClaude{}, false), + "failing": newNamingAPI(t, &askedClaude{err: providers.ErrUnreachable}, true), + } { + r := do(t, m.h, "POST", sp, m.alice, map[string]any{"name": "", "rules": map[string]any{"genres": []string{"hard rock"}}}) + if r.Code != http.StatusBadRequest || errCode(r) != "invalid_input" { + t.Errorf("%s: %d %v", name, r.Code, r.Body) + } + if list := do(t, m.h, "GET", sp, m.alice, nil); list.Body["total"] != float64(0) { + t.Errorf("%s: a smart playlist was kept with no name: %v", name, list.Body) + } + } +} + +func TestTheClientCanAskWhetherNamesAreAutomatic(t *testing.T) { + on := newNamingAPI(t, &askedClaude{}, true) + if r := do(t, on.h, "GET", "/api/v1/naming", on.alice, nil); r.Code != http.StatusOK || r.Body["auto"] != true { + t.Errorf("on: %d %v", r.Code, r.Body) + } + off := newNamingAPI(t, &askedClaude{}, false) + if r := do(t, off.h, "GET", "/api/v1/naming", off.alice, nil); r.Code != http.StatusOK || r.Body["auto"] != false || len(r.Body) != 1 { + t.Errorf("off: %d %v", r.Code, r.Body) + } + if r := do(t, off.h, "GET", "/api/v1/naming", "", nil); r.Code != http.StatusUnauthorized { + t.Errorf("no token: %d", r.Code) + } +} diff --git a/internal/api/http/router.go b/internal/api/http/router.go index 730c92e..b3e5ed4 100644 --- a/internal/api/http/router.go +++ b/internal/api/http/router.go @@ -112,6 +112,7 @@ type mixService interface { type namingService interface { FactsOf(ctx context.Context, kind string, tracks []catalog.Track, hint string) (naming.Facts, error) Suggest(ctx context.Context, f naming.Facts, lang string) (naming.Suggestion, error) + Auto(ctx context.Context) bool } // smartService is what the handlers need from smart.Service. @@ -282,15 +283,16 @@ func NewRouter(d Deps) *gin.Engine { protected.POST("/playlists/:id/tracks", pl.addTracks) protected.DELETE("/playlists/:id/tracks/:item", pl.removeItem) protected.PATCH("/playlists/:id/tracks/:item", pl.moveItem) - mx := &mixHandlers{svc: d.Mixes, playlists: d.Playlists} + mx := &mixHandlers{svc: d.Mixes, playlists: d.Playlists, naming: d.Naming} protected.GET("/mixes", mx.list) protected.GET("/mixes/:id", mx.get) protected.POST("/mixes/:id/playlist", mx.save) nm := &namingHandlers{svc: d.Naming, playlists: d.Playlists, mixes: d.Mixes, smart: d.Smart} + protected.GET("/naming", nm.status) protected.POST("/playlists/:id/suggest-name", nm.playlistName) protected.POST("/mixes/:id/suggest-name", nm.mixName) protected.POST("/smart-playlists/:id/suggest-name", nm.smartName) - sm := &smartHandlers{svc: d.Smart, playlists: d.Playlists} + sm := &smartHandlers{svc: d.Smart, playlists: d.Playlists, naming: d.Naming} protected.GET("/genres", sm.genres) protected.GET("/smart-playlists", sm.list) protected.POST("/smart-playlists", sm.create) diff --git a/internal/api/openapi/openapi.yaml b/internal/api/openapi/openapi.yaml index d695f56..20d0e05 100644 --- a/internal/api/openapi/openapi.yaml +++ b/internal/api/openapi/openapi.yaml @@ -1667,6 +1667,29 @@ paths: '401': {$ref: '#/components/responses/Unauthorized'} '404': {$ref: '#/components/responses/PlaylistNotFound'} + /naming: + get: + tags: [Smart playlists] + operationId: getNamingStatus + summary: Whether names are made by themselves + description: | + `auto` is true when the `anthropic` provider is on with its key: a playlist that is kept from a mix or a smart + playlist with `auto_name`, and a smart playlist made with no name, are then named by Claude. A page asks this so + that it does not ask for a name that Claude will make. + security: [{bearerAuth: []}] + responses: + '200': + description: The status. + content: + application/json: + schema: + type: object + additionalProperties: false + required: [auto] + properties: + auto: {type: boolean} + '401': {$ref: '#/components/responses/Unauthorized'} + /playlists/{id}/suggest-name: parameters: - {$ref: '#/components/parameters/Id'} @@ -3596,6 +3619,8 @@ components: properties: name: {type: string, maxLength: 200, description: "The name of the playlist; blank or absent means the title of the mix."} variant: {type: integer, minimum: 0, maximum: 1000000, description: "The variant the client showed; absent means the mix of the day."} + auto_name: {type: boolean, default: false, description: "When true and the Claude provider is on, the playlist is named by Claude from its songs (with a line of description), and `name` is only the name to give it when Claude is off, fails or declines."} + lang: {type: string, maxLength: 16, description: "The language of a name that Claude makes: `en` or `it`. Absent or another: English."} GenreList: type: object @@ -3709,9 +3734,9 @@ components: CreateSmartPlaylist: type: object additionalProperties: false - required: [name] properties: - name: {type: string, minLength: 1, maxLength: 200, description: Trimmed.} + name: {type: string, maxLength: 200, description: "Trimmed. It can be blank or absent only when the Claude provider is on (see `GET /naming`): Claude then names the playlist from the songs its rules give, and a failure is `invalid_input`."} + lang: {type: string, maxLength: 16, description: "The language of a name that Claude makes: `en` or `it`. Absent or another: English."} description: {type: string, maxLength: 2000} rules: {$ref: '#/components/schemas/SmartRules'} sort: {$ref: '#/components/schemas/SmartSort'} @@ -3754,6 +3779,8 @@ components: properties: name: {type: string, maxLength: 200, description: "The name of the playlist; blank or absent means the name of the smart playlist."} variant: {type: integer, minimum: 0, maximum: 1000000, description: "The variant the client showed; absent means the songs of the day."} + auto_name: {type: boolean, default: false, description: "When true and the Claude provider is on, the playlist is named by Claude from its songs (with a line of description), and `name` is only the name to give it when Claude is off, fails or declines."} + lang: {type: string, maxLength: 16, description: "The language of a name that Claude makes: `en` or `it`. Absent or another: English."} Playlist: type: object diff --git a/internal/naming/naming.go b/internal/naming/naming.go index 0395670..d8c5a93 100644 --- a/internal/naming/naming.go +++ b/internal/naming/naming.go @@ -155,6 +155,13 @@ func (s *Service) Suggest(ctx context.Context, f Facts, language string) (Sugges return out, nil } +// Auto says whether names are made by themselves: the Claude provider is on, with its key. A provider that cannot be +// read counts as off. +func (s *Service) Auto(ctx context.Context) bool { + _, on, err := s.settings.Active(ctx, providers.Anthropic) + return err == nil && on +} + // junkArtists are the names that stand for nobody. var junkArtists = map[string]bool{"unknown artist": true, "various artists": true, "": true} diff --git a/web/src/api/mixes.ts b/web/src/api/mixes.ts index 74a7588..d677221 100644 --- a/web/src/api/mixes.ts +++ b/web/src/api/mixes.ts @@ -1,5 +1,6 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient } from '@tanstack/react-query' import { api } from './client' +import { useLang } from './naming' import { refresh as refreshPlaylists, type Playlist } from './playlists' import type { components } from './schema' @@ -29,8 +30,11 @@ export function useMix(id: string, variant: number) { /** Keeps the songs of a mix as a playlist of mine. */ export function useSaveMix() { const client = useQueryClient() + const lang = useLang() + // `name` is what the playlist is called unless Claude is on, which then names it from its songs. return useMutation({ - mutationFn: ({ id, ...body }: { id: string; name: string; variant: number }) => api.post(`${path(id)}/playlist`, body), + mutationFn: ({ id, ...body }: { id: string; name: string; variant: number }) => + api.post(`${path(id)}/playlist`, { ...body, auto_name: true, lang }), onSuccess: () => refreshPlaylists(client), }) } diff --git a/web/src/api/naming.ts b/web/src/api/naming.ts index deca5a8..8d47265 100644 --- a/web/src/api/naming.ts +++ b/web/src/api/naming.ts @@ -1,16 +1,31 @@ -import { useMutation } from '@tanstack/react-query' +import { useMutation, useQuery } from '@tanstack/react-query' import { useTranslation } from 'react-i18next' import { api } from './client' import type { components } from './schema' export type NameSuggestion = components['schemas']['NameSuggestion'] +/** The language the server is asked to name things in: the one of the page, Italian or English. */ +export function useLang(): 'it' | 'en' { + const { i18n } = useTranslation() + return i18n.language.toLowerCase().startsWith('it') ? 'it' : 'en' +} + +/** Whether names are made by themselves: the Claude provider is on. Until it is known, they are not. */ +export function useAutoNames(): boolean { + const status = useQuery({ + queryKey: ['naming'], + queryFn: () => api.get<{ auto: boolean }>('/naming'), + staleTime: 60_000, + }) + return status.data?.auto ?? false +} + /** * 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' + const lang = useLang() 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 9fb91cf..c07ec00 100644 --- a/web/src/api/schema.d.ts +++ b/web/src/api/schema.d.ts @@ -1172,6 +1172,28 @@ export interface paths { patch: operations["updatePlaylist"]; trace?: never; }; + "/naming": { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + /** + * Whether names are made by themselves + * @description `auto` is true when the `anthropic` provider is on with its key: a playlist that is kept from a mix or a smart + * playlist with `auto_name`, and a smart playlist made with no name, are then named by Claude. A page asks this so + * that it does not ask for a name that Claude will make. + */ + get: operations["getNamingStatus"]; + put?: never; + post?: never; + delete?: never; + options?: never; + head?: never; + patch?: never; + trace?: never; + }; "/playlists/{id}/suggest-name": { parameters: { query?: never; @@ -2427,6 +2449,13 @@ export interface components { name?: string; /** @description The variant the client showed; absent means the mix of the day. */ variant?: number; + /** + * @description When true and the Claude provider is on, the playlist is named by Claude from its songs (with a line of description), and `name` is only the name to give it when Claude is off, fails or declines. + * @default false + */ + auto_name: boolean; + /** @description The language of a name that Claude makes: `en` or `it`. Absent or another: English. */ + lang?: string; }; GenreList: { items: { @@ -2528,8 +2557,10 @@ export interface components { offset: number; }; CreateSmartPlaylist: { - /** @description Trimmed. */ - name: string; + /** @description Trimmed. It can be blank or absent only when the Claude provider is on (see `GET /naming`): Claude then names the playlist from the songs its rules give, and a failure is `invalid_input`. */ + name?: string; + /** @description The language of a name that Claude makes: `en` or `it`. Absent or another: English. */ + lang?: string; description?: string; rules?: components["schemas"]["SmartRules"]; sort?: components["schemas"]["SmartSort"]; @@ -2562,6 +2593,13 @@ export interface components { name?: string; /** @description The variant the client showed; absent means the songs of the day. */ variant?: number; + /** + * @description When true and the Claude provider is on, the playlist is named by Claude from its songs (with a line of description), and `name` is only the name to give it when Claude is off, fails or declines. + * @default false + */ + auto_name: boolean; + /** @description The language of a name that Claude makes: `en` or `it`. Absent or another: English. */ + lang?: string; }; Playlist: { /** Format: int64 */ @@ -4909,6 +4947,29 @@ export interface operations { 404: components["responses"]["PlaylistNotFound"]; }; }; + getNamingStatus: { + parameters: { + query?: never; + header?: never; + path?: never; + cookie?: never; + }; + requestBody?: never; + responses: { + /** @description The status. */ + 200: { + headers: { + [name: string]: unknown; + }; + content: { + "application/json": { + auto: boolean; + }; + }; + }; + 401: components["responses"]["Unauthorized"]; + }; + }; suggestPlaylistName: { parameters: { query?: never; diff --git a/web/src/api/smart.ts b/web/src/api/smart.ts index cfecda7..0bdfcca 100644 --- a/web/src/api/smart.ts +++ b/web/src/api/smart.ts @@ -1,6 +1,7 @@ import { keepPreviousData, useMutation, useQuery, useQueryClient, type QueryClient } from '@tanstack/react-query' import { api } from './client' import { usePagedList, type ListOptions, type Track } from './catalog' +import { useLang } from './naming' import type { Playlist } from './playlists' import { refresh as refreshPlaylists } from './playlists' import type { components } from './schema' @@ -78,9 +79,10 @@ export function useSuggestedTracks(key: string, variant: number) { /** Keeps the songs of a suggested one on screen as a normal playlist of mine. */ export function useSaveSuggested() { const client = useQueryClient() + const lang = useLang() return useMutation({ mutationFn: ({ key, ...body }: { key: string; name: string; variant: number }) => - api.post(`/smart-playlists/suggested/${encodeURIComponent(key)}/playlist`, body), + api.post(`/smart-playlists/suggested/${encodeURIComponent(key)}/playlist`, { ...body, auto_name: true, lang }), onSuccess: () => refreshPlaylists(client), }) } @@ -105,8 +107,10 @@ function refresh(client: QueryClient) { export function useCreateSmart() { const client = useQueryClient() + const lang = useLang() + // A blank name is for Claude to fill in, when it is on. return useMutation({ - mutationFn: (body: SmartInput & { name: string; description: string }) => api.post('/smart-playlists', body), + mutationFn: (body: SmartInput & { name: string; description: string }) => api.post('/smart-playlists', { ...body, lang }), onSuccess: () => refresh(client), }) } @@ -131,8 +135,10 @@ export function useDeleteSmart() { /** Keeps the songs on screen as a normal playlist of mine. */ export function useSaveSmart() { const client = useQueryClient() + const lang = useLang() return useMutation({ - mutationFn: ({ id, ...body }: { id: number; name: string; variant: number }) => api.post(`/smart-playlists/${id}/playlist`, body), + mutationFn: ({ id, ...body }: { id: number; name: string; variant: number }) => + api.post(`/smart-playlists/${id}/playlist`, { ...body, auto_name: true, lang }), onSuccess: () => refreshPlaylists(client), }) } diff --git a/web/src/i18n/locales/en.json b/web/src/i18n/locales/en.json index 72c2c23..31a9952 100644 --- a/web/src/i18n/locales/en.json +++ b/web/src/i18n/locales/en.json @@ -661,6 +661,7 @@ "titleNew": "New smart playlist", "titleEdit": "Edit smart playlist", "name": "Name", + "nameAuto": "Leave it empty and Claude will name it from its songs.", "description": "Description", "genres": "Genres", "genresHint": "Songs with any of these genres. Type one and press Enter.", diff --git a/web/src/i18n/locales/it.json b/web/src/i18n/locales/it.json index 8017de0..9d0a9b7 100644 --- a/web/src/i18n/locales/it.json +++ b/web/src/i18n/locales/it.json @@ -661,6 +661,7 @@ "titleNew": "Nuova playlist smart", "titleEdit": "Modifica playlist smart", "name": "Nome", + "nameAuto": "Lascialo vuoto e Claude le darà un nome in base ai brani.", "description": "Descrizione", "genres": "Generi", "genresHint": "Brani con uno qualsiasi di questi generi. Scrivine uno e premi Invio.", diff --git a/web/src/pages/SmartEditorPage.tsx b/web/src/pages/SmartEditorPage.tsx index 6950fa2..9d83657 100644 --- a/web/src/pages/SmartEditorPage.tsx +++ b/web/src/pages/SmartEditorPage.tsx @@ -15,6 +15,7 @@ import { type SmartPlaylist, type SmartSort, } from '@/api/smart' +import { useAutoNames } from '@/api/naming' import ChoiceGroup from '@/components/ChoiceGroup' import { EmptyMessage, ErrorMessage, Loading } from '@/components/Status' import SuggestName from '@/components/SuggestName' @@ -76,7 +77,9 @@ function SmartEditor({ existing }: { existing: SmartPlaylist | null }) { const limit = Math.min(MAX_LIMIT, Math.max(1, Math.floor(Number(limitText)) || DEFAULT_LIMIT)) const input = useDebounced({ rules, sort, limit }, 500) const preview = useSmartPreview(input) - const ready = name.trim() !== '' + // When Claude is on it names a new playlist that has no name: the field may stay empty. + const auto = useAutoNames() + const ready = name.trim() !== '' || (auto && existing === null) const pending = create.isPending || update.isPending const failure = create.error ?? update.error @@ -99,6 +102,7 @@ function SmartEditor({ existing }: { existing: SmartPlaylist | null }) {
setName(e.target.value)} /> + {auto && existing === null &&

{t('smart.editor.nameAuto')}

}
diff --git a/web/src/pages/mixes.test.tsx b/web/src/pages/mixes.test.tsx index 3801d8c..e309956 100644 --- a/web/src/pages/mixes.test.tsx +++ b/web/src/pages/mixes.test.tsx @@ -183,7 +183,7 @@ test('Save as playlist keeps the variant that is shown, names it with the title, const status = await screen.findByRole('status') expect(status).toHaveTextContent('Saved as “Hard Rock Mix”') - expect(saved).toEqual({ name: 'Hard Rock Mix', variant: 1 }) + expect(saved).toEqual({ name: 'Hard Rock Mix', variant: 1, auto_name: true, lang: 'en' }) expect(calls.some((c) => c.key === `POST /api/v1/mixes/${HARD_ROCK}/playlist`)).toBe(true) await userEvent.click(within(status).getByRole('link', { name: 'Open the playlist' })) diff --git a/web/src/pages/smart.test.tsx b/web/src/pages/smart.test.tsx index fd9b95f..b5dc927 100644 --- a/web/src/pages/smart.test.tsx +++ b/web/src/pages/smart.test.tsx @@ -211,7 +211,7 @@ test('Save as playlist keeps the variant on screen under the name, and links to await userEvent.click(screen.getByRole('button', { name: 'Save as playlist' })) const status = await screen.findByRole('status') expect(status).toHaveTextContent('Saved as “Fresh rock”') - expect(saved).toEqual({ name: 'Fresh rock', variant: 1 }) + expect(saved).toEqual({ name: 'Fresh rock', variant: 1, auto_name: true, lang: 'en' }) await userEvent.click(within(status).getByRole('link', { name: 'Open the playlist' })) expect(await screen.findByText('THE PLAYLIST PAGE')).toBeInTheDocument() }) @@ -276,7 +276,7 @@ test('a new smart playlist is made from the rules that were set, and its page op const post = calls.find((c) => c.key === 'POST /api/v1/smart-playlists')! expect(body(post)).toEqual({ - name: 'Fresh', description: '', sort: 'recently_added', limit: 50, + name: 'Fresh', description: '', sort: 'recently_added', limit: 50, lang: 'en', rules: { genres: ['rock'], formats: ['flac'], added_within_days: 30, never_played: true }, }) expect(await screen.findByRole('heading', { level: 1, name: 'Fresh' })).toBeInTheDocument() @@ -436,7 +436,7 @@ test('a suggested one plays, shuffles again and is kept as a playlist under its await waitFor(() => expect(screen.getByRole('button', { name: 'Save as playlist' })).toBeEnabled()) await userEvent.click(screen.getByRole('button', { name: 'Save as playlist' })) expect(await screen.findByRole('status')).toHaveTextContent('Saved as “Never played”') - expect(saved).toEqual({ name: 'Never played', variant: 1 }) + expect(saved).toEqual({ name: 'Never played', variant: 1, auto_name: true, lang: 'en' }) expect(calls.filter((c) => c.key.endsWith('/tracks')).map((c) => c.url.searchParams.get('variant'))).toEqual([null, '1']) }) @@ -458,7 +458,7 @@ test('Make it mine makes a smart playlist of my own with the same rules, and ope renderApp('/smart-playlists/suggested/never-played') await userEvent.click(await screen.findByRole('button', { name: 'Make it mine' })) const post = calls.find((c) => c.key === 'POST /api/v1/smart-playlists')! - expect(body(post)).toEqual({ name: 'Never played', description: 'Songs you have never listened to.', rules: { never_played: true }, sort: 'random', limit: 50 }) + expect(body(post)).toEqual({ name: 'Never played', description: 'Songs you have never listened to.', rules: { never_played: true }, sort: 'random', limit: 50, lang: 'en' }) expect(await screen.findByRole('heading', { level: 1, name: 'Edit smart playlist' })).toBeInTheDocument() }) @@ -511,3 +511,42 @@ test('the editor can count the plays over the last days, and sends it as a rule' await userEvent.click(screen.getByRole('radio', { name: 'Most played' })) await waitFor(() => expect(body(previewCalls(calls).at(-1)!)).toEqual({ rules: { min_plays: 2, plays_within_days: 30 }, sort: 'most_played', limit: 50 }), { timeout: 3000 }) }) + +// --- names that Claude makes by itself ---------------------------------------------------------- + +test('with Claude on, a new smart playlist can be kept with no name, and the page says so', async () => { + const { calls } = mockFetch( + editorRoutes({ + 'GET /api/v1/naming': () => ({ auto: true }), + 'POST /api/v1/smart-playlists': () => json(201, smart(7, 'Riff senza sosta', { rules: { genres: ['rock'] } })), + 'GET /api/v1/smart-playlists/7': () => smart(7, 'Riff senza sosta', { rules: { genres: ['rock'] } }), + 'GET /api/v1/smart-playlists/7/tracks': () => tracks(0, 1), + }), + ) + renderApp('/smart-playlists/new') + expect(await screen.findByText(/Claude will name it/)).toBeInTheDocument() + await userEvent.type(screen.getByRole('combobox', { name: 'Genres' }), 'rock{Enter}') + const save = screen.getByRole('button', { name: 'Save' }) + await waitFor(() => expect(save).toBeEnabled()) + await userEvent.click(save) + const post = await waitFor(() => calls.find((c) => c.key === 'POST /api/v1/smart-playlists')!) + expect(body(post)).toMatchObject({ name: '', lang: 'en', rules: { genres: ['rock'] } }) + expect(await screen.findByRole('heading', { level: 1, name: 'Riff senza sosta' })).toBeInTheDocument() +}) + +test('with Claude off a new smart playlist still needs a name, and says nothing about Claude', async () => { + mockFetch(editorRoutes({ 'GET /api/v1/naming': () => ({ auto: false }) })) + renderApp('/smart-playlists/new') + const save = await screen.findByRole('button', { name: 'Save' }) + expect(save).toBeDisabled() + expect(screen.queryByText(/Claude will name it/)).not.toBeInTheDocument() +}) + +test('a smart playlist that exists keeps needing its name, with Claude on too', async () => { + mockFetch(editorRoutes({ 'GET /api/v1/naming': () => ({ auto: true }), 'GET /api/v1/smart-playlists/3': () => smart(3, 'Fresh rock') })) + renderApp('/smart-playlists/3/edit') + const name = await screen.findByRole('textbox', { name: 'Name' }) + await userEvent.clear(name) + expect(screen.getByRole('button', { name: 'Save' })).toBeDisabled() + expect(screen.queryByText(/Claude will name it/)).not.toBeInTheDocument() +})