@audiofool/moondog 0.3.0-beta.15 → 0.3.0-beta.17

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (44) hide show
  1. package/README.md +6 -3
  2. package/package.json +3 -2
  3. package/scripts/moondog.mjs +4 -5
  4. package/src/core/capability-catalog.mjs +24 -14
  5. package/src/core/host.mjs +30 -0
  6. package/src/core/library-store.mjs +33 -1
  7. package/src/core/listening-now.mjs +7 -2
  8. package/src/core/moondog-application.mjs +219 -143
  9. package/src/i18n/messages/de.mjs +4 -3
  10. package/src/i18n/messages/en.mjs +4 -3
  11. package/src/i18n/messages/es.mjs +4 -3
  12. package/src/i18n/messages/fr.mjs +4 -3
  13. package/src/i18n/messages/it.mjs +4 -3
  14. package/src/i18n/messages/ja.mjs +4 -3
  15. package/src/i18n/messages/ko.mjs +4 -3
  16. package/src/i18n/messages/pt.mjs +4 -3
  17. package/src/i18n/messages/zh-Hant.mjs +4 -3
  18. package/src/i18n/messages/zh.mjs +4 -3
  19. package/src/i18n/screen/es.mjs +16 -3
  20. package/src/i18n/screen/ja.mjs +16 -3
  21. package/src/i18n/screen/pt.mjs +16 -3
  22. package/src/i18n/screen/zh.mjs +16 -3
  23. package/src/importers/zip-reader.mjs +61 -0
  24. package/src/integrations/apple-music/music-app.mjs +3 -2
  25. package/src/integrations/lastfm/history.mjs +2 -1
  26. package/src/integrations/lyrics/lrclib.mjs +1 -1
  27. package/src/integrations/netease/ncm-cli-player.mjs +62 -20
  28. package/src/integrations/open-music-similarity/artist-radio.mjs +3 -3
  29. package/src/integrations/spotify/account-data-history.mjs +63 -57
  30. package/src/integrations/spotify/authentication.mjs +2 -22
  31. package/src/integrations/spotify/extended-streaming-history.mjs +48 -40
  32. package/src/integrations/spotify/history-archive.mjs +2 -13
  33. package/src/integrations/spotify/service.mjs +62 -57
  34. package/src/integrations/spotify/web-api-client.mjs +4 -2
  35. package/src/integrations/user-agent.mjs +6 -0
  36. package/src/integrations/web/codex-web.mjs +3 -1
  37. package/src/integrations/youtube-music/takeout.mjs +11 -16
  38. package/src/profile/history-import.mjs +3 -1
  39. package/src/runtime/pi/agent-runtime.mjs +138 -136
  40. package/src/runtime/pi/next-songs.mjs +71 -0
  41. package/src/runtime/pi/persistent-credential-store.mjs +2 -0
  42. package/src/surfaces/cli/command-completions.mjs +1 -0
  43. package/src/surfaces/cli/format-output.mjs +19 -7
  44. package/src/surfaces/cli/tui.mjs +24 -1
@@ -152,30 +152,12 @@ function explicitQuickPlaylistIntent(text) {
152
152
  return match ? { action: "remove_track", playlistName: match[1], title: match[2], artist: match[3] } : null;
153
153
  }
154
154
 
155
- function spotifyPlaylistDetails({ name, description } = {}) {
156
- if (
157
- typeof name !== "string" ||
158
- name.trim().length < 1 ||
159
- Array.from(name).length > 100
160
- ) {
161
- throw spotifyResolutionError(
162
- "invalid_playlist_name",
163
- "The Spotify playlist name is invalid.",
164
- );
165
- }
166
- if (
167
- description !== undefined &&
168
- (typeof description !== "string" || Array.from(description).length > 200)
169
- ) {
170
- throw spotifyResolutionError(
171
- "invalid_playlist_description",
172
- "The Spotify playlist description is invalid.",
173
- );
155
+ // The name a saved plan's playlist takes: Spotify's limit of 100 characters, so its copy there carries the same name.
156
+ function planPlaylistName(name) {
157
+ if (typeof name !== "string" || name.trim().length < 1 || Array.from(name).length > 100) {
158
+ throw spotifyResolutionError("invalid_playlist_name", "The playlist name is invalid.");
174
159
  }
175
- return {
176
- name: name.trim(),
177
- ...(description !== undefined ? { description: description.trim() } : {}),
178
- };
160
+ return name.trim();
179
161
  }
180
162
 
181
163
  const requiredDomainServiceMethods = Object.freeze([
@@ -246,6 +228,8 @@ export const CONVERSATION_NAME_TIMEOUT_MS = 20_000;
246
228
  export class MoondogApplication {
247
229
  // Model calls naming conversations, stopped when the application closes.
248
230
  #naming = new Set();
231
+ // Up next's picks the window offers now, by reference (upNextProposals).
232
+ #proposals = new Map();
249
233
 
250
234
  constructor({
251
235
  importsRoot = resolveAppleMusicImportsRoot(),
@@ -945,31 +929,7 @@ export class MoondogApplication {
945
929
  if (service === "spotify") {
946
930
  if (!this.spotifyPlaybackReady()) throw Object.assign(new Error("Spotify is not ready to play here."), { code: "spotify_not_ready" });
947
931
  const list = songs.slice(0, 100);
948
- const refs = [];
949
- const avoidedFound = [];
950
- // A recording's own title and credit can name more than the entry does (a feature); an Avoid holds against it.
951
- const allowed = (title, credit) => this.avoidAllows({ title, artist_credit: credit });
952
- const uris = await mapLimited(list, 4, async (entry) => {
953
- // A cached recording plays without a search, once its own credit passes today's Avoids.
954
- if (entry.refs?.spotify_uri && entry.refs.spotify_credit) {
955
- if (allowed(entry.refs.spotify_title ?? entry.title, entry.refs.spotify_credit)) return entry.refs.spotify_uri;
956
- avoidedFound.push(entry.id);
957
- return null;
958
- }
959
- const { matched } = await this.spotifyResolveSongs([{ title: entry.title, artist: entry.artist_credit }], { signal }).catch(() => ({ matched: [] }));
960
- // A match reaches the model without its URI; the host keeps it under the match's reference.
961
- const ref = matched[0]?.item_ref_id;
962
- const known = ref ? this.spotifyHostReadItems().find((item) => item.item_ref_id === ref) : null;
963
- const uri = typeof known?.uri === "string" ? known.uri : typeof matched[0]?.uri === "string" ? matched[0].uri : null;
964
- if (!uri) return null;
965
- const title = known?.name ?? matched[0]?.name ?? entry.title;
966
- const credit = (known?.artists ?? matched[0]?.artists ?? []).join(", ") || entry.artist_credit;
967
- refs.push({ entryId: entry.id, refs: { spotify_uri: uri, spotify_title: title, spotify_credit: credit } });
968
- if (!allowed(title, credit)) { avoidedFound.push(entry.id); return null; }
969
- return uri;
970
- });
971
- signal?.throwIfAborted();
972
- this.libraryStore.rememberRefs(refs);
932
+ const { uris, avoidedFound } = await this.#spotifyUrisOf(list, { signal });
973
933
  const playable = uris.filter(Boolean);
974
934
  const skipped = avoided.length + avoidedFound.length;
975
935
  Object.assign(extra, skipped ? { skipped_avoided_count: skipped } : {});
@@ -992,6 +952,154 @@ export class MoondogApplication {
992
952
  throw Object.assign(new Error("No player here can play this playlist."), { code: "library_no_player" });
993
953
  }
994
954
 
955
+ // The Spotify recording of each library song, in the songs' order: the one a play or an export found before, or a
956
+ // search by title and artist, kept on the entry for next time. null stands for a song Spotify doesn't have or an
957
+ // Avoid holds back; avoidedFound names the second kind.
958
+ async #spotifyUrisOf(list, { signal } = {}) {
959
+ const refs = [];
960
+ const avoidedFound = [];
961
+ // A recording's own title and credit can name more than the entry does (a feature); an Avoid holds against it.
962
+ const allowed = (title, credit) => this.avoidAllows({ title, artist_credit: credit });
963
+ const uris = await mapLimited(list, 4, async (entry) => {
964
+ // A cached recording needs no search, once its own credit passes today's Avoids.
965
+ if (entry.refs?.spotify_uri && entry.refs.spotify_credit) {
966
+ if (allowed(entry.refs.spotify_title ?? entry.title, entry.refs.spotify_credit)) return entry.refs.spotify_uri;
967
+ avoidedFound.push(entry.id);
968
+ return null;
969
+ }
970
+ signal?.throwIfAborted();
971
+ const { matched } = await this.spotifyResolveSongs([{ title: entry.title, artist: entry.artist_credit }], { signal }).catch(() => ({ matched: [] }));
972
+ // A match reaches the model without its URI; the host keeps it under the match's reference.
973
+ const ref = matched[0]?.item_ref_id;
974
+ const known = ref ? this.spotifyHostReadItems().find((item) => item.item_ref_id === ref) : null;
975
+ const uri = typeof known?.uri === "string" ? known.uri : typeof matched[0]?.uri === "string" ? matched[0].uri : null;
976
+ if (!uri) return null;
977
+ const title = known?.name ?? matched[0]?.name ?? entry.title;
978
+ const credit = (known?.artists ?? matched[0]?.artists ?? []).join(", ") || entry.artist_credit;
979
+ refs.push({ entryId: entry.id, refs: { spotify_uri: uri, spotify_title: title, spotify_credit: credit } });
980
+ if (!allowed(title, credit)) { avoidedFound.push(entry.id); return null; }
981
+ return uri;
982
+ });
983
+ signal?.throwIfAborted();
984
+ this.libraryStore.rememberRefs(refs);
985
+ return { uris, avoidedFound };
986
+ }
987
+
988
+ /**
989
+ * Exports a library playlist to a music service, as a copy there. The playlist stays the listener's own, here;
990
+ * the copy follows it: the first export makes a playlist there, and a later one brings that same playlist up
991
+ * to date. A copy changed on the service since the last export is left alone (changed_on_service) until the
992
+ * listener says to replace it. Spotify is the service that takes a playlist so far. Tracks Moondog made have
993
+ * no recording there, so they stay out (left_out_made).
994
+ */
995
+ async exportLibraryPlaylist({ playlistId, service = "spotify", replace = false } = {}, { signal } = {}) {
996
+ const library = this.requireLibrary();
997
+ if (service !== "spotify") throw Object.assign(new Error("Only Spotify takes a playlist from the library so far."), { code: "library_export_unsupported" });
998
+ const playlist = library.playlist(playlistId);
999
+ if (!playlist) throw Object.assign(new Error("That playlist is not in the library."), { code: "library_playlist_not_found" });
1000
+ const named = { id: playlist.id, name: playlist.saved ? "Saved" : playlist.name };
1001
+ if (!this.spotifyReady()) throw Object.assign(new Error("Connect Spotify first, so Moondog can make a playlist there."), { code: "spotify_not_ready" });
1002
+ this.requireSpotifyWriteScopes(["playlist-modify-private"]);
1003
+ const songs = playlist.entries.filter((entry) => entry.kind === "song");
1004
+ const leftOut = playlist.entries.length - songs.length;
1005
+ const avoided = songs.filter((entry) => !this.avoidAllows({ title: entry.title, artist_credit: entry.artist_credit }));
1006
+ const list = songs.filter((entry) => !avoided.includes(entry));
1007
+ const found = await this.#spotifyUrisOf(list, { signal });
1008
+ // A song the playlist holds twice, or two entries Spotify answers with one recording, goes over once.
1009
+ const uris = [...new Set(found.uris.filter(Boolean))];
1010
+ const skipped = avoided.length + found.avoidedFound.length;
1011
+ const counts = { not_found: found.uris.filter((uri) => !uri).length - found.avoidedFound.length, left_out_made: leftOut,
1012
+ ...(skipped ? { skipped_avoided_count: skipped } : {}) };
1013
+ if (!uris.length) return { state: songs.length ? "not_found" : "empty", service, playlist: named, ...counts };
1014
+ const previous = playlist.exports?.find((copy) => copy.provider === service);
1015
+ const remember = (copy) => library.rememberExport(playlist.id, { provider: service, id: copy.playlistId,
1016
+ url: `https://open.spotify.com/playlist/${copy.playlistId}`, count: copy.track_count, signature: copy.signature });
1017
+ this.invalidateSpotifyQuickEditContext();
1018
+ let receipt;
1019
+ try {
1020
+ receipt = await this.requireSpotifyService().exportPlaylist({ name: named.name, uris, replace: replace === true,
1021
+ ...(previous ? { previous: { playlistId: previous.id, signature: previous.signature } } : {}) }, { signal });
1022
+ } catch (error) {
1023
+ if (error?.exportedCopy) remember(error.exportedCopy);
1024
+ throw error;
1025
+ }
1026
+ if (receipt.state === "changed_on_spotify") {
1027
+ return { state: "changed_on_service", service, playlist: named, url: previous.url, on_service: receipt.playlist.track_count, would_export: uris.length, ...counts };
1028
+ }
1029
+ remember({ playlistId: receipt.playlist_id, track_count: uris.length, signature: receipt.signature });
1030
+ return { state: receipt.state, service, playlist: named, url: `https://open.spotify.com/playlist/${receipt.playlist_id}`, exported: uris.length, ...counts };
1031
+ }
1032
+
1033
+ // Up next's picks: when the songs queued run low, the host picks what could come next (choose, the
1034
+ // conversation's model), and only the songs found playable on the player that plays now, past the listener's
1035
+ // Avoids, are offered. where is that player: "moondog" (Moondog's own, for Apple Music), "spotify" or "netease".
1036
+ // Each pick keeps what the player needs under a reference, so a click queues it without searching again.
1037
+ async upNextProposals({ playing, next = [], offered = [], where } = {}, { choose, signal } = {}) {
1038
+ const ready = where === "moondog" ? this.playbackService === "apple_music" && Boolean(this.musicCatalog) && typeof this.musicPreviewPlayer?.enqueue === "function"
1039
+ : where === "spotify" ? this.playbackService === "spotify" && this.spotifyPlaybackReady()
1040
+ : where === "netease" ? this.playbackService === "netease" && this.neteaseReady() : false;
1041
+ if (!ready || typeof choose !== "function" || !playing?.title) return [];
1042
+ const profile = await this.getListenerProfile().then(compactListenerProfile).catch(() => null);
1043
+ const brief = profile?.summary ? JSON.stringify({ summary: profile.summary, claims: (profile.claims ?? []).slice(0, 8),
1044
+ ...(profile.listener_choices ? { listener_choices: profile.listener_choices } : {}) }) : null;
1045
+ const picks = await choose({ playing, next, offered, profile: brief });
1046
+ signal?.throwIfAborted();
1047
+ const taken = new Set([playing, ...next].map((track) => `${track?.title ?? ""}`.toLowerCase()));
1048
+ const found = [];
1049
+ for (const pick of picks) {
1050
+ if (found.length >= 3) break;
1051
+ if (taken.has(pick.title.toLowerCase()) || !this.avoidAllows({ title: pick.title, artist_credit: pick.artist })) continue;
1052
+ const song = await this.#findUpNext(where, pick, { signal }).catch(() => null);
1053
+ signal?.throwIfAborted();
1054
+ if (!song || !this.avoidAllows({ title: song.title, artist_credit: song.artists.join(", "), artists: song.artists })) continue;
1055
+ taken.add(song.title.toLowerCase());
1056
+ const ref = `p${this.#proposals.size}-${Date.now().toString(36)}`;
1057
+ this.#proposals.set(ref, { where, ...song });
1058
+ while (this.#proposals.size > 30) this.#proposals.delete(this.#proposals.keys().next().value);
1059
+ found.push({ ref, title: song.title, artists: song.artists, image: song.image ?? null });
1060
+ }
1061
+ return found;
1062
+ }
1063
+
1064
+ async #findUpNext(where, { title, artist }, { signal } = {}) {
1065
+ if (where === "moondog") {
1066
+ const result = await this.musicCatalog.findPreview({ title, artist });
1067
+ if (result?.state !== "resolved") return null;
1068
+ const track = result.track;
1069
+ return { title: track.title, artists: [track.artist_credit].filter(Boolean), image: track.artwork_url ?? null, track };
1070
+ }
1071
+ if (where === "spotify") {
1072
+ const { matched } = await this.spotifyResolveSongs([{ title, artist }], { signal });
1073
+ const ref = matched[0]?.item_ref_id;
1074
+ const known = ref ? this.spotifyHostReadItems().find((item) => item.item_ref_id === ref) : null;
1075
+ const uri = typeof known?.uri === "string" ? known.uri : typeof matched[0]?.uri === "string" ? matched[0].uri : null;
1076
+ if (!uri) return null;
1077
+ return { title: known?.name ?? matched[0].name ?? title, artists: known?.artists ?? matched[0].artists ?? [artist], image: known?.image ?? null, uri };
1078
+ }
1079
+ const song = await this.requireNetease().find({ title, artist, intent: "为听者挑接下来的歌" });
1080
+ return song ? { title: song.title, artists: song.artists, image: song.image ?? null, id: song.id } : null;
1081
+ }
1082
+
1083
+ /** One of Up next's picks, added after what is queued on its player; it goes in the ledger as Moondog's suggestion. */
1084
+ async queueUpNextProposal(ref, { signal } = {}) {
1085
+ const song = this.#proposals.get(String(ref ?? ""));
1086
+ if (!song) return { state: "gone" };
1087
+ this.#proposals.delete(String(ref));
1088
+ if (song.where === "moondog") {
1089
+ if (!this.musicPreviewPlayer.enqueue(song.track)) return { state: "not_playing" };
1090
+ this.#noteSuggestions("apple_music", [{ action: "apple_music.queue.up_next", providerTrackId: song.track.catalog_id ? `apple_music:${song.track.catalog_id}` : null,
1091
+ isrc: song.track.isrc, title: song.title, artistCredit: song.track.artist_credit }]);
1092
+ return { state: "queued" };
1093
+ }
1094
+ if (song.where === "spotify") {
1095
+ await this.requireSpotifyService().addToQueue({ uri: song.uri }, { signal });
1096
+ this.#noteSuggestions("spotify", [{ action: "queue.up_next", providerTrackId: song.uri, title: song.title, artists: song.artists }]);
1097
+ return { state: "queued" };
1098
+ }
1099
+ const receipt = await this.playNetease({ items: [{ id: song.id }], mode: "queue", intent: "加入听者的接下来" });
1100
+ return { state: ["queued", "playing"].includes(receipt?.mode) ? "queued" : "not_found" };
1101
+ }
1102
+
995
1103
  // Makes one instrumental track from the listener's taste and plays it in Moondog's own player.
996
1104
  // The agent proposes sound descriptors, each with its source; the taste compiler keeps only the
997
1105
  // ones it can trace and none that names an artist or a song. The track and its receipt stay on
@@ -3718,30 +3826,6 @@ export class MoondogApplication {
3718
3826
  }
3719
3827
  }
3720
3828
 
3721
- async spotifyCreatePlaylist({ name, description, trackRefs } = {}, { signal } = {}) {
3722
- signal?.throwIfAborted();
3723
- this.requireSpotifyPlaylistCreationFlow();
3724
- if (
3725
- !Array.isArray(trackRefs) ||
3726
- !Array.isArray(this.validatedPlaylistTrackRefs) ||
3727
- trackRefs.length !== this.validatedPlaylistTrackRefs.length ||
3728
- trackRefs.some(
3729
- (trackRefId, index) =>
3730
- trackRefId !== this.validatedPlaylistTrackRefs[index],
3731
- )
3732
- ) {
3733
- throw spotifyResolutionError(
3734
- "spotify_playlist_plan_required",
3735
- "Spotify playlist writes require the exact validated playlist plan from this prompt.",
3736
- );
3737
- }
3738
- const details = spotifyPlaylistDetails({ name, description });
3739
- this.requireSpotifyWriteScopes(["playlist-modify-private"]);
3740
- const uris = this.requireSpotifyTrackUris(trackRefs);
3741
- const planned = new Map((this.pendingSpotifyPlaylist?.plan?.tracks ?? []).map((track) => [track.track_ref_id, track]));
3742
- return this.writeSpotifyPlaylist(details, uris, { signal, tracks: trackRefs.map((ref) => planned.get(ref) ?? null) });
3743
- }
3744
-
3745
3829
  pendingSpotifyPlaylistStatus() {
3746
3830
  const plan = this.pendingSpotifyPlaylist?.plan;
3747
3831
  if (!plan) return { state: "none" };
@@ -3781,44 +3865,63 @@ export class MoondogApplication {
3781
3865
  return structuredClone(this.pendingSpotifyPlaylist.plan);
3782
3866
  }
3783
3867
 
3784
- async spotifyCreatePendingPlaylist({ name, description } = {}, { signal } = {}) {
3868
+ /**
3869
+ * Keeps the validated playlist plan as a playlist in the listener's library, which is where a playlist is made
3870
+ * and arranged. The plan is this prompt's own (trackRefs, in its exact order) or the pending one the listener
3871
+ * approved. toSpotify also sends the new playlist to Spotify as its copy, through the library's export, so a
3872
+ * later export brings that same copy up to date. The library keeps the playlist even when the copy fails.
3873
+ * onSaved hears of the library playlist before anything is sent.
3874
+ */
3875
+ async savePlaylistPlan({ name, trackRefs, pending = false, toSpotify = false } = {}, { signal, onSaved } = {}) {
3785
3876
  signal?.throwIfAborted();
3786
3877
  this.requireSpotifyPlaylistCreationFlow();
3787
- if (!this.pendingSpotifyPlaylist) {
3788
- throw spotifyResolutionError(
3789
- "spotify_pending_playlist_unavailable",
3790
- "There is no pending validated playlist plan to save. Create a playlist plan first.",
3791
- );
3878
+ if (!pending && (!Array.isArray(trackRefs) || !Array.isArray(this.validatedPlaylistTrackRefs) ||
3879
+ trackRefs.length !== this.validatedPlaylistTrackRefs.length ||
3880
+ trackRefs.some((trackRefId, index) => trackRefId !== this.validatedPlaylistTrackRefs[index]))) {
3881
+ throw spotifyResolutionError("spotify_playlist_plan_required", "A playlist is saved from the exact validated playlist plan of this prompt.");
3792
3882
  }
3793
- const details = spotifyPlaylistDetails({ name, description });
3794
- this.requireSpotifyScopes(["user-read-private"]);
3795
- this.requireSpotifyWriteScopes(["playlist-modify-private"]);
3796
3883
  const draft = this.pendingSpotifyPlaylist;
3884
+ if (!draft?.plan) {
3885
+ throw spotifyResolutionError("spotify_pending_playlist_unavailable", "There is no pending validated playlist plan to save. Create a playlist plan first.");
3886
+ }
3887
+ const playlistName = planPlaylistName(name);
3888
+ const library = this.requireLibrary();
3797
3889
  const { kept, avoided } = this.#withoutAvoidedPlanTracks(draft.plan.tracks);
3798
- const result = await this.requireSpotifyResolver().resolve(
3799
- keptTrusted(draft, kept),
3800
- { signal },
3801
- );
3802
- signal?.throwIfAborted();
3803
- const resolvedByRef = new Map();
3804
- for (const resolution of result.resolutions ?? []) {
3805
- if (resolution.status === "resolved" && resolution.spotify?.uri) {
3806
- resolvedByRef.set(
3807
- resolution.track_ref_id,
3808
- resolution.spotify.uri,
3809
- );
3890
+ // For the copy, the resolver finds each song's Spotify recording from the plan's own track, which knows more
3891
+ // than a title and an artist. A song it can't place is searched by name at the export, and counted there.
3892
+ const uris = new Map();
3893
+ if (toSpotify && this.spotifyReady() && this.spotifyConnection?.resolver && draft.trustedTracks) {
3894
+ const result = await this.requireSpotifyResolver().resolve(keptTrusted(draft, kept), { signal })
3895
+ .catch((error) => (signal?.aborted ? Promise.reject(error) : { resolutions: [] }));
3896
+ for (const resolution of result.resolutions ?? []) {
3897
+ if (resolution.status === "resolved" && typeof resolution.spotify?.uri === "string") uris.set(resolution.track_ref_id, resolution.spotify.uri);
3810
3898
  }
3811
3899
  }
3812
- const uris = kept.map((track) =>
3813
- resolvedByRef.get(track.track_ref_id),
3814
- );
3815
- if (uris.some((uri) => typeof uri !== "string")) {
3816
- throw spotifyResolutionError(
3817
- "spotify_pending_playlist_unresolved",
3818
- "The pending playlist could not be fully resolved on Spotify, so no playlist was created.",
3819
- );
3900
+ signal?.throwIfAborted();
3901
+ if (this.pendingPlaylistPromptTransaction) this.pendingPlaylistPromptTransaction.playlistWriteAttempted = true;
3902
+ const made = library.savePlaylist({ name: playlistName, origin: "moondog", addedBy: "moondog", entries: kept.map((track) => ({
3903
+ kind: "song", title: track.title, artist_credit: track.artist_credit, ...(track.release ? { album: track.release } : {}),
3904
+ ...(uris.has(track.track_ref_id) ? { refs: { spotify_uri: uris.get(track.track_ref_id), spotify_title: track.title, spotify_credit: track.artist_credit } } : {}),
3905
+ })) });
3906
+ // Moondog chose these songs, so they go in the ledger under the service the listener plays them on.
3907
+ this.#noteSuggestions(toSpotify ? "spotify" : this.playbackService, kept.map((track) => ({ action: "playlist.write",
3908
+ ...(uris.has(track.track_ref_id) ? { providerTrackId: uris.get(track.track_ref_id) } : {}), title: track.title, artistCredit: track.artist_credit })));
3909
+ // The plan is a playlist now, so a cancelled prompt does not bring it back as pending.
3910
+ if (this.pendingPlaylistPromptTransaction) this.pendingPlaylistPromptTransaction.externalized = true;
3911
+ this.pendingSpotifyPlaylist = null;
3912
+ this.pendingPlaylistRevisionCandidateSet = null;
3913
+ const saved = { playlist: { id: made.id, name: library.playlist(made.id).name, track_count: made.added }, ...skippedAvoided(avoided) };
3914
+ onSaved?.(structuredClone(saved));
3915
+ if (!toSpotify) return saved;
3916
+ try {
3917
+ const sent = await this.exportLibraryPlaylist({ playlistId: made.id, service: "spotify" }, { signal });
3918
+ return { ...saved, spotify: { state: sent.state, ...(Number.isInteger(sent.exported) ? { exported: sent.exported } : {}), not_found: sent.not_found ?? 0 } };
3919
+ } catch (error) {
3920
+ if (signal?.aborted) throw error;
3921
+ // The playlist is in the library either way; the copy can be sent again with an export.
3922
+ return { ...saved, spotify: { state: error?.outcomeUnknown === true ? "unknown" : "failed",
3923
+ code: /^[a-z][a-z0-9_]{1,63}$/u.test(error?.code ?? "") ? error.code : "spotify_export_failed" } };
3820
3924
  }
3821
- return this.writeSpotifyPlaylist(details, uris, { signal, tracks: kept, avoided });
3822
3925
  }
3823
3926
 
3824
3927
  async spotifyPlayPendingPlan({ deviceId } = {}, { signal } = {}) {
@@ -4003,41 +4106,6 @@ export class MoondogApplication {
4003
4106
  ...(signal?.aborted ? { cancelled: true } : {}) };
4004
4107
  }
4005
4108
 
4006
- async writeSpotifyPlaylist(details, uris, { signal, tracks = [], avoided: leftOut = [] } = {}) {
4007
- signal?.throwIfAborted();
4008
- this.requireSpotifyPlaylistCreationFlow();
4009
- const { kept, avoided } = this.#withoutAvoidedPlanTracks(tracks);
4010
- if (avoided.length) {
4011
- uris = uris.filter((_uri, index) => kept.includes(tracks[index]));
4012
- tracks = kept;
4013
- }
4014
- if (this.pendingPlaylistPromptTransaction) this.pendingPlaylistPromptTransaction.playlistWriteAttempted = true;
4015
- this.invalidateSpotifyQuickEditContext();
4016
- try {
4017
- const receipt = await this.requireSpotifyService().createPlaylistWithTracks({
4018
- ...details,
4019
- uris,
4020
- }, { signal });
4021
- this.#noteSuggestions("spotify", tracks.flatMap((track, index) => track ? [{ action: "playlist.write",
4022
- providerTrackId: uris[index], title: track.title, artistCredit: track.artist_credit }] : []));
4023
- if (this.pendingPlaylistPromptTransaction) {
4024
- this.pendingPlaylistPromptTransaction.externalized = true;
4025
- }
4026
- this.pendingSpotifyPlaylist = null;
4027
- this.pendingPlaylistRevisionCandidateSet = null;
4028
- return { ...receipt, ...skippedAvoided([...leftOut, ...avoided]) };
4029
- } catch (error) {
4030
- if (error?.outcomeUnknown === true || ["playlist_created_without_tracks", "playlist_created_tracks_unknown"].includes(error?.code)) {
4031
- if (this.pendingPlaylistPromptTransaction) {
4032
- this.pendingPlaylistPromptTransaction.externalized = true;
4033
- }
4034
- this.pendingSpotifyPlaylist = null;
4035
- this.pendingPlaylistRevisionCandidateSet = null;
4036
- }
4037
- throw error;
4038
- }
4039
- }
4040
-
4041
4109
  async spotifySaveLibraryTracks({ trackRefs } = {}, { signal } = {}) {
4042
4110
  signal?.throwIfAborted();
4043
4111
  this.requireSpotifyWriteScopes(["user-library-modify"]);
@@ -4588,6 +4656,11 @@ export class MoondogApplication {
4588
4656
  const source = await this.sourceStatus();
4589
4657
  const profile = await this.profileStatus();
4590
4658
  const spotify = this.spotifyStatus();
4659
+ // A new install has imported nothing yet. That is a state to explain, not a failed check.
4660
+ const noLibrary = !this.profileServicesReady() && source.state === "missing" &&
4661
+ [null, "projection_subject_unavailable"].includes(this.domainServicesError);
4662
+ const similarityReady = this.musicSimilarityReady();
4663
+ const similarityWaits = noLibrary && !similarityReady && this.musicSimilarity !== null;
4591
4664
  const checks = [
4592
4665
  ...["search", "read"].map((kind) => {
4593
4666
  const lookup = this.webLookup(kind);
@@ -4607,14 +4680,15 @@ export class MoondogApplication {
4607
4680
  {
4608
4681
  id: "apple_music.source",
4609
4682
  ok: ["ready", "degraded"].includes(source.state),
4610
- state: source.state,
4611
- optional_for_local_commands: profile.state === "ready",
4683
+ state: noLibrary ? "no_library" : source.state,
4684
+ optional_for_local_commands: noLibrary || profile.state === "ready",
4612
4685
  },
4613
4686
  {
4614
4687
  id: "profile.projection",
4615
4688
  ok: profile.state === "ready",
4616
- state: profile.state,
4617
- ...(profile.error ? { error: profile.error } : {}),
4689
+ state: noLibrary ? "no_library" : profile.state,
4690
+ ...(profile.error && !noLibrary ? { error: profile.error } : {}),
4691
+ ...(noLibrary ? { optional_for_local_commands: true } : {}),
4618
4692
  },
4619
4693
  {
4620
4694
  id: "agent.runtime",
@@ -4624,8 +4698,9 @@ export class MoondogApplication {
4624
4698
  },
4625
4699
  {
4626
4700
  id: "music.discovery.open_similarity",
4627
- ok: this.musicSimilarityReady(),
4628
- state: this.musicSimilarityReady() ? "configured" : "unavailable",
4701
+ ok: similarityReady,
4702
+ state: similarityReady ? "configured" : similarityWaits ? "waiting_for_library" : "unavailable",
4703
+ ...(similarityWaits ? { optional_for_local_commands: true } : {}),
4629
4704
  },
4630
4705
  {
4631
4706
  id: "external.effects",
@@ -4662,6 +4737,7 @@ export class MoondogApplication {
4662
4737
  ok: checks
4663
4738
  .filter((check) => !check.optional_for_local_commands)
4664
4739
  .every((check) => check.ok),
4740
+ ...(noLibrary ? { library: "none" } : {}),
4665
4741
  checks,
4666
4742
  };
4667
4743
  }
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "Nicht hinzugefügt:",
71
71
  "queue.earlierReceipt": "Das ist das Ergebnis der früheren Warteschlangen-Aktion; diese Klarstellung hat die Songs nicht erneut hinzugefügt.",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify hat die private Playlist „${name}“ erstellt, aber das Hinzufügen der Titel wurde nicht bestätigt. Prüfe sie, bevor du entscheidest, ob du es erneut versuchst.`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify hat die private Playlist „${name}“ erstellt, aber keine Titel hinzugefügt. Die leere Playlist existiert jetzt; prüfe sie, bevor du entscheidest, ob du es erneut versuchst.`,
75
- "playlist.saved": ({ name, count }) => `Als private Spotify-Playlist „${name}“ gespeichert (${count} Titel).`,
73
+ "playlist.kept": ({ name, count }) => `In deiner Mediathek als „${name}“ gespeichert (${count} Titel).`,
74
+ "playlist.copyUnknown": ({ name }) => `Die Spotify-Kopie von „${name}“ wurde nicht bestätigt. Die Playlist ist in deiner Mediathek; prüfe Spotify, bevor du sie erneut exportierst.`,
75
+ "playlist.copyFailed": ({ name }) => `Die Spotify-Kopie von „${name}“ wurde nicht erstellt. Die Playlist ist in deiner Mediathek, und du kannst sie erneut exportieren.`,
76
+ "playlist.saved": ({ name, count }) => `Auf Spotify als Playlist „${name}“ gespeichert (${count} Titel).`,
76
77
 
77
78
  "action.playback.resume": "Wiedergabe-Anfrage",
78
79
  "action.playback.pause": "Pause-Anfrage",
@@ -71,9 +71,10 @@ export default {
71
71
  "queue.notAddedHeading": "Not added:",
72
72
  "queue.earlierReceipt": "This is the earlier queue receipt; this clarification did not add the songs again.",
73
73
 
74
- "playlist.partialUnknown": ({ name }) => `Spotify created the private playlist "${name}", but adding its tracks was not confirmed. Inspect it before deciding whether to retry.`,
75
- "playlist.partialEmpty": ({ name }) => `Spotify created the private playlist "${name}", but did not add its tracks. The empty playlist now exists; inspect it before deciding whether to retry.`,
76
- "playlist.saved": ({ name, count }) => `Saved as the private Spotify playlist "${name}" (${count} tracks).`,
74
+ "playlist.kept": ({ name, count }) => `Saved in your library as "${name}" (${count} songs).`,
75
+ "playlist.copyUnknown": ({ name }) => `The Spotify copy of "${name}" was not confirmed. The playlist is in your library; check Spotify before you export it again.`,
76
+ "playlist.copyFailed": ({ name }) => `The Spotify copy of "${name}" was not made. The playlist is in your library, and you can export it again.`,
77
+ "playlist.saved": ({ name, count }) => `Saved on Spotify as the playlist "${name}" (${count} tracks).`,
77
78
 
78
79
  "action.playback.resume": "playback request",
79
80
  "action.playback.pause": "pause request",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "Sin añadir:",
71
71
  "queue.earlierReceipt": "Este es el resultado de la cola anterior; esta aclaración no volvió a añadir las canciones.",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify creó la playlist privada "${name}", pero no confirmó que se añadieran las canciones. Revísala antes de decidir si lo intentas de nuevo.`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify creó la playlist privada "${name}", pero no añadió las canciones. La playlist vacía ya existe; revísala antes de decidir si lo intentas de nuevo.`,
75
- "playlist.saved": ({ name, count }) => `Guardada como la playlist privada de Spotify "${name}" (${count} canciones).`,
73
+ "playlist.kept": ({ name, count }) => `Guardada en tu biblioteca como "${name}" (${count} canciones).`,
74
+ "playlist.copyUnknown": ({ name }) => `No se confirmó la copia de "${name}" en Spotify. La playlist está en tu biblioteca; revisa Spotify antes de exportarla de nuevo.`,
75
+ "playlist.copyFailed": ({ name }) => `No se hizo la copia de "${name}" en Spotify. La playlist está en tu biblioteca y puedes exportarla de nuevo.`,
76
+ "playlist.saved": ({ name, count }) => `Guardada en Spotify como la playlist "${name}" (${count} canciones).`,
76
77
 
77
78
  "action.playback.resume": "la petición de reproducción",
78
79
  "action.playback.pause": "la pausa",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "Non ajoutés :",
71
71
  "queue.earlierReceipt": "Voici le reçu de l'ajout précédent ; cette précision n'a pas ajouté les morceaux une seconde fois.",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify a créé la playlist privée « ${name} », mais l'ajout de ses morceaux n'a pas été confirmé. Vérifiez-la avant de décider de réessayer.`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify a créé la playlist privée « ${name} », mais n'a pas ajouté ses morceaux. La playlist vide existe désormais ; vérifiez-la avant de décider de réessayer.`,
75
- "playlist.saved": ({ name, count }) => `Enregistré comme playlist Spotify privée « ${name} » (${count} morceaux).`,
73
+ "playlist.kept": ({ name, count }) => `Enregistrée dans votre bibliothèque sous « ${name} » (${count} morceaux).`,
74
+ "playlist.copyUnknown": ({ name }) => `La copie Spotify de « ${name} » n'a pas été confirmée. La playlist est dans votre bibliothèque ; vérifiez Spotify avant de l'exporter à nouveau.`,
75
+ "playlist.copyFailed": ({ name }) => `La copie Spotify de « ${name} » n'a pas été créée. La playlist est dans votre bibliothèque et vous pouvez l'exporter à nouveau.`,
76
+ "playlist.saved": ({ name, count }) => `Enregistrée sur Spotify comme playlist « ${name} » (${count} morceaux).`,
76
77
 
77
78
  "action.playback.resume": "demande de lecture",
78
79
  "action.playback.pause": "demande de pause",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "Non aggiunti:",
71
71
  "queue.earlierReceipt": "Questo è l'esito della richiesta di coda precedente; questo chiarimento non ha aggiunto di nuovo i brani.",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify ha creato la playlist privata "${name}", ma l'aggiunta dei brani non è stata confermata. Controllala prima di decidere se riprovare.`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify ha creato la playlist privata "${name}", ma non ha aggiunto i brani. La playlist vuota ora esiste; controllala prima di decidere se riprovare.`,
75
- "playlist.saved": ({ name, count }) => `Salvata come playlist privata di Spotify "${name}" (${count} brani).`,
73
+ "playlist.kept": ({ name, count }) => `Salvata nella tua libreria come "${name}" (${count} brani).`,
74
+ "playlist.copyUnknown": ({ name }) => `La copia di "${name}" su Spotify non è stata confermata. La playlist è nella tua libreria; controlla Spotify prima di esportarla di nuovo.`,
75
+ "playlist.copyFailed": ({ name }) => `La copia di "${name}" su Spotify non è stata creata. La playlist è nella tua libreria e puoi esportarla di nuovo.`,
76
+ "playlist.saved": ({ name, count }) => `Salvata su Spotify come playlist "${name}" (${count} brani).`,
76
77
 
77
78
  "action.playback.resume": "richiesta di riproduzione",
78
79
  "action.playback.pause": "richiesta di pausa",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "まだ追加していない曲:",
71
71
  "queue.earlierReceipt": "これは前回のキュー操作の結果です。今回の補足では曲を再度追加していません。",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify に非公開プレイリスト「${name}」を作成しましたが、曲の追加は確認できませんでした。再試行する前にプレイリストを確認してください。`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify に非公開プレイリスト「${name}」を作成しましたが、曲は追加されませんでした。空のプレイリストが残っています。再試行する前に確認してください。`,
75
- "playlist.saved": ({ name, count }) => `Spotify の非公開プレイリスト「${name}」として保存しました(${count} 曲)。`,
73
+ "playlist.kept": ({ name, count }) => `ライブラリにプレイリスト「${name}」として保存しました(${count} 曲)。`,
74
+ "playlist.copyUnknown": ({ name }) => `Spotify 側の「${name}」のコピーは確認できませんでした。プレイリストはライブラリにあります。もう一度書き出す前に Spotify を確認してください。`,
75
+ "playlist.copyFailed": ({ name }) => `Spotify 側の「${name}」のコピーは作成されませんでした。プレイリストはライブラリにあり、もう一度書き出せます。`,
76
+ "playlist.saved": ({ name, count }) => `Spotify にプレイリスト「${name}」として保存しました(${count} 曲)。`,
76
77
 
77
78
  "action.playback.resume": "再生リクエスト",
78
79
  "action.playback.pause": "一時停止",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "추가하지 않은 곡:",
71
71
  "queue.earlierReceipt": "이것은 앞선 대기열 작업의 결과입니다. 이번 설명으로 곡을 다시 넣지는 않았습니다.",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify에 비공개 플레이리스트 "${name}" 생성은 끝났지만, 곡 추가는 확인되지 않았습니다. 다시 시도할지 정하기 전에 확인해 주세요.`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify에 비공개 플레이리스트 "${name}" 생성은 끝났지만 곡은 추가하지 않았습니다. 빈 플레이리스트가 생겼으니 다시 시도할지 정하기 전에 확인해 주세요.`,
75
- "playlist.saved": ({ name, count }) => `Spotify 비공개 플레이리스트 "${name}"(${count}곡)으로 저장했습니다.`,
73
+ "playlist.kept": ({ name, count }) => `보관함에 플레이리스트 "${name}"(${count}곡)으로 저장했습니다.`,
74
+ "playlist.copyUnknown": ({ name }) => `Spotify의 "${name}" 사본은 확인되지 않았습니다. 플레이리스트는 보관함에 있습니다. 다시 내보내기 전에 Spotify를 확인해 주세요.`,
75
+ "playlist.copyFailed": ({ name }) => `Spotify의 "${name}" 사본은 만들어지지 않았습니다. 플레이리스트는 보관함에 있으며 다시 내보낼 수 있습니다.`,
76
+ "playlist.saved": ({ name, count }) => `Spotify에 플레이리스트 "${name}"(${count}곡)으로 저장했습니다.`,
76
77
 
77
78
  "action.playback.resume": "재생 요청",
78
79
  "action.playback.pause": "일시 정지 요청",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "Não adicionadas:",
71
71
  "queue.earlierReceipt": "Este é o resultado da fila anterior; este esclarecimento não adicionou as músicas de novo.",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `O Spotify criou a playlist privada "${name}", mas não confirmou que as músicas foram adicionadas. Confira antes de decidir se tenta de novo.`,
74
- "playlist.partialEmpty": ({ name }) => `O Spotify criou a playlist privada "${name}", mas não adicionou as músicas. A playlist vazia já existe; confira antes de decidir se tenta de novo.`,
75
- "playlist.saved": ({ name, count }) => `Salva como a playlist privada do Spotify "${name}" (${count} músicas).`,
73
+ "playlist.kept": ({ name, count }) => `Salva na sua biblioteca como "${name}" (${count} músicas).`,
74
+ "playlist.copyUnknown": ({ name }) => `A cópia de "${name}" no Spotify não foi confirmada. A playlist está na sua biblioteca; confira o Spotify antes de exportar de novo.`,
75
+ "playlist.copyFailed": ({ name }) => `A cópia de "${name}" no Spotify não foi feita. A playlist está na sua biblioteca, e você pode exportar de novo.`,
76
+ "playlist.saved": ({ name, count }) => `Salva no Spotify como a playlist "${name}" (${count} músicas).`,
76
77
 
77
78
  "action.playback.resume": "o pedido de reprodução",
78
79
  "action.playback.pause": "a pausa",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "沒有加入:",
71
71
  "queue.earlierReceipt": "這是上一次佇列操作的結果;這次說明沒有再次加入歌曲。",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify 已建立私人播放清單「${name}」,但加入曲目的結果尚未確認。請先檢查再決定是否重試。`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify 已建立私人播放清單「${name}」,但沒有加入曲目;這個空的播放清單已經存在,請先檢查再決定是否重試。`,
75
- "playlist.saved": ({ name, count }) => `已儲存為 Spotify 私人播放清單「${name}」(${count} 首)。`,
73
+ "playlist.kept": ({ name, count }) => `已存進你的資料庫,播放清單「${name}」(${count} 首)。`,
74
+ "playlist.copyUnknown": ({ name }) => `Spotify 上「${name}」的副本是否建好尚未確認。播放清單已在你的資料庫裡;再次匯出前請先看一下 Spotify。`,
75
+ "playlist.copyFailed": ({ name }) => `Spotify 上「${name}」的副本沒有建成。播放清單已在你的資料庫裡,可以再匯出一次。`,
76
+ "playlist.saved": ({ name, count }) => `已儲存到 Spotify,播放清單「${name}」(${count} 首)。`,
76
77
 
77
78
  "action.playback.resume": "播放請求",
78
79
  "action.playback.pause": "暫停請求",
@@ -70,9 +70,10 @@ export default {
70
70
  "queue.notAddedHeading": "还没加入:",
71
71
  "queue.earlierReceipt": "这是上次队列操作的结果;这次澄清没有再次添加歌曲。",
72
72
 
73
- "playlist.partialUnknown": ({ name }) => `Spotify 已创建私有歌单「${name}」,但加入曲目的结果尚未确认。请检查歌单后再决定是否重试。`,
74
- "playlist.partialEmpty": ({ name }) => `Spotify 已创建私有歌单「${name}」,但未能加入曲目;这个空歌单已经存在,请检查后再决定是否重试。`,
75
- "playlist.saved": ({ name, count }) => `已保存为 Spotify 私有歌单「${name}」(${count} 首)。`,
73
+ "playlist.kept": ({ name, count }) => `已存进你的资料库,歌单「${name}」(${count} 首)。`,
74
+ "playlist.copyUnknown": ({ name }) => `Spotify 上「${name}」的副本是否建好尚未确认。歌单已在你的资料库里;再次导出前请先看一下 Spotify。`,
75
+ "playlist.copyFailed": ({ name }) => `Spotify 上「${name}」的副本没有建成。歌单已在你的资料库里,可以再导出一次。`,
76
+ "playlist.saved": ({ name, count }) => `已保存到 Spotify,歌单「${name}」(${count} 首)。`,
76
77
 
77
78
  "action.playback.resume": "播放请求",
78
79
  "action.playback.pause": "暂停请求",