@audiofool/moondog 0.4.0-beta.2 → 0.4.0-beta.4

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 (96) hide show
  1. package/README.md +19 -8
  2. package/package.json +1 -1
  3. package/scripts/moondog.mjs +130 -106
  4. package/src/core/apple-library-source-status.mjs +64 -18
  5. package/src/core/apple-projection-domain-services.mjs +67 -52
  6. package/src/core/capability-catalog.mjs +18 -2
  7. package/src/core/import-source-history.mjs +28 -0
  8. package/src/core/library-draft.mjs +16 -0
  9. package/src/core/library-names.mjs +12 -0
  10. package/src/core/library-store.mjs +361 -23
  11. package/src/core/listener-avoids.mjs +31 -0
  12. package/src/core/listening-action.mjs +41 -0
  13. package/src/core/listening-moment.mjs +67 -0
  14. package/src/core/listening-now.mjs +69 -28
  15. package/src/core/listening-profile-domain-services.mjs +32 -18
  16. package/src/core/listening-scope.mjs +119 -0
  17. package/src/core/moondog-application.mjs +1045 -270
  18. package/src/core/play-follower.mjs +104 -0
  19. package/src/core/portable-playlist.mjs +125 -0
  20. package/src/core/profile-discovery-draft.mjs +35 -0
  21. package/src/core/track-title.mjs +70 -4
  22. package/src/i18n/import-history.mjs +647 -0
  23. package/src/i18n/messages/de.mjs +3 -3
  24. package/src/i18n/messages/en.mjs +3 -3
  25. package/src/i18n/messages/es.mjs +3 -3
  26. package/src/i18n/messages/fr.mjs +3 -3
  27. package/src/i18n/messages/it.mjs +3 -3
  28. package/src/i18n/messages/ja.mjs +3 -3
  29. package/src/i18n/messages/ko.mjs +3 -3
  30. package/src/i18n/messages/pt.mjs +3 -3
  31. package/src/i18n/messages/zh-Hant.mjs +3 -3
  32. package/src/i18n/messages/zh.mjs +3 -3
  33. package/src/i18n/screen/es.mjs +90 -26
  34. package/src/i18n/screen/ja.mjs +89 -25
  35. package/src/i18n/screen/pt.mjs +90 -26
  36. package/src/i18n/screen/zh.mjs +89 -25
  37. package/src/importers/apple-music-library/import-batch.mjs +64 -32
  38. package/src/importers/apple-music-library/normalize.mjs +36 -6
  39. package/src/importers/apple-music-library/save-time.mjs +17 -0
  40. package/src/importers/zip-reader.mjs +24 -2
  41. package/src/integrations/apple-music/catalog-playlist-reader.mjs +111 -0
  42. package/src/integrations/apple-music/catalog.mjs +84 -25
  43. package/src/integrations/apple-music/music-app-listening.mjs +107 -0
  44. package/src/integrations/apple-music/music-app.mjs +6 -2
  45. package/src/integrations/apple-music/song-id.mjs +13 -0
  46. package/src/integrations/apple-music/terminal-preview-player.mjs +154 -44
  47. package/src/integrations/listenbrainz/history-file.mjs +63 -35
  48. package/src/integrations/netease/ncm-cli-player.mjs +355 -68
  49. package/src/integrations/netease/queue-occurrence.mjs +138 -0
  50. package/src/integrations/playlist-links.mjs +93 -30
  51. package/src/integrations/public-playlists.mjs +21 -15
  52. package/src/integrations/spotify/account-data-history.mjs +9 -10
  53. package/src/integrations/spotify/account-data-profile.mjs +1 -0
  54. package/src/integrations/spotify/extended-streaming-history.mjs +57 -52
  55. package/src/integrations/spotify/history-archive.mjs +8 -18
  56. package/src/integrations/spotify/library-snapshot.mjs +2 -1
  57. package/src/integrations/spotify/service.mjs +29 -11
  58. package/src/integrations/spotify/web-api-client.mjs +2 -2
  59. package/src/integrations/stable-audio/local-generator.mjs +13 -5
  60. package/src/integrations/youtube-music/takeout.mjs +12 -8
  61. package/src/memory/local-memory-store.mjs +479 -27
  62. package/src/memory/reflection-worker.mjs +19 -0
  63. package/src/profile/apple-library-import.mjs +56 -2
  64. package/src/profile/history-import.mjs +58 -27
  65. package/src/profile/listener-corrections.mjs +2 -4
  66. package/src/profile/listener-profile-build.mjs +133 -46
  67. package/src/profile/listener-profile-store.mjs +57 -4
  68. package/src/profile/listener-profile-verification.mjs +11 -5
  69. package/src/profile/listener-profile-worker.mjs +36 -10
  70. package/src/profile/listening-history-store.mjs +975 -354
  71. package/src/profile/listening-profile-projection.mjs +130 -160
  72. package/src/profile/local-file-import.mjs +172 -0
  73. package/src/profile/moondog-suggestions.mjs +40 -11
  74. package/src/profile/profile-exploration.mjs +36 -6
  75. package/src/profile/recorded-measures.mjs +5 -0
  76. package/src/profile/spotify-archive-taste.mjs +41 -65
  77. package/src/runtime/pi/agent-runtime.mjs +368 -221
  78. package/src/runtime/pi/custom-endpoints.mjs +30 -8
  79. package/src/runtime/pi/memory-agent-runtime.mjs +45 -3
  80. package/src/runtime/pi/moondog-model.mjs +6 -0
  81. package/src/runtime/pi/playback-rules.mjs +100 -0
  82. package/src/runtime/pi/profile-build-runtime.mjs +85 -24
  83. package/src/surfaces/cli/brand-components.mjs +9 -6
  84. package/src/surfaces/cli/command-completions.mjs +8 -1
  85. package/src/surfaces/cli/format-output.mjs +207 -34
  86. package/src/surfaces/cli/history-import-view.mjs +130 -21
  87. package/src/surfaces/cli/listenbrainz-command.mjs +7 -2
  88. package/src/surfaces/cli/listener-profile-command.mjs +67 -8
  89. package/src/surfaces/cli/listening-menu.mjs +3 -0
  90. package/src/surfaces/cli/profile-command.mjs +1 -0
  91. package/src/surfaces/cli/spotify-command.mjs +17 -25
  92. package/src/surfaces/cli/taste-period.mjs +22 -0
  93. package/src/surfaces/cli/taste-profile-model.mjs +52 -32
  94. package/src/surfaces/cli/tui.mjs +557 -170
  95. package/src/surfaces/html/tasteprint.mjs +181 -93
  96. package/src/surfaces/import-source-history.mjs +80 -0
@@ -1,4 +1,7 @@
1
+ import { hasLibraryDraftHeader, libraryDraftLocation, libraryDraftText } from "../../core/library-draft.mjs";
2
+ import { importHistoryStrings } from "../../i18n/import-history.mjs";
1
3
  import { homedir } from "node:os";
4
+ import { resolve, sep } from "node:path";
2
5
  import { LOCALES, N_, intlLocale, liveScreenTranslator, normalizeLocale, translator } from "../../i18n/index.mjs";
3
6
  import {
4
7
  CombinedAutocompleteProvider,
@@ -28,6 +31,7 @@ import { MODEL_ROLE_WORDS } from "./model-roles-command.mjs";
28
31
  import { followChatModel } from "../../runtime/pi/model-roles.mjs";
29
32
  import { imagesFromText } from "../../runtime/pi/image-input.mjs";
30
33
  import {
34
+ formatImportReceipt,
31
35
  formatLocalResult,
32
36
  helpText,
33
37
  safeInlineText,
@@ -37,9 +41,11 @@ import {
37
41
  import { createMoondogTheme } from "./brand-theme.mjs";
38
42
  import { SeasonsChart } from "./seasons-chart.mjs";
39
43
  import { LOGO_MOTION_INTERVAL_MS } from "./terminal-art.mjs";
40
- import { buildTasteProfileModel } from "./taste-profile-model.mjs";
44
+ import { buildTasteProfileModel, readTasteReviewProfile } from "./taste-profile-model.mjs";
41
45
  import { TasteProfileView } from "./taste-profile-view.mjs";
42
46
  import { lyricTrackKey } from "../../core/lyric-profile.mjs";
47
+ import { matchLibraryNames } from "../../core/library-names.mjs";
48
+ import { draftWithProfileTrack, profileSeedForDraft } from "../../core/profile-discovery-draft.mjs";
43
49
  import { HistoryImportView } from "./history-import-view.mjs";
44
50
  import { FirstRunView, neteaseSetupCommand, playbackServiceChoices, playbackServiceName } from "./first-run-view.mjs";
45
51
  import { IMPORT_GUIDE_URLS } from "./import-guides.mjs";
@@ -105,6 +111,15 @@ class ListeningRoom extends TuiAltScreen {
105
111
  }
106
112
  }
107
113
 
114
+ const serviceControlNotices = {
115
+ skipped: N_("Skipped on {service}."),
116
+ stopped: N_("Stopped playback on {service}."),
117
+ paused: N_("Paused playback on {service}."),
118
+ idle: N_("Nothing is playing on {service}."),
119
+ no_next: N_("No next track on {service}."),
120
+ unavailable: N_("Playback controls are unavailable for {service}."),
121
+ };
122
+
108
123
  const slashCommands = [
109
124
  { name: "update", description: N_("Check for or install a Moondog release") },
110
125
  { name: "home", description: N_("Back to the record sleeve") },
@@ -133,8 +148,8 @@ const slashCommands = [
133
148
  { name: "generation", description: process.platform === "darwin" ? N_("Let Moondog make music on this Mac") : N_("Let Moondog make music on this computer") },
134
149
  { name: "onair", description: N_("Go on air: Moondog keeps making music from your taste") },
135
150
  { name: "spotify", description: N_("Connect and control Spotify") },
136
- { name: "skip", description: N_("Skip to the next song preview or stream track") },
137
- { name: "stop", description: N_("Stop the song previews or the stream") },
151
+ { name: "skip", description: N_("Skip to the next track") },
152
+ { name: "stop", description: N_("Stop playback or pause Spotify") },
138
153
  { name: "reload", description: N_("Reload model settings and sign-ins") },
139
154
  { name: "remember", description: N_("Ask Moondog to remember something") },
140
155
  { name: "forget", description: N_("Forget one memory by ID") },
@@ -184,14 +199,13 @@ export function parseTuiArguments(text) {
184
199
  return values;
185
200
  }
186
201
 
187
- function offlineReply(runtimeStatus, tr) {
188
- const provider = runtimeStatus.provider ?? "openai";
189
- const [why, next] = runtimeStatus.reason === "provider_authentication_required"
190
- ? [tr("you're not signed in to {provider}", { provider }), tr("Sign in with `/auth {provider}`.", { provider })]
191
- : runtimeStatus.reason === "model_not_configured" || !runtimeStatus.reason
192
- ? [tr("no model is connected"), tr("Type `/model` to pick one.")]
193
- : [tr("I can't reach the model (`{reason}`)", { reason: runtimeStatus.reason }), tr("Type `/model` to pick another, or `/reload` to try again.")];
194
- return tr("Obscured by clouds. I can't talk yet because {why}.\n\n{next}\n\nYour profile doesn't need a model. `/taste`, `/import`, and `/help` all work right now.", { why, next });
202
+ function offlineDraftHint(status, tr) {
203
+ if (status.reason === "provider_authentication_required") return tr("Sign in with `/auth {provider}`.", { provider: status.provider ?? "openai" }).replaceAll("`", "");
204
+ if (status.reason && status.reason !== "model_not_configured") {
205
+ const reason = tr("I can't reach the model (`{reason}`)", { reason: status.reason });
206
+ return `${reason}. ${tr("Type `/model` to pick another, or `/reload` to try again.")}`.replaceAll("`", "");
207
+ }
208
+ return tr("Your request is still here. Press Ctrl+P, then choose /model.");
195
209
  }
196
210
 
197
211
  function elapsedTime(startedAt) {
@@ -250,13 +264,17 @@ export async function runMoondogTui({
250
264
  }
251
265
  // Screen text follows the listener's language and switches with /language.
252
266
  const tr = liveScreenTranslator(() => application.locale);
267
+ // Import text follows the screen's language, so one screen is never two; Traditional Chinese keeps its own script.
268
+ const importLocale = () => application.locale === "zh-Hant" ? "zh-Hant" : tr.locale;
253
269
  setBrandText(tr);
254
- // /skip and /stop exist only where the room controls the previews itself.
270
+ // A terminal can control the selected music service even without a local preview player.
255
271
  const previewControls = typeof previewPlayer?.subscribe === "function" &&
256
272
  typeof previewPlayer.skip === "function" && typeof previewPlayer.stop === "function";
273
+ const selectedControls = typeof application.controlSelectedPlayback === "function";
274
+ const transportControls = previewControls || selectedControls;
257
275
  // /onair needs both: the room's own player and music making here.
258
276
  const onAirControls = previewControls && typeof generation?.save === "function";
259
- const commands = slashCommands.filter(({ name }) => (previewControls || !["skip", "stop"].includes(name)) &&
277
+ const commands = slashCommands.filter(({ name }) => (transportControls || !["skip", "stop"].includes(name)) &&
260
278
  (name !== "generation" || typeof generation?.save === "function") && (name !== "onair" || onAirControls) &&
261
279
  (name !== "library" || application.libraryReady?.() === true));
262
280
  const localizedCommands = commands.map(({ name, description }) => ({ name, get description() { return tr.marked(description); } }));
@@ -308,18 +326,21 @@ export async function runMoondogTui({
308
326
  let importPage = "start";
309
327
  let importReturnHome = false;
310
328
  let preparedImport = null;
329
+ let importReadController = null;
330
+ let importSave = null;
311
331
  let importNeedsRefresh = false;
312
332
  let importOrigin = "file";
313
333
  let importProvider = null;
314
334
  let importFileReturn = "start";
315
335
  let importAuthController = null;
316
336
  // Reading Last.fm can take minutes, so Esc can stop it; the access state says whether a key is set.
317
- let lastfmController = null;
318
337
  let lastfmAccess = null;
319
338
  let profileReturnHome = false;
320
339
  let profileSnapshot = null;
321
340
  let profileNeedsRefresh = false;
322
341
  let profileDiscoveryDraft = null;
342
+ let savedPending = { draft: "", queued: [] };
343
+ let libraryLocation = null;
323
344
  let homeFocused = false;
324
345
  let homeSelected = 0;
325
346
  let busy = false;
@@ -375,11 +396,14 @@ export async function runMoondogTui({
375
396
  const updateCheckController = new AbortController();
376
397
  let footerColor = dim;
377
398
  let localCommandController = null;
399
+ let profileBuildStarted = false;
378
400
  let startAttempted = false;
379
401
  let cleanedUp = false;
380
402
  let resolveStopped;
381
403
  const stoppedPromise = new Promise((resolve) => { resolveStopped = resolve; });
382
- const editor = new ListeningEditor(tui, editorTheme, getTheme, () => ({ busy, homeVisible, homeFocused }));
404
+ const editor = new ListeningEditor(tui, editorTheme, getTheme, () => ({ busy, homeVisible, homeFocused, libraryLabel: libraryLocation?.label }));
405
+ let composingDraft = false;
406
+ editor.onChange = (text) => { composingDraft = Boolean(text); };
383
407
  const recallBySession = new Map();
384
408
  const sessionId = () => application.ensureMemorySession?.()?.session_id ?? null;
385
409
  const storeRecall = () => {
@@ -586,7 +610,7 @@ export async function runMoondogTui({
586
610
  }
587
611
  // Without room for the keys line, the first run's status says how to choose and skip.
588
612
  if (firstRunView && !busy && terminal.rows < 20) statusText = tr("↑↓ ↵ choose · esc skip setup");
589
- if (busy && !profileView && !importView && !(firstRunView && tui.hasOverlay()) && width >= 20) {
613
+ if (busy && !profileView && !importView && !tui.hasOverlay() && width >= 20) {
590
614
  const elapsed = ` · ${elapsedTime(workStartedAt)}`;
591
615
  statusText = truncateToWidth(statusText, width - 3 - visibleWidth(elapsed)) + elapsed;
592
616
  }
@@ -607,6 +631,7 @@ export async function runMoondogTui({
607
631
  : profileView
608
632
  ? busy ? tr("One moment...")
609
633
  : width >= 76 ? tr("type filter · ↑↓ select · enter actions · tab views · esc back") : tr("↑↓ select · enter actions · tab views · esc back")
634
+ : tui.hasOverlay() ? tr("Enter chooses · Esc back")
610
635
  : busy ? cancellationRequested
611
636
  ? messageQueue.length ? tr("stopping · the queue waits") : tr("stopping")
612
637
  : messageQueue.length
@@ -618,9 +643,9 @@ export async function runMoondogTui({
618
643
  : tr("enter queues the next one · waiting for command")
619
644
  : editor.isShowingAutocomplete() ? tr("↑↓ choose · tab/enter complete · esc dismiss") : homeFocused
620
645
  ? tr("↑ ↓ choose · enter open · esc type")
646
+ : queuePaused && messageQueue.length ? tr("queued drafts paused · up edits the last")
621
647
  : homeVisible && !editor.getText()
622
648
  ? width >= 60 ? tr("tab explore · ctrl+p commands enter send · shift+enter newline") : tr("tab explore · ctrl+p commands")
623
- : queuePaused && messageQueue.length ? tr("queued drafts paused · up edits the last")
624
649
  : width >= 72 ? tr("enter send · shift+enter newline · alt+r rewind") : tr("enter send · /rewind");
625
650
  lines.push(paintBrandLine(` ${theme.faint(keys)}`, width, theme));
626
651
  }
@@ -724,8 +749,9 @@ export async function runMoondogTui({
724
749
  // Each preview sits next to its song on Apple Music. The note joins the reply in progress;
725
750
  // terminals that support it show each link as clickable "Apple Music" text.
726
751
  // A song that fails to load is marked in the note, so silence is never left unexplained.
727
- let previewNote = null;
728
- const previewNoteText = ({ tracks, album, failed }) => {
752
+ let previewNotes = [];
753
+ const playbackFailureLabel = reason => reason === "decoder" ? tr("couldn't play") : tr("couldn't load");
754
+ const previewNoteText = ({ tracks, album, failed, firstPosition }) => {
729
755
  const link = (url) => `[Apple Music](${String(url).replaceAll("(", "%28").replaceAll(")", "%29")})`;
730
756
  const lines = [`${theme.plain ? "" : "♪ "}${tr("30-second previews from Apple Music")}`];
731
757
  if (album?.title) {
@@ -734,27 +760,39 @@ export async function runMoondogTui({
734
760
  }
735
761
  lines.push("", ...tracks.map((track, index) => {
736
762
  const artist = track.artist_credit && track.artist_credit !== album?.artist_credit ? ` - ${safeInlineText(track.artist_credit)}` : "";
737
- return `${index + 1}. ${safeInlineText(track.title)}${artist} · ${link(track.catalog_url)}${failed.has(index) ? ` · _${tr("couldn't load")}_` : ""}`;
763
+ const cause = failed.get(index);
764
+ return `${firstPosition + index}. ${safeInlineText(track.title)}${artist} · ${link(track.catalog_url)}${cause ? ` · _${playbackFailureLabel(cause)}_` : ""}`;
738
765
  }));
739
- if (tracks.length && failed.size === tracks.length) lines.push("", `_${tr("None of these previews could load. Check your connection, then ask again.")}_`);
766
+ if (tracks.length && failed.size === tracks.length) lines.push("", `_${[...failed.values()].every(cause => cause === "download")
767
+ ? tr("None of these previews could load. Check your connection, then ask again.") : tr("No tracks in this batch could play.")}_`);
740
768
  return sanitizeTerminalText(lines.join("\n"));
741
769
  };
742
- const addPreviewNote = ({ tracks = [], album = null } = {}) => {
743
- previewNote = { tracks, album, failed: new Set() };
770
+ const addPreviewNote = ({ tracks = [], album = null, firstPosition = 1 } = {}) => {
771
+ const previewNote = { tracks, album, firstPosition, failed: new Map() };
772
+ previewNotes.push(previewNote);
744
773
  previewNote.markdown = new Markdown(previewNoteText(previewNote), 1, 1, markdownTheme, textStyle);
745
774
  transcript.addChild(previewNote.markdown);
746
775
  tui.requestRender();
747
776
  };
748
- const markPreviewFailed = ({ position } = {}) => {
749
- if (!previewNote || !Number.isInteger(position) || position < 1 || position > previewNote.tracks.length) return;
750
- previewNote.failed.add(position - 1);
777
+ const markPreviewFailed = ({ position, track, reason = "download" } = {}) => {
778
+ const previewNote = previewNotes.find(note => position >= note.firstPosition && position < note.firstPosition + note.tracks.length);
779
+ if (!previewNote || !transcript.children.includes(previewNote.markdown)) {
780
+ if (track?.title) transcript.addChild(new Text(sanitizeTerminalText(`${track.title} · ${playbackFailureLabel(reason)}`), 1, 1));
781
+ return;
782
+ }
783
+ previewNote.failed.set(position - previewNote.firstPosition, reason);
751
784
  previewNote.markdown.setText(previewNoteText(previewNote));
752
785
  };
753
786
  const stopWatchingPreviews = previewControls ? previewPlayer.subscribe((event) => {
754
787
  if (cleanedUp) return;
755
788
  // A track Moondog made needs no preview note: the reply names it, and the host's line says where it was made.
756
- if (event?.type === "queue") { if (!event.tracks?.some((track) => track.generated)) addPreviewNote(event); }
757
- else if (event?.type === "failed") markPreviewFailed(event);
789
+ if (event?.type === "queue" || event?.type === "append") {
790
+ if (event.type === "queue") previewNotes = [];
791
+ if (event.tracks?.length && !event.tracks.some(track => track.generated)) addPreviewNote(event);
792
+ } else if (event?.type === "failed") {
793
+ if (nowPlaying?.position === event.position) nowPlaying = null;
794
+ markPreviewFailed(event);
795
+ }
758
796
  else if (["loading", "playing", "paused"].includes(event?.type)) nowPlaying = event;
759
797
  else if (event?.type === "stopped") nowPlaying = null;
760
798
  tui.requestRender();
@@ -767,18 +805,44 @@ export async function runMoondogTui({
767
805
  if (ended === "failed") setFooter(tr("Off air: the next record couldn't be made."), failure);
768
806
  tui.requestRender();
769
807
  }) ?? null;
770
- // These act at once, even while Moondog is answering.
771
- const controlPreviews = (command) => {
772
- // /stop also ends Moondog's stream while its next track is still being made and nothing plays.
808
+ const transportController = new AbortController();
809
+ let remoteControls = Promise.resolve();
810
+ let latestControl = 0;
811
+ const controlPlayback = (command) => {
812
+ const request = ++latestControl;
813
+ const stream = application.streamView?.() ?? onAir;
814
+ const isSong = nowPlaying?.track?.generated || previewPlayer?.wholeSongs?.() === true;
815
+ // Cancel a pending Apple lookup before stopping the local player, including while a reply is running.
816
+ const pendingStopped = command === "stop" && application.cancelPendingMusicPreviews?.() === true;
773
817
  const streamStopped = command === "stop" && application.stopStream?.()?.state === "stopped";
774
- const acted = command === "stop" ? previewPlayer.stop() || streamStopped : previewPlayer.skip();
775
- const waiting = !acted && command === "skip" && application.streamView?.()?.phase === "waiting";
776
- // Off air shows even during a reply: a stream stopped while its first track is made has no row to lose.
777
- if (!busy || streamStopped) {
778
- setFooter(waiting ? tr("The next record is still being cut.") : !acted ? tr("No previews are playing.")
779
- : streamStopped ? tr("Off air.") : command === "stop" ? tr("Previews stopped.") : tr("Skipped."));
780
- }
781
- tui.requestRender();
818
+ const acted = previewControls && previewPlayer[command]();
819
+ if (streamStopped) return setFooter(tr("Off air."));
820
+ if (acted || pendingStopped) return setFooter(command === "skip" ? tr("Skipped.")
821
+ : isSong ? tr("Playback stopped.") : tr("Previews stopped."));
822
+ if (stream) return setFooter(stream.phase === "starting" ? tr("The first record is still being cut.") : tr("The next record is still being cut."));
823
+ if (!selectedControls) return setFooter(tr("No previews are playing."));
824
+
825
+ // Preserve the order of service writes. A later local command can still act immediately.
826
+ const intendedService = application.playbackService;
827
+ remoteControls = remoteControls.then(async () => {
828
+ if (cleanedUp) return;
829
+ if (application.playbackService !== intendedService) {
830
+ if (request === latestControl) setFooter(tr("The playback service changed. Try again."), warning);
831
+ return;
832
+ }
833
+ try {
834
+ const result = await application.controlSelectedPlayback(command, { signal: transportController.signal });
835
+ if (request !== latestControl || cleanedUp) return;
836
+ const selected = result.service ?? application.playbackService;
837
+ if (result.state === "idle" && selected === "apple_music" && previewControls && previewPlayer.wholeSongs?.() !== true) {
838
+ return setFooter(tr("No previews are playing."));
839
+ }
840
+ const service = ["spotify", "netease", "apple_music"].includes(selected) ? playbackServiceName(selected, tr) : selected;
841
+ setFooter(tr.marked(serviceControlNotices[result.state] ?? serviceControlNotices.unavailable, { service }));
842
+ } catch (error) {
843
+ if (request === latestControl && !cleanedUp) setFooter(tr("That didn't work: {error}", { error: error?.message ?? String(error) }), warning);
844
+ }
845
+ });
782
846
  };
783
847
  // /onair goes off air at once while a stream runs, even while Moondog is answering, and says so
784
848
  // when music making is off. Otherwise it returns the request to send, in the reply's language.
@@ -1074,6 +1138,145 @@ export async function runMoondogTui({
1074
1138
  generationFooter(status);
1075
1139
  };
1076
1140
 
1141
+ const playlistServices = { spotify: "Spotify", apple_music: "Apple Music", netease: "NetEase Music", qq_music: "QQ Music" };
1142
+ const libraryPlaylistChoices = (folders, playlists) => {
1143
+ const folderById = new Map(folders.map((folder) => [folder.id, folder]));
1144
+ const locations = new Set();
1145
+ const duplicates = new Set();
1146
+ const items = playlists.map((playlist) => {
1147
+ const path = [];
1148
+ for (let folder = folderById.get(playlist.folderId); folder; folder = folderById.get(folder.parentId)) path.unshift(folder.name);
1149
+ const folder = path.join(" / ");
1150
+ const label = playlist.saved ? tr("Saved") : playlist.name;
1151
+ const service = playlistServices[playlist.origin];
1152
+ const location = JSON.stringify([label.toLowerCase(), folder.toLowerCase(), service]);
1153
+ if (locations.has(location)) duplicates.add(location);
1154
+ locations.add(location);
1155
+ return { value: playlist.id, label, folder, service, location, count: playlist.count };
1156
+ });
1157
+ return items.map(({ value, label, folder, service, location, count }) => ({
1158
+ value, label, folder, description: [duplicates.has(location) && value, folder, service, tr.n(count, "{count} song", "{count} songs")].filter(Boolean).join(" · "),
1159
+ }));
1160
+ };
1161
+ const currentPlaylistChoice = (choices) => libraryLocation?.session === sessionId()
1162
+ ? choices.find((choice) => choice.value === libraryLocation.ref) : undefined;
1163
+ const browseLibrary = async (group, query) => {
1164
+ const title = group === "albums" ? tr("Browse albums") : group === "artists" ? tr("Browse artists") : tr("Browse playlists");
1165
+ const songCount = (count) => tr.n(count, "{count} song", "{count} songs");
1166
+ let playlists;
1167
+ if (group === "playlists") {
1168
+ const tree = application.libraryView();
1169
+ const matches = matchLibraryNames(query);
1170
+ playlists = libraryPlaylistChoices(tree.folders, tree.playlists).filter((item) => matches(item.label, item.folder));
1171
+ }
1172
+ let offset = 0;
1173
+ for (;;) {
1174
+ const page = playlists ? { playlists: playlists.slice(offset, offset + 20), total: playlists.length }
1175
+ : application.findLibraryShelves(group, query, offset);
1176
+ const items = playlists ? page.playlists : page[group].map((item) => ({
1177
+ value: item.id, label: item.name, description: [item.artist, songCount(item.count)].filter(Boolean).join(" · "),
1178
+ }));
1179
+ if (!items.length) { setFooter(tr("No matching library items. Save songs or try a different search.")); return; }
1180
+ const end = offset + items.length;
1181
+ if (end < page.total) items.push({ value: "next-page", label: tr("Next page"), offset: end });
1182
+ if (offset) items.push({ value: "previous-page", label: tr("Previous page"), offset: Math.max(0, offset - 20) });
1183
+ const selected = await choose(items, undefined, page.total > 20 ? `${title} · ${offset + 1}–${end}/${page.total}` : title);
1184
+ if (!selected || cleanedUp) { setFooter(tr("Ready.")); return; }
1185
+ if (selected.offset !== undefined) { offset = selected.offset; continue; }
1186
+ const open = await application.libraryPlaylist(selected.value);
1187
+ if (!open) { setFooter(tr("Nothing matches that.")); return; }
1188
+ const label = open.saved ? tr("Saved") : [open.name, open.artist].filter(Boolean).join(" · ");
1189
+ libraryLocation = { ref: open.id, label, session: sessionId() };
1190
+ const shown = open.entries.slice(0, 20);
1191
+ const lines = shown.map((entry) => `- ${safeInlineText(entry.title)} · ${entry.kind === "made" ? tr("Made by Moondog") : safeInlineText(entry.artist_credit)}`);
1192
+ const count = shown.length < open.entries.length ? `${shown.length}/${songCount(open.entries.length)}` : songCount(open.entries.length);
1193
+ addMoondogMessage([`**${safeInlineText(label)}** · ${count}`, ...lines].join("\n"));
1194
+ setFooter(tr("Ask about this music · /library close to leave."));
1195
+ return;
1196
+ }
1197
+ };
1198
+
1199
+ const refreshLinkedPlaylist = async (query) => {
1200
+ const { folders, playlists } = application.libraryView();
1201
+ const matchesName = matchLibraryNames(query);
1202
+ const matches = playlists.filter((playlist) => playlist.linked && matchesName(playlist.name));
1203
+ if (!matches.length) {
1204
+ addMoondogMessage(tr("No linked playlist matches. Use `/library import <link>` to keep a copy."));
1205
+ setFooter(tr("Ready."));
1206
+ return;
1207
+ }
1208
+ const choices = libraryPlaylistChoices(folders, matches);
1209
+ const title = tr("Choose a linked playlist");
1210
+ setFooter(title);
1211
+ const current = query ? undefined : currentPlaylistChoice(choices);
1212
+ const selected = current ?? (query && choices.length === 1 ? choices[0] : await choose(choices, undefined, title));
1213
+ if (!selected || cleanedUp) { setFooter(tr("Cancelled.")); return; }
1214
+ setFooter(tr("Reading the playlist…"));
1215
+ const preview = await application.previewPlaylistRefresh({ playlistId: selected.value }, { signal: localCommandController?.signal });
1216
+ if (cleanedUp) return;
1217
+ localCommandController?.signal.throwIfAborted();
1218
+ const name = safeInlineText(preview.playlist.name);
1219
+ const source = playlistServices[preview.provider] ?? preview.provider;
1220
+ const summary = tr("Add {added} · remove {removed}", { added: tr.number(preview.added), removed: tr.number(preview.removed) });
1221
+ const order = preview.reordered ? tr("Existing songs will change order.") : tr("Existing songs will keep their order.");
1222
+ const detailsOnly = preview.changed && !preview.added && !preview.removed && !preview.reordered;
1223
+ const scope = Number.isFinite(preview.total)
1224
+ ? tr("{service} returned {read} of {songs}.", { service: source, read: tr.number(preview.read), songs: tr.n(preview.total, "{count} song", "{count} songs") })
1225
+ : tr("{service} returned {songs} without a total.", { service: source, songs: tr.n(preview.read, "{count} song", "{count} songs") });
1226
+ const method = preview.partial
1227
+ ? tr("The source is incomplete. Only new songs will be added. Your current songs, their order, and tracks Moondog made stay.")
1228
+ : tr("The source sets its songs in this copy. Songs you added here and tracks Moondog made stay.");
1229
+ if (!preview.changed) {
1230
+ addMoondogMessage([`**${name}**`, scope, ...(preview.partial ? [method] : []), tr("No changes to apply.")].join("\n\n"));
1231
+ setFooter(tr("No changes to apply."));
1232
+ return;
1233
+ }
1234
+ setFooter(tr("Review playlist changes"));
1235
+ const confirm = await choose([
1236
+ { value: "cancel", label: tr("Keep current copy") }, { value: "apply", label: tr("Apply refresh") },
1237
+ ], "cancel", tr("Review playlist changes"), [preview.playlist.name, scope, summary, order,
1238
+ ...(detailsOnly ? [tr("Song details or playlist artwork will be updated.")] : []), method]);
1239
+ if (confirm?.value !== "apply" || cleanedUp) { setFooter(tr("Cancelled.")); return; }
1240
+ localCommandController?.signal.throwIfAborted();
1241
+ const receipt = await application.refreshPlaylistLink({ token: preview.token });
1242
+ if (cleanedUp) return;
1243
+ const updatedName = receipt.playlist?.name ?? preview.playlist.name;
1244
+ addMoondogMessage([tr("Refreshed {name}.", { name: safeInlineText(updatedName) }),
1245
+ tr("Added {added} · removed {removed}.", { added: tr.number(receipt.added), removed: tr.number(receipt.removed) }),
1246
+ ...(detailsOnly ? [tr("Updated song details or playlist artwork.")] : []),
1247
+ ...(receipt.reordered ? [tr("Existing songs were reordered.")] : [])].join(" "));
1248
+ setFooter(tr("Refreshed {name}.", { name: updatedName }), success);
1249
+ };
1250
+
1251
+ const exportLibraryFiles = async (destination) => {
1252
+ let folder = destination;
1253
+ if (/^["']/u.test(folder)) {
1254
+ const parts = parseTuiArguments(folder);
1255
+ folder = parts.length === 1 ? parts[0] : "";
1256
+ }
1257
+ if (!folder) throw new Error(tr("Use /library export-files <destination folder>."));
1258
+ const fromHome = folder === "~" || folder.startsWith("~/") || folder.startsWith("~" + sep);
1259
+ const directory = resolve(fromHome ? home + folder.slice(1) : folder);
1260
+ const { folders, playlists } = application.libraryView();
1261
+ const choices = libraryPlaylistChoices(folders, playlists);
1262
+ const selected = currentPlaylistChoice(choices) ?? await choose(choices, undefined, tr("Choose a playlist to export"));
1263
+ if (!selected || cleanedUp) { setFooter(tr("Cancelled.")); return; }
1264
+ const signal = localCommandController?.signal;
1265
+ signal?.throwIfAborted();
1266
+ setFooter(tr("Writing playlist files…"));
1267
+ const result = await application.exportLibraryFiles({ playlistId: selected.value, directory, savedName: tr("Saved") }, { signal });
1268
+ if (cleanedUp) return;
1269
+ const receipt = tr("Exported {name}.", { name: safeInlineText(selected.label) });
1270
+ const counts = tr("Entries {entries} · songs with links {linked} · made tracks with audio {copied}", {
1271
+ entries: tr.number(result.entries), linked: tr.number(result.catalogLinked), copied: tr.number(result.madeCopied),
1272
+ });
1273
+ const unavailable = result.missingAudio || result.unlinkedSongs ? tr("Missing audio {missing} · songs without links {unlinked}", {
1274
+ missing: tr.number(result.missingAudio), unlinked: tr.number(result.unlinkedSongs),
1275
+ }) : "";
1276
+ addMoondogMessage([receipt, new Text(sanitizeTerminalText(result.directory), 1, 0), [counts, unavailable].filter(Boolean).join("\n\n")]);
1277
+ setFooter(tr("Ready."), success);
1278
+ };
1279
+
1077
1280
  // /library lists Saved and the listener's folders and playlists, plays one by name, or keeps the song
1078
1281
  // playing now, in Saved or in a playlist by name (made when there is none). The window shares this library.
1079
1282
  const manageLibrary = async (args) => {
@@ -1081,6 +1284,15 @@ export async function runMoondogTui({
1081
1284
  const [action, ...rest] = args;
1082
1285
  const words = rest.join(" ").trim();
1083
1286
  const nameOf = (playlist) => (playlist.saved ? tr("Saved") : playlist.name);
1287
+ const mixHelp = tr("Use `/library play-mix <name>` to play a playlist once with Apple Music previews and full-length Moondog tracks.");
1288
+ if (["albums", "artists", "playlists"].includes(action)) return browseLibrary(action, words);
1289
+ if (action === "close" && !words) {
1290
+ libraryLocation = null;
1291
+ setFooter(tr("Ready."));
1292
+ return;
1293
+ }
1294
+ if (action === "refresh") return refreshLinkedPlaylist(words);
1295
+ if (action === "export-files") return exportLibraryFiles(rest[0] ?? "");
1084
1296
  if (!action) {
1085
1297
  const { folders, playlists } = application.libraryView();
1086
1298
  const count = (playlist) => tr.n(playlist.count, "{count} song", "{count} songs");
@@ -1098,20 +1310,50 @@ export async function runMoondogTui({
1098
1310
  }
1099
1311
  };
1100
1312
  walk(null, 0);
1101
- addMoondogMessage(`${lines.join("\n")}\n\n${tr("Play one with `/library play <name>`, or keep the song playing now with `/library save`.")}`);
1313
+ lines.push("", tr("Type `/library ` and press Tab for more."));
1314
+ addMoondogMessage(lines.join("\n"));
1102
1315
  return;
1103
1316
  }
1104
- if (action === "play") {
1105
- const [playlist] = application.findLibraryPlaylists(words);
1317
+ if (action === "play" || action === "play-mix") {
1318
+ const mix = action === "play-mix";
1319
+ if (mix && !words) throw new Error(mixHelp);
1320
+ let playlist;
1321
+ if (mix) {
1322
+ const { folders, playlists } = application.libraryView();
1323
+ const matches = matchLibraryNames(words);
1324
+ const found = playlists.filter(item => matches(item.name, nameOf(item)));
1325
+ [playlist] = found;
1326
+ if (found.length > 1) {
1327
+ const title = tr("Choose a playlist to play");
1328
+ setFooter(title);
1329
+ const selected = await choose(libraryPlaylistChoices(folders, found), undefined, title);
1330
+ if (!selected || cleanedUp) { setFooter(tr("Cancelled.")); return; }
1331
+ playlist = found.find(item => item.id === selected.value);
1332
+ }
1333
+ } else {
1334
+ [playlist] = application.findLibraryPlaylists(words);
1335
+ }
1106
1336
  if (!playlist || !words) throw new Error(tr("No playlist is called “{name}”.", { name: words }));
1107
- const played = await application.playLibrary({ playlistId: playlist.id });
1337
+ const played = await application.playLibrary({ playlistId: playlist.id, ...(mix ? { withAppleMusic: true } : {}) });
1338
+ const detail = [];
1339
+ if (played.failed_to_play) detail.push(tr.n(played.failed_to_play, "{count} track couldn't play.", "{count} tracks couldn't play."));
1340
+ if (played.completed) detail.push(tr.n(played.completed, "{count} track finished.", "{count} tracks finished."));
1341
+ if (played.queued) detail.push(tr.n(played.queued, "{count} track is queued.", "{count} tracks are queued."));
1342
+ if (played.not_found && (mix || played.failed_to_play !== undefined)) detail.push(tr.n(played.not_found, "{count} track was unavailable.", "{count} tracks were unavailable."));
1343
+ if (played.remaining_count) detail.push(tr.n(played.remaining_count, "{count} later track is outside this queue.", "{count} later tracks are outside this queue."));
1108
1344
  if (played.state !== "playing") {
1109
- addMoondogMessage(played.state === "empty" ? tr("{name} has nothing in it yet.", { name: nameOf(playlist) }) : tr("None of its songs could be found."));
1345
+ const reason = played.state === "empty" ? tr("{name} has nothing in it yet.", { name: nameOf(playlist) })
1346
+ : played.state === "pending" ? tr("The player hasn't confirmed a start for {name}.", { name: nameOf(playlist) })
1347
+ : played.state === "completed" ? tr("Playback finished.")
1348
+ : mix || played.state === "failed" ? tr("No tracks in this batch could play.") : tr("None of its songs could be found.");
1349
+ if (mix && played.state === "pending") detail.push(tr("Apple Music songs play as 30-second previews. Moondog's tracks play in full."));
1350
+ addMoondogMessage([reason, ...detail].join(" "));
1110
1351
  return;
1111
1352
  }
1112
1353
  addMoondogMessage([tr("Playing {name}.", { name: nameOf(playlist) }),
1113
- played.left_out_made ? tr("Moondog's tracks were left out. They play with Apple Music chosen.") : "",
1114
- played.not_found ? tr("Some songs couldn't be found.") : ""].filter(Boolean).join(" "));
1354
+ mix ? tr("Apple Music songs play as 30-second previews. Moondog's tracks play in full.") : "",
1355
+ played.left_out_made ? tr("Moondog's tracks were left out. Use `/library play-mix <name>` to include them.") : "",
1356
+ !mix && played.not_found && played.failed_to_play === undefined ? tr("Some songs couldn't be found.") : "", ...detail].filter(Boolean).join(" "));
1115
1357
  setFooter(tr("Playing {name}.", { name: nameOf(playlist) }), success);
1116
1358
  return;
1117
1359
  }
@@ -1131,9 +1373,12 @@ export async function runMoondogTui({
1131
1373
  if (!link) throw new Error(tr("Paste a playlist link after /library import."));
1132
1374
  setFooter(tr("Reading the playlist…"));
1133
1375
  const imported = await application.importPlaylistFromLink({ link, ...(choice ? { taste: choice === "taste" } : {}) });
1134
- const counted = imported.total && imported.total > imported.added
1135
- ? tr("{added} of {total} songs came in.", { added: imported.added, total: imported.total })
1136
- : tr.n(imported.added, "{count} song came in.", "{count} songs came in.");
1376
+ let counted;
1377
+ if (imported.partial && (imported.total === null || imported.total === imported.read)) {
1378
+ counted = tr("Partial playlist · {songs} available.", { songs: tr.n(imported.read, "{count} song", "{count} songs") });
1379
+ } else if (imported.total > imported.added) {
1380
+ counted = tr("{added} of {total} songs came in.", { added: imported.added, total: imported.total });
1381
+ } else counted = tr.n(imported.added, "{count} song came in.", "{count} songs came in.");
1137
1382
  const taste = imported.taste === "added" ? tr("It now shapes your taste.")
1138
1383
  : imported.taste === "failed" ? tr("It couldn't shape your taste this time.")
1139
1384
  : tr("It doesn't shape your taste; add taste after the link if it should.");
@@ -1166,7 +1411,7 @@ export async function runMoondogTui({
1166
1411
  setFooter(text, success);
1167
1412
  return;
1168
1413
  }
1169
- throw new Error(tr("Use /library, /library play <name>, /library save [playlist], /library import <link>, or /library export <name>."));
1414
+ throw new Error(tr("Use /library to see the available commands."));
1170
1415
  };
1171
1416
 
1172
1417
  const removeLifecycleListeners = () => {
@@ -1180,7 +1425,7 @@ export async function runMoondogTui({
1180
1425
 
1181
1426
  const cleanup = () => {
1182
1427
  if (cleanedUp) return;
1183
- try { application.conversationPending?.({ draft: editor.getText(), queued: [...messageQueue] }); } catch { /* Terminal cleanup must still run when storage is unavailable. */ }
1428
+ try { savePendingConversation(); } catch { /* Terminal cleanup must still run when storage is unavailable. */ }
1184
1429
  cleanedUp = true;
1185
1430
  clearTimeout(watchTimer);
1186
1431
  stopWatchingModel?.();
@@ -1194,12 +1439,14 @@ export async function runMoondogTui({
1194
1439
  clearInterval(homeMotion);
1195
1440
  homeMotion = null;
1196
1441
  localCommandController?.abort();
1442
+ transportController.abort();
1197
1443
  importAuthController?.abort();
1198
- lastfmController?.abort();
1444
+ importReadController?.abort();
1199
1445
  lyricController?.abort();
1200
1446
  updateCheckController.abort();
1201
- preparedImport?.close?.();
1202
- preparedImport = null;
1447
+ const importClosed = importSave
1448
+ ? importSave.catch(() => {}).then(discardPreparedImport)
1449
+ : discardPreparedImport();
1203
1450
  removeLifecycleListeners();
1204
1451
  try {
1205
1452
  if (startAttempted) tui.stop();
@@ -1212,11 +1459,12 @@ export async function runMoondogTui({
1212
1459
  } catch {}
1213
1460
  throw error;
1214
1461
  } finally {
1215
- resolveStopped();
1462
+ resolveStopped(importClosed);
1216
1463
  }
1217
1464
  };
1218
1465
 
1219
- const shutdown = () => {
1466
+ const shutdown = (request) => {
1467
+ exitRequest = request;
1220
1468
  // A reply still running stops with the room, and so does a track it is making.
1221
1469
  try { activeRuntime.abort(); } catch { /* Nothing was running. */ }
1222
1470
  cleanup();
@@ -1256,9 +1504,8 @@ export async function runMoondogTui({
1256
1504
  signalTarget.once("SIGHUP", handleSighup);
1257
1505
  signalTarget.once("uncaughtExceptionMonitor", handleUncaughtFailure);
1258
1506
 
1259
- const choose = async (items, currentValue, title) => {
1507
+ const choose = async (items, currentValue, title, paragraphs) => {
1260
1508
  if (items.length === 0) return undefined;
1261
- const menu = new ListeningMenu({ items, currentValue, title, getTheme, getText: () => tr, getRows: () => terminal.rows });
1262
1509
  return await new Promise((resolve) => {
1263
1510
  let overlay;
1264
1511
  const finish = (value) => {
@@ -1270,14 +1517,22 @@ export async function runMoondogTui({
1270
1517
  tui.requestRender();
1271
1518
  resolve(value);
1272
1519
  };
1273
- menu.onSelect = (item) => finish(item);
1274
- menu.onCancel = () => finish(undefined);
1275
- overlay = tui.showOverlay(menu, {
1276
- width: "86%",
1277
- maxHeight: "100%",
1278
- anchor: "center",
1279
- margin: 1,
1280
- });
1520
+ let menu;
1521
+ if (paragraphs) {
1522
+ menu = new HistoryImportView({
1523
+ tui, getTheme, getText: () => tr, getRows: () => Math.max(1, terminal.rows - 2 - (terminal.rows >= 20 ? 2 : 1)),
1524
+ onAction: ({ type }) => finish(items.find((item) => item.value === type)),
1525
+ });
1526
+ menu.setState({ page: "reviewChoice", review: { title, paragraphs, actions: items.map((item) => ({ type: item.value, label: item.label })) } });
1527
+ menu.selected = Math.max(0, items.findIndex((item) => item.value === currentValue));
1528
+ } else {
1529
+ menu = new ListeningMenu({ items, currentValue, title, getTheme, getText: () => tr, getRows: () => terminal.rows });
1530
+ menu.onSelect = (item) => finish(item);
1531
+ menu.onCancel = () => finish(undefined);
1532
+ }
1533
+ overlay = tui.showOverlay(menu, paragraphs
1534
+ ? { width: "100%", anchor: "top-center", margin: { top: 2 } }
1535
+ : { width: "86%", maxHeight: "100%", anchor: "center", margin: 1 });
1281
1536
  });
1282
1537
  };
1283
1538
 
@@ -1293,7 +1548,7 @@ export async function runMoondogTui({
1293
1548
  };
1294
1549
 
1295
1550
  const refreshProfile = async () => {
1296
- const snapshot = await application.getProfileSummary({ maxItems: 10 });
1551
+ const snapshot = await readTasteReviewProfile(application);
1297
1552
  if (cleanedUp || !profileView) return;
1298
1553
  profileSnapshot = snapshot;
1299
1554
  profileView.setModel(buildTasteProfileModel(snapshot, tr));
@@ -1343,11 +1598,10 @@ export async function runMoondogTui({
1343
1598
  return;
1344
1599
  }
1345
1600
  const target = subject.target;
1346
- const context = `Track: ${JSON.stringify(sanitizeTerminalText(target.label))}\nArtist: ${JSON.stringify(sanitizeTerminalText(target.artistCredit))}`;
1347
- const text = profileDiscoveryDraft && draft.includes(profileDiscoveryDraft.context)
1348
- ? draft.replace(profileDiscoveryDraft.context, () => context)
1349
- : `${draft || tr("Find me 3 songs to go to from here, and tell me why each one.")}\n\n${context}`;
1350
- profileDiscoveryDraft = { context, target: { ...target } };
1601
+ const text = draftWithProfileTrack(draft, profileDiscoveryDraft, target, tr("Find me 3 songs to go to from here, and tell me why each one."));
1602
+ if (!text) return;
1603
+ profileDiscoveryDraft = target;
1604
+ libraryLocation = null;
1351
1605
  editor.setText(text);
1352
1606
  profileReturnHome = false;
1353
1607
  closeProfile();
@@ -1420,7 +1674,7 @@ export async function runMoondogTui({
1420
1674
  addTasteReport(await application.runLocalCommand("taste", runtimeStatus));
1421
1675
  return;
1422
1676
  }
1423
- const snapshot = await application.getProfileSummary({ maxItems: 10 });
1677
+ const snapshot = await readTasteReviewProfile(application);
1424
1678
  if (cleanedUp) return;
1425
1679
  profileSnapshot = snapshot;
1426
1680
  profileNeedsRefresh = false;
@@ -1827,10 +2081,11 @@ export async function runMoondogTui({
1827
2081
  }
1828
2082
  };
1829
2083
 
1830
- const discardPreparedImport = () => {
1831
- preparedImport?.close?.();
2084
+ function discardPreparedImport() {
2085
+ const pending = preparedImport;
1832
2086
  preparedImport = null;
1833
- };
2087
+ return pending?.close?.();
2088
+ }
1834
2089
 
1835
2090
  const setImportPage = (page, details = {}) => {
1836
2091
  importPage = page;
@@ -1848,18 +2103,45 @@ export async function runMoondogTui({
1848
2103
  tui.requestRender(true);
1849
2104
  };
1850
2105
 
2106
+ // A stopped provider read can settle after the listener starts another one.
2107
+ // Release a late preview and let Escape restore the guide immediately.
2108
+ async function waitForImportPreview(reading, signal) {
2109
+ const stopped = Promise.withResolvers();
2110
+ const stop = () => stopped.reject(signal.reason);
2111
+ signal.addEventListener("abort", stop, { once: true });
2112
+ if (signal.aborted) stop();
2113
+ try {
2114
+ return await Promise.race([Promise.resolve(reading).then(async prepared => {
2115
+ if (signal.aborted) {
2116
+ await prepared?.close?.();
2117
+ signal.throwIfAborted();
2118
+ }
2119
+ return prepared;
2120
+ }), stopped.promise]);
2121
+ } finally { signal.removeEventListener("abort", stop); }
2122
+ }
2123
+
1851
2124
  const inspectImport = async (filePath) => {
1852
2125
  discardPreparedImport();
1853
2126
  importOrigin = "file";
1854
2127
  const view = importView;
1855
2128
  view.setPath(filePath);
2129
+ const controller = new AbortController();
2130
+ importReadController = controller;
2131
+ const { signal } = controller;
1856
2132
  setBusy(true);
1857
- setImportPage("working", { message: tr("Reading your file...") });
2133
+ setImportPage("working", { message: tr("Reading your file..."), cancellable: true });
1858
2134
  setFooter(tr("Reading the file. Nothing is added until you say so."));
1859
2135
  try {
1860
2136
  if (typeof prepareImport !== "function") throw new Error(tr("Reading files isn't available when Moondog is started this way."));
1861
- const prepared = await prepareImport(filePath, { provider: importProvider });
1862
- if (cleanedUp || importView !== view) { prepared.close?.(); return; }
2137
+ const onProgress = ({ stage, count, total }) => {
2138
+ if (cleanedUp || importView !== view || signal.aborted) return;
2139
+ const labels = importHistoryStrings(importLocale());
2140
+ if (stage === "comparing") setImportPage("working", { message: labels.comparing, cancellable: true });
2141
+ if (stage === "files" && total) setImportPage("working", { message: `${labels.filesRead} · ${tr.number(count)}/${tr.number(total)}`, cancellable: true });
2142
+ };
2143
+ const prepared = await waitForImportPreview(prepareImport(filePath, { provider: importProvider, signal, onProgress }), signal);
2144
+ if (signal.aborted || cleanedUp || importView !== view) { await prepared.close?.(); return; }
1863
2145
  if (!importProvider) {
1864
2146
  importProvider = prepared.preview.kind === "library" ? "apple" : prepared.provider === "listenbrainz" ? "other" : ["youtube_music", "qq_music", "netease"].includes(prepared.provider) ? prepared.provider : "spotify";
1865
2147
  importFileReturn = { apple: "appleQuick", other: "other", youtube_music: "youtube_music", qq_music: "qq_music", netease: "netease" }[importProvider] ?? "spotifyHistory";
@@ -1868,13 +2150,17 @@ export async function runMoondogTui({
1868
2150
  setImportPage("preview", { preview: prepared.preview });
1869
2151
  setFooter(tr("Here's what's inside. Nothing is added until you import it."), success);
1870
2152
  } catch (error) {
1871
- if (!cleanedUp && importView === view) {
2153
+ if (!cleanedUp && importView === view && !signal.aborted) {
1872
2154
  setImportPage("file", { error: sanitizeTerminalText(error.message) });
1873
2155
  setFooter(tr("Nothing imported. Your path is still there to fix."), warning);
1874
2156
  }
1875
2157
  } finally {
2158
+ if (importReadController === controller) importReadController = null;
1876
2159
  setBusy(false);
1877
- if (!cleanedUp && importView === view) tui.setFocus(view);
2160
+ if (!cleanedUp && importView === view) {
2161
+ if (signal.aborted) { setImportPage("file"); setFooter(tr("Stopped. Nothing imported.")); }
2162
+ tui.setFocus(view);
2163
+ }
1878
2164
  }
1879
2165
  };
1880
2166
 
@@ -1882,10 +2168,13 @@ export async function runMoondogTui({
1882
2168
  discardPreparedImport();
1883
2169
  importOrigin = "quick";
1884
2170
  const view = importView;
2171
+ const controller = new AbortController();
2172
+ importReadController = controller;
1885
2173
  setBusy(true);
1886
- setImportPage("working", { message: tr("Asking Spotify for your library and recent listening...") });
2174
+ setImportPage("working", { message: tr("Asking Spotify for your library and recent listening..."), cancellable: true });
1887
2175
  setFooter(tr("Reading from Spotify. Nothing is added until you say so."));
1888
2176
  const stages = {
2177
+ comparing: () => importHistoryStrings(importLocale()).comparing,
1889
2178
  saved_tracks: count => tr("Reading your Spotify library: {count} saved songs...", { count }),
1890
2179
  saved_albums: count => tr("Reading your Spotify library: {count} saved albums...", { count }),
1891
2180
  followed_artists: count => tr("Reading your Spotify library: {count} followed artists...", { count }),
@@ -1894,13 +2183,13 @@ export async function runMoondogTui({
1894
2183
  top_items: count => tr("Reading your Spotify library: {count} top artists and tracks...", { count }),
1895
2184
  };
1896
2185
  const onProgress = ({ stage, count }) => {
1897
- if (cleanedUp || importView !== view || !stages[stage]) return;
1898
- setImportPage("working", { message: stages[stage](tr.number(count)) });
2186
+ if (cleanedUp || importView !== view || controller.signal.aborted || !stages[stage]) return;
2187
+ setImportPage("working", { message: stages[stage](tr.number(count)), cancellable: true });
1899
2188
  };
1900
2189
  try {
1901
2190
  if (typeof prepareRecentImport !== "function") throw new Error(tr("Recent listening isn't available when Moondog is started this way. A history ZIP still works."));
1902
- const prepared = await prepareRecentImport({ onProgress });
1903
- if (cleanedUp || importView !== view) { prepared.close?.(); return; }
2191
+ const prepared = await waitForImportPreview(prepareRecentImport({ onProgress, signal: controller.signal }), controller.signal);
2192
+ if (cleanedUp || importView !== view || controller.signal.aborted) { await prepared.close?.(); return; }
1904
2193
  if (!prepared.preview.listeningEvents && !prepared.preview.library?.profileEvidence) {
1905
2194
  prepared.close?.();
1906
2195
  setImportPage("empty");
@@ -1912,6 +2201,11 @@ export async function runMoondogTui({
1912
2201
  }
1913
2202
  } catch (error) {
1914
2203
  if (cleanedUp || importView !== view) return;
2204
+ if (controller.signal.aborted) {
2205
+ setImportPage("quick");
2206
+ setFooter(tr("Stopped. Nothing imported."));
2207
+ return;
2208
+ }
1915
2209
  const messages = {
1916
2210
  spotify_action_forbidden: tr("Spotify said no. Make sure this account is listed under User Management in your Spotify app, and that the app owner has Premium. A history ZIP works either way."),
1917
2211
  spotify_scope_insufficient: tr("Spotify needs one more permission. Choose Reconnect Spotify."),
@@ -1922,6 +2216,7 @@ export async function runMoondogTui({
1922
2216
  setImportPage("quick", { error: messages[error.code] ?? sanitizeTerminalText(error.message) });
1923
2217
  setFooter(tr("Nothing imported. Your profile is unchanged."));
1924
2218
  } finally {
2219
+ if (importReadController === controller) importReadController = null;
1925
2220
  setBusy(false);
1926
2221
  if (!cleanedUp && importView === view) tui.setFocus(view);
1927
2222
  }
@@ -1933,12 +2228,16 @@ export async function runMoondogTui({
1933
2228
  importOrigin = "lastfm";
1934
2229
  const view = importView;
1935
2230
  const controller = new AbortController();
1936
- lastfmController = controller;
2231
+ importReadController = controller;
1937
2232
  setBusy(true);
1938
2233
  setImportPage("working", { message: tr("Asking Last.fm for your scrobbles..."), cancellable: true });
1939
2234
  setFooter(tr("Reading from Last.fm. Nothing is added until you say so."));
1940
2235
  const onProgress = ({ stage, count, total }) => {
1941
2236
  if (cleanedUp || importView !== view || controller.signal.aborted) return;
2237
+ if (stage === "comparing") {
2238
+ setImportPage("working", { message: importHistoryStrings(importLocale()).comparing, cancellable: true });
2239
+ return;
2240
+ }
1942
2241
  const message = stage === "loved"
1943
2242
  ? tr("Reading your loved tracks: {count}...", { count: tr.number(count) })
1944
2243
  : total > 0
@@ -1948,8 +2247,8 @@ export async function runMoondogTui({
1948
2247
  };
1949
2248
  try {
1950
2249
  if (typeof prepareImport !== "function") throw new Error(tr("Reading Last.fm isn't available when Moondog is started this way."));
1951
- const prepared = await prepareImport(username, { provider: "lastfm", onProgress, signal: controller.signal });
1952
- if (cleanedUp || importView !== view) { prepared.close?.(); return; }
2250
+ const prepared = await waitForImportPreview(prepareImport(username, { provider: "lastfm", onProgress, signal: controller.signal }), controller.signal);
2251
+ if (cleanedUp || importView !== view || controller.signal.aborted) { await prepared.close?.(); return; }
1953
2252
  preparedImport = prepared;
1954
2253
  setImportPage("preview", { preview: prepared.preview });
1955
2254
  setFooter(tr("Here's what Last.fm has. Nothing is added until you import it."), success);
@@ -1964,7 +2263,7 @@ export async function runMoondogTui({
1964
2263
  setImportPage(access ? "lastfmSetup" : "lastfmUser", { error: sanitizeTerminalText(error.message) });
1965
2264
  setFooter(tr("Nothing imported. Your profile is unchanged."), warning);
1966
2265
  } finally {
1967
- if (lastfmController === controller) lastfmController = null;
2266
+ if (importReadController === controller) importReadController = null;
1968
2267
  setBusy(false);
1969
2268
  if (!cleanedUp && importView === view) tui.setFocus(view);
1970
2269
  }
@@ -2047,43 +2346,21 @@ export async function runMoondogTui({
2047
2346
  setImportPage("working", { message: tr("Adding it to your profile...") });
2048
2347
  setFooter(tr("Saving your history on this machine..."));
2049
2348
  try {
2050
- const receipt = await pending.commit();
2349
+ importSave = (async () => {
2350
+ const receipt = await pending.commit();
2351
+ await discardPreparedImport();
2352
+ return receipt;
2353
+ })();
2354
+ const receipt = await importSave;
2051
2355
  saved = true;
2052
2356
  importNeedsRefresh = receipt;
2053
- discardPreparedImport();
2054
2357
  if (cleanedUp) return;
2055
- const insertedEvents = receipt.inserted_events ?? 0;
2056
- const supersededEvents = receipt.superseded_events ?? 0;
2057
- // Scrobbles that repeat another service's plays are kept but count once.
2058
- const mirroredEvents = receipt.mirrored_events ?? 0;
2059
- const playDelta = receipt.effective_event_delta ?? insertedEvents - supersededEvents;
2060
- const playCountChange = playDelta === 0 ? tr("The profile's play count is unchanged.")
2061
- : playDelta > 0 ? tr.n(playDelta, "The profile has {count} more play.", "The profile has {count} more plays.")
2062
- : tr.n(-playDelta, "The profile has {count} fewer play after reconciling overlaps.", "The profile has {count} fewer plays after reconciling overlaps.");
2063
- const evidence = receipt.inserted_profile_evidence ? preview.library
2064
- ? tr.n(receipt.inserted_profile_evidence, "{count} saved song, album, follow, playlist entry, or Spotify top pick.", "{count} saved songs, albums, follows, playlist entries, and Spotify top picks.")
2065
- : tr.n(receipt.inserted_profile_evidence, "{count} saved song, follow, or playlist entry.", "{count} saved songs, follows, or playlist entries.") : null;
2066
- const counts = preview.kind === "library"
2067
- ? receipt.already_imported ? tr("You've imported this library before, so nothing changed.")
2068
- : tr.n(receipt.library_tracks ?? preview.tracks, "Saved {count} song from your library. A library shows what you keep, not when you played it, so no plays were added.", "Saved {count} songs from your library. A library shows what you keep, not when you played it, so no plays were added.")
2069
- : insertedEvents === 0 && !receipt.inserted_profile_evidence && !supersededEvents && !mirroredEvents
2070
- ? tr("Already up to date. There was nothing new in this one.")
2071
- : [
2072
- ...(insertedEvents || supersededEvents || mirroredEvents || !evidence ? [supersededEvents || mirroredEvents
2073
- ? `${tr.n(insertedEvents, "Saved {count} new listening record.", "Saved {count} new listening records.")} ${playCountChange}`
2074
- : receipt.duplicate_events
2075
- ? tr("{plays}, {duplicates} I already had.", { plays: tr.n(insertedEvents, "{count} new play", "{count} new plays"), duplicates: tr.number(receipt.duplicate_events) })
2076
- : tr.n(insertedEvents, "{count} new play.", "{count} new plays.")] : []),
2077
- ...(evidence ? [insertedEvents || supersededEvents ? tr("Also {items}", { items: evidence }) : evidence] : []),
2078
- ].join(" ");
2079
2358
  // Keep the durable result visible even if refreshing the runtime later fails.
2080
2359
  addMoondogMessage([
2081
2360
  preview.kind === "library" ? tr("## Your Apple Music library is in") : preview.kind === "collection" ? tr("## Your collection is in")
2082
2361
  : preview.library ? tr("## Your Spotify is in") : tr("## Your history is in"),
2083
2362
  [view?.previewSource(preview)[0] ?? preview.sourceLabel, preview.fileName].filter(Boolean).join(" · "),
2084
- counts,
2085
- ...(supersededEvents ? [tr.n(supersededEvents, "Reconciled {count} overlapping record, keeping the more detailed listening evidence.", "Reconciled {count} overlapping records, keeping the more detailed listening evidence.")] : []),
2086
- ...(mirroredEvents ? [tr.n(mirroredEvents, "{count} play was already here from another service, so it counts once.", "{count} plays were already here from another service, so they count once.")] : []),
2363
+ formatImportReceipt(preview, receipt, tr, importLocale()),
2087
2364
  tr("Everything from before is still here, including your choices. `/import` adds another source any time."),
2088
2365
  ].join("\n\n"));
2089
2366
  setImportPage("working", { message: tr("Saved. Reading it...") });
@@ -2111,6 +2388,7 @@ export async function runMoondogTui({
2111
2388
  }
2112
2389
  } finally {
2113
2390
  setBusy(false);
2391
+ importSave = null;
2114
2392
  if (!cleanedUp) tui.setFocus(importView === view ? view : profileView ?? editor);
2115
2393
  }
2116
2394
  };
@@ -2174,7 +2452,7 @@ export async function runMoondogTui({
2174
2452
  importReturnHome = homeVisible;
2175
2453
  homeFocused = false;
2176
2454
  importView = new HistoryImportView({
2177
- tui, getTheme, getText: () => tr,
2455
+ tui, getTheme, getText: () => tr, getLocale: importLocale,
2178
2456
  getRows: () => Math.max(1, terminal.rows - 2 - (terminal.rows >= 20 ? 2 : 1)),
2179
2457
  profileReady: application.profileServicesReady?.() ?? false,
2180
2458
  onAction: (action) => {
@@ -2365,14 +2643,42 @@ export async function runMoondogTui({
2365
2643
  if (!state.service && neteaseState() === "unknown") void application.neteasePlayer.check().then(() => refreshFirstRun(), () => {});
2366
2644
  };
2367
2645
 
2368
- const savePendingConversation = () => application.conversationPending?.({ draft: editor.getText(), queued: [...messageQueue] });
2369
- const restorePendingConversation = () => {
2646
+ // Last writer wins: words edited here replace the saved draft; an untouched editor leaves it as it is.
2647
+ function savePendingConversation(words = editor.getText()) {
2648
+ const profileSeed = profileSeedForDraft(words, profileDiscoveryDraft);
2649
+ const location = words && !words.startsWith("/") && !profileSeed && libraryLocation?.session === sessionId() ? libraryDraftLocation(libraryLocation) : null;
2650
+ const draft = location ? libraryDraftText(words, location) : words;
2651
+ const pending = { draft, queued: [...messageQueue], ...(profileSeed ? { profileSeed } : {}), ...(location ? { libraryLocation: location } : {}) };
2652
+ if (JSON.stringify(pending) === JSON.stringify(savedPending)) return;
2653
+ const { queued, ...draftFields } = pending;
2654
+ const { queued: savedQueue, ...savedDraft } = savedPending;
2655
+ const draftEdited = JSON.stringify(draftFields) !== JSON.stringify(savedDraft);
2656
+ const queueChanged = JSON.stringify(queued) !== JSON.stringify(savedQueue);
2657
+ application.conversationPending?.({ ...(draftEdited ? draftFields : application.conversationPending()), ...(queueChanged ? { queued } : {}) });
2658
+ savedPending = pending;
2659
+ }
2660
+
2661
+ // Leaving saves the draft; a conversation deleted elsewhere can still be left.
2662
+ const saveBeforeLeaving = () => { try { savePendingConversation(); } catch { /* Nothing left to save it in. */ } };
2663
+
2664
+ const restorePendingConversation = ({ rewound = false } = {}) => {
2370
2665
  const pending = application.conversationPending?.();
2666
+ profileDiscoveryDraft = profileSeedForDraft(pending?.draft, pending?.profileSeed);
2667
+ savedPending = pending ?? { draft: "", queued: [] };
2371
2668
  if (!pending) return;
2372
- editor.setText(pending.draft);
2669
+ const location = libraryDraftLocation(pending.libraryLocation);
2670
+ if (location && hasLibraryDraftHeader(pending.draft, location)) {
2671
+ libraryLocation = { ...location, session: sessionId() };
2672
+ editor.setText(pending.draft.slice(location.label.length + 1).replace(/^\n/u, ""));
2673
+ } else {
2674
+ if (pending.draft && !rewound) libraryLocation = null;
2675
+ editor.setText(pending.draft);
2676
+ }
2677
+ // A draft merely mirrored from the store should follow the next conversation until edited here.
2678
+ composingDraft = rewound && Boolean(editor.getText());
2373
2679
  messageQueue.splice(0, messageQueue.length, ...pending.queued);
2374
2680
  queuePaused = pending.queued.length > 0;
2375
- releaseQueue = false;
2681
+ releaseQueue = !queuePaused;
2376
2682
  };
2377
2683
  const rewindConversation = async (args) => {
2378
2684
  if (args.length > 1) throw new Error(tr("Use /rewind or /rewind latest."));
@@ -2390,12 +2696,15 @@ export async function runMoondogTui({
2390
2696
  if (cleanedUp) return;
2391
2697
  if (!selected) { setFooter(tr("Rewind cancelled. Queued drafts stay paused.")); return; }
2392
2698
  storeRecall();
2393
- savePendingConversation();
2699
+ saveBeforeLeaving();
2394
2700
  const rewound = typeof activeRuntime.rewindTo === 'function'
2395
2701
  ? await activeRuntime.rewindTo(selected.value)
2396
2702
  : application.rewindConversation(selected.value);
2397
2703
  if (typeof activeRuntime.rewindTo !== 'function') activeRuntime.restoreSession?.();
2398
2704
  profileDiscoveryDraft = null;
2705
+ const earlier = entries.find((entry) => entry.entry_id === selected.value);
2706
+ libraryLocation = earlier?.library_ref && earlier.user_text.startsWith("@")
2707
+ ? { ref: earlier.library_ref, label: earlier.user_text.split("\n", 1)[0].slice(1), session: rewound.session_id } : null;
2399
2708
  conversationTitle = '';
2400
2709
  transcript.clear();
2401
2710
  homeVisible = false;
@@ -2406,7 +2715,10 @@ export async function runMoondogTui({
2406
2715
  else addMoondogMessage(turn.text);
2407
2716
  }
2408
2717
  installRecall(rewound.session_id, recallFromTurns());
2409
- restorePendingConversation();
2718
+ restorePendingConversation({ rewound: true });
2719
+ if (libraryLocation && editor.getText().split("\n", 1)[0] === `@${libraryLocation.label}`) {
2720
+ editor.setText(editor.getText().slice(libraryLocation.label.length + 1).trimStart());
2721
+ }
2410
2722
  // The watcher draws only what others add, so it must not take the removed messages for another's edit.
2411
2723
  markDrawn();
2412
2724
  addMoondogMessage(tr("Rewound to before this message. Edit it below, then send. Spotify actions and saved preferences from the replaced messages have not been undone."));
@@ -2420,7 +2732,7 @@ export async function runMoondogTui({
2420
2732
  if (typeof application.branchConversation !== 'function') throw new Error(tr("Branching isn't available in this runtime."));
2421
2733
  if (!application.conversationEntries?.({ limit: 1 }).length) { setFooter(tr("Nothing to branch from yet.")); return; }
2422
2734
  storeRecall();
2423
- savePendingConversation();
2735
+ saveBeforeLeaving();
2424
2736
  const branch = application.branchConversation();
2425
2737
  activeRuntime.restoreSession();
2426
2738
  installRecall(branch.session_id, recallFromTurns());
@@ -2469,7 +2781,7 @@ export async function runMoondogTui({
2469
2781
  return;
2470
2782
  }
2471
2783
  storeRecall();
2472
- try { savePendingConversation(); } catch { /* A conversation deleted elsewhere must not keep the listener in it. */ }
2784
+ saveBeforeLeaving();
2473
2785
  conversationTitle = "";
2474
2786
  application.resumeSession(selected.value);
2475
2787
  if (!recallBySession.has(selected.value)) {
@@ -2477,8 +2789,9 @@ export async function runMoondogTui({
2477
2789
  }
2478
2790
  editor.replaceRecall(recallBySession.get(selected.value));
2479
2791
  activeRuntime.restoreSession();
2480
- restorePendingConversation();
2481
2792
  const turns = drawSavedConversation();
2793
+ markDrawn();
2794
+ restorePendingConversation();
2482
2795
  const savedTitle = selected.label ? undefined
2483
2796
  : application.listSavedSessions({ limit: 200 }).find((session) => session.session_id === selected.value)?.title;
2484
2797
  const title = selected.label ?? savedTitle ?? turns.find((turn) => turn.role === "user")?.text ?? tr("Saved conversation");
@@ -2496,7 +2809,7 @@ export async function runMoondogTui({
2496
2809
  localCommandController?.signal.throwIfAborted();
2497
2810
  updateNotice = "";
2498
2811
  addMoondogMessage(result.text);
2499
- if (result.update) { exitRequest = { update: result.update }; shutdown(); }
2812
+ if (result.update) shutdown({ update: result.update });
2500
2813
  else setFooter(tr("Update check finished."));
2501
2814
  return;
2502
2815
  }
@@ -2549,6 +2862,7 @@ export async function runMoondogTui({
2549
2862
  }
2550
2863
  if (command === "home") {
2551
2864
  if (args.length) throw new Error(tr("/home doesn't take anything after it."));
2865
+ libraryLocation = null;
2552
2866
  homeVisible = true;
2553
2867
  homeFocused = false;
2554
2868
  sleeve.invalidate();
@@ -2674,18 +2988,22 @@ export async function runMoondogTui({
2674
2988
  return;
2675
2989
  }
2676
2990
  if (command === "profile" && args.length > 0) {
2991
+ profileBuildStarted = false;
2677
2992
  if (typeof runProfile !== "function") {
2678
2993
  throw new Error(tr("Changing your profile isn't available when Moondog is started this way."));
2679
2994
  }
2680
2995
  addMoondogMessage(await runProfile(args, {
2681
2996
  signal: localCommandController?.signal,
2682
2997
  tr,
2683
- onProgress: progress => setFooter(progress.model_retry
2684
- ? tr("Retrying the model, {attempt} of {max}. Ctrl+C cancels and keeps the saved draft.", { attempt: progress.model_retry.attempt, max: progress.model_retry.maxRetries })
2685
- : progress.phase === "check" ? tr("Checking the draft for contradictions. Ctrl+C keeps the draft.")
2686
- : progress.phase === "revision" ? tr("Fixing what the check found. Ctrl+C keeps the draft.")
2687
- : progress.phase === "complete" ? tr("Saving your listening profile.")
2688
- : tr("Reading your music and writing your profile. Ctrl+C cancels.")),
2998
+ onProgress: progress => {
2999
+ profileBuildStarted = true;
3000
+ setFooter(progress.model_retry
3001
+ ? tr("Retrying the model, {attempt} of {max}. Ctrl+C cancels and keeps the saved draft.", { attempt: progress.model_retry.attempt, max: progress.model_retry.maxRetries })
3002
+ : progress.phase === "check" ? tr("Checking the draft for contradictions. Ctrl+C keeps the draft.")
3003
+ : progress.phase === "revision" ? tr("Fixing what the check found. Ctrl+C keeps the draft.")
3004
+ : progress.phase === "complete" ? tr("Saving your listening profile.")
3005
+ : tr("Reading your music and writing your profile. Ctrl+C cancels."));
3006
+ },
2689
3007
  }));
2690
3008
  void updateHomeLyrics();
2691
3009
  if (["correct", "retract"].includes(args[0])) {
@@ -2752,14 +3070,18 @@ export async function runMoondogTui({
2752
3070
  if (command === "new") {
2753
3071
  if (args.length) throw new Error(tr("/new doesn't take anything after it."));
2754
3072
  storeRecall();
2755
- try { savePendingConversation(); } catch { /* A conversation deleted elsewhere must not keep the listener in it. */ }
3073
+ saveBeforeLeaving();
2756
3074
  application.startNewSession?.("user_new");
3075
+ drawn = { session: sessionId(), ids: new Set() };
3076
+ seenVersion = null;
2757
3077
  editor.setText('');
2758
3078
  messageQueue.splice(0);
2759
3079
  queuePaused = false;
2760
3080
  installRecall(sessionId(), []);
2761
3081
  activeRuntime.reset();
3082
+ savedPending = { draft: "", queued: [] };
2762
3083
  profileDiscoveryDraft = null;
3084
+ libraryLocation = null;
2763
3085
  conversationTitle = "";
2764
3086
  transcript.clear();
2765
3087
  homeVisible = true;
@@ -2768,8 +3090,16 @@ export async function runMoondogTui({
2768
3090
  setFooter(tr("A fresh start. /resume brings back the last one."), success);
2769
3091
  return;
2770
3092
  }
2771
- const result = await application.runLocalCommand(command, runtimeStatus);
2772
- addMoondogMessage(formatLocalResult(command, result, tr));
3093
+ let options;
3094
+ if (command === "sources") {
3095
+ const offset = Number(args[0] ?? 0);
3096
+ if (args.length > 1 || (args.length && !/^\d+$/u.test(args[0])) || !Number.isSafeInteger(offset)) {
3097
+ throw new Error(importHistoryStrings(importLocale()).usage);
3098
+ }
3099
+ options = { offset };
3100
+ }
3101
+ const result = await application.runLocalCommand(command, runtimeStatus, options);
3102
+ addMoondogMessage(formatLocalResult(command, result, tr, { sourcesCommand: "/sources", locale: importLocale() }));
2773
3103
  setFooter(tr("Ready."));
2774
3104
  };
2775
3105
 
@@ -2801,9 +3131,9 @@ export async function runMoondogTui({
2801
3131
  const settleQueue = () => {
2802
3132
  if (busy || cleanedUp || !releaseQueue || messageQueue.length === 0) return;
2803
3133
  const next = messageQueue.shift();
2804
- void editor.onSubmit(next);
3134
+ void editor.onSubmit(next, { fromQueue: true });
2805
3135
  };
2806
- const submitListeningTurn = async (rawValue) => {
3136
+ const submitListeningTurn = async (rawValue, { fromQueue = false } = {}) => {
2807
3137
  const value = sanitizeTerminalText(rawValue).trim();
2808
3138
  if (!value) return;
2809
3139
 
@@ -2814,8 +3144,8 @@ export async function runMoondogTui({
2814
3144
  shutdown();
2815
3145
  return;
2816
3146
  }
2817
- if (previewControls && (command === "skip" || command === "stop")) {
2818
- controlPreviews(command);
3147
+ if (transportControls && (command === "skip" || command === "stop")) {
3148
+ controlPlayback(command);
2819
3149
  return;
2820
3150
  }
2821
3151
  if (!commands.some((entry) => entry.name === command)) {
@@ -2837,12 +3167,13 @@ export async function runMoondogTui({
2837
3167
  try {
2838
3168
  if (!["home", "theme", "art", "motion", "model", "service", "resume", "rewind", "branch", "new", "taste", "profile", "import"].includes(command)) enterConversation();
2839
3169
  if (command !== "auth") editor.addToHistory(value);
2840
- localCommandController = ["web", "lyrics", "model", "update", "profile"].includes(command) ? new AbortController() : null;
3170
+ localCommandController = ["web", "lyrics", "model", "update", "profile"].includes(command) || (command === "library" && ["refresh", "export-files"].includes(args[0])) ? new AbortController() : null;
2841
3171
  const controller = localCommandController;
2842
3172
  setBusy(true, controller ? () => controller.abort() : null);
2843
3173
  setFooter(`/${command}...`);
2844
3174
  const argumentText = value.slice(1).trim().slice(rawCommand.length).trim();
2845
3175
  const parsedArgs = command === "import" ? argumentText ? [argumentText] : []
3176
+ : command === "library" && args[0] === "export-files" ? [args[0], argumentText.slice(args[0].length).trimStart()]
2846
3177
  : ["profile", "spotify", "web", "generation"].includes(command)
2847
3178
  ? parseTuiArguments(argumentText)
2848
3179
  : args;
@@ -2853,7 +3184,12 @@ export async function runMoondogTui({
2853
3184
  const cancelled = localCommandController?.signal.aborted;
2854
3185
  // Ctrl+C during a sign-in is the listener's choice, not a failure.
2855
3186
  const signInCancelled = !cancelled && ["auth_login_cancelled", "spotify_auth_aborted"].includes(error?.code);
2856
- addMoondogMessage(signInCancelled ? tr("Sign-in cancelled.") : cancelled ? command === "web" ? tr("Stopped the lookup.") : command === "model" ? tr("Stopped the catalog check. Model unchanged.") : command === "update" ? tr("Stopped the update check. No update installed.") : command === "profile" ? tr("Stopped the profile build. Saved progress and your previous reading are kept. Use /profile build to continue.") : tr("Stopped the lyric sync.") : tr("That didn't work: {error}", { error: error.message }));
3187
+ if (cancelled && command === "profile" && args[0] === "build" && !profileBuildStarted) {
3188
+ // Connecting to the model does not create a build. Up recalls the original request, including --force.
3189
+ addMoondogMessage(`${tr("Cancelled.")} ${tr("Press ↑ to bring your message back, then Enter to try again.")}`);
3190
+ } else {
3191
+ addMoondogMessage(signInCancelled ? tr("Sign-in cancelled.") : cancelled ? command === "library" ? tr("Cancelled.") : command === "web" ? tr("Stopped the lookup.") : command === "model" ? tr("Stopped the catalog check. Model unchanged.") : command === "update" ? tr("Stopped the update check. No update installed.") : command === "profile" ? tr("Stopped the profile build. Saved progress and your previous reading are kept. Use /profile build to continue.") : tr("Stopped the lyric sync.") : tr("That didn't work: {error}", { error: error.message }));
3192
+ }
2857
3193
  setFooter(cancelled || signInCancelled ? tr("Cancelled.") : tr("/{command} didn't work.", { command }), cancelled || signInCancelled ? dim : failure);
2858
3194
  } finally {
2859
3195
  localCommandController = null;
@@ -2863,23 +3199,43 @@ export async function runMoondogTui({
2863
3199
  return;
2864
3200
  }
2865
3201
 
2866
- const profileSeed = profileDiscoveryDraft && value.includes(profileDiscoveryDraft.context)
2867
- ? profileDiscoveryDraft.target : undefined;
2868
- if (profileSeed && runtimeStatus.state !== "configured") {
3202
+ const profileSeed = profileSeedForDraft(value, profileDiscoveryDraft);
3203
+ const location = libraryLocation && !profileSeed && libraryLocation.session === sessionId() ? libraryLocation : null;
3204
+ // A queued request must not replace newer words the listener is already editing.
3205
+ const holdBack = () => {
2869
3206
  releaseQueue = false;
2870
- editor.setText(rawValue);
2871
- setFooter(tr("Your request is still here · /model connects a model first."), warning);
3207
+ if (fromQueue && editor.getText()) messageQueue.unshift(rawValue);
3208
+ else editor.setText(rawValue);
3209
+ queuePaused = messageQueue.length > 0;
3210
+ };
3211
+ if (location && application.libraryLocationAvailable?.(location.ref) === false) {
3212
+ holdBack();
3213
+ setFooter(`${tr("Nothing matches that.")} · /library close`, warning);
3214
+ return;
3215
+ }
3216
+ try {
3217
+ if (runtimeStatus.state !== "configured") {
3218
+ holdBack();
3219
+ // Up brings the question back after the listener clears the editor for the hinted command.
3220
+ editor.addToHistory(value);
3221
+ savePendingConversation();
3222
+ setFooter(offlineDraftHint(runtimeStatus, tr), warning);
3223
+ return;
3224
+ }
3225
+ // Pi clears the editor before calling onSubmit. Persist an edit to a saved draft so the
3226
+ // journal can consume those exact words when the connected runtime starts this turn.
3227
+ if (!fromQueue && savedPending.draft && !editor.getText()) savePendingConversation(rawValue);
3228
+ } catch (error) {
3229
+ if (!editor.getText()) editor.setText(rawValue);
3230
+ setFooter(tr("Something went wrong: {error}", { error: sanitizeTerminalText(error.message) }), failure);
2872
3231
  return;
2873
3232
  }
2874
3233
  // Retain the binding for history recall, only while its exact metadata is visible.
2875
3234
  if (!profileSeed) profileDiscoveryDraft = null;
3235
+ const said = location ? libraryDraftText(value, location) : value;
2876
3236
  editor.addToHistory(value);
2877
- addUserMessage(value);
3237
+ addUserMessage(said);
2878
3238
  enterConversation();
2879
- if (runtimeStatus.state !== "configured") {
2880
- addMoondogMessage(offlineReply(runtimeStatus, tr));
2881
- return;
2882
- }
2883
3239
 
2884
3240
  setBusy(true, () => activeRuntime.abort());
2885
3241
  // While the model thinks, the host's own line from behind the decks, a new one each time it goes back to thinking.
@@ -2922,7 +3278,8 @@ export async function runMoondogTui({
2922
3278
  // An image path in the message goes with it, as Hermes Agent's terminal does; the words stay.
2923
3279
  const images = await imagesFromText(value);
2924
3280
  if (images.length) setFooter(tr("Looking at the attached images... Ctrl+C cancels."));
2925
- const result = await activeRuntime.prompt(value, {
3281
+ const result = await activeRuntime.prompt(said, {
3282
+ ...(location ? { libraryRef: location.ref } : {}),
2926
3283
  ...(profileSeed ? { profileSeed } : {}),
2927
3284
  ...(images.length ? { images } : {}),
2928
3285
  onTextDelta: (delta) => {
@@ -2988,12 +3345,24 @@ export async function runMoondogTui({
2988
3345
  : tr("Lost the model. ↑ brings your message back.")
2989
3346
  : tr("The model couldn't answer."), failure);
2990
3347
  } finally {
3348
+ // The local reply is already drawn. Other entries still belong to the transcript watcher.
3349
+ if (!cleanedUp) {
3350
+ try {
3351
+ if (activeRuntime.syncedEntryId) drawn.ids.add(activeRuntime.syncedEntryId);
3352
+ else {
3353
+ const entry = application.conversationEntries?.({ limit: 1 })?.at(-1);
3354
+ if (entry?.user_text === said) drawn.ids.add(entry.entry_id);
3355
+ }
3356
+ } catch { /* A missing journal must not leave the terminal busy. */ }
3357
+ }
3358
+ if (savedPending.libraryLocation?.ref === location?.ref && savedPending.draft.trim() === said &&
3359
+ application.conversationPending?.()?.draft === "") savedPending = { draft: "", queued: savedPending.queued };
2991
3360
  if (!cleanedUp && work.calls.length) work.settle(elapsedTime(workStartedAt));
2992
3361
  setBusy(false);
2993
3362
  if (!cleanedUp) tui.requestRender();
2994
3363
  }
2995
3364
  };
2996
- editor.onSubmit = async (rawValue) => {
3365
+ editor.onSubmit = async (rawValue, options) => {
2997
3366
  const pending = sanitizeTerminalText(rawValue).trim();
2998
3367
  if (/^\/rewind(?:\s|$)/u.test(pending)) {
2999
3368
  if (rewindPending) return;
@@ -3016,13 +3385,17 @@ export async function runMoondogTui({
3016
3385
  finally { clearTimeout(timer); rewindPending = false; }
3017
3386
  return;
3018
3387
  }
3388
+ // Enter addresses the conversation on screen. A writer may have appeared since the last poll.
3389
+ if (!busy && !rewindPending && !pending.startsWith("/")) {
3390
+ try { syncShownConversation(); } catch { /* The watcher retries if the store is busy. */ }
3391
+ }
3019
3392
  if (busy || rewindPending) {
3020
3393
  if (pending === "/quit" || pending === "/exit") {
3021
3394
  shutdown();
3022
3395
  return;
3023
3396
  }
3024
- if (previewControls && (pending === "/skip" || pending === "/stop")) {
3025
- controlPreviews(pending.slice(1));
3397
+ if (transportControls && (pending === "/skip" || pending === "/stop")) {
3398
+ controlPlayback(pending.slice(1));
3026
3399
  return;
3027
3400
  }
3028
3401
  // /onair stops a stream at once; the request to go on air waits in the queue like any message.
@@ -3036,13 +3409,11 @@ export async function runMoondogTui({
3036
3409
  return;
3037
3410
  }
3038
3411
  releaseQueue = !queuePaused;
3039
- const submission = submitListeningTurn(rawValue);
3412
+ const submission = submitListeningTurn(rawValue, options);
3040
3413
  activeSubmission = submission;
3041
3414
  try { await submission; }
3042
3415
  finally {
3043
3416
  if (activeSubmission === submission) activeSubmission = null;
3044
- // This turn's messages are on screen already; the watcher draws only what others add.
3045
- if (!cleanedUp) { try { markDrawn(); } catch { /* The next look tries again. */ } }
3046
3417
  if (!busy && !cleanedUp && releaseQueue) settleQueue();
3047
3418
  }
3048
3419
  };
@@ -3053,11 +3424,12 @@ export async function runMoondogTui({
3053
3424
  const LOOK_MS = { idle: 1_000, answering: 300 };
3054
3425
  let seenVersion = null;
3055
3426
  // The conversation on screen and the saved messages it shows.
3056
- let drawn = { session: null, ids: new Set() };
3427
+ let drawn = { session: sessionId(), ids: new Set() };
3057
3428
  const savedEntries = () => application.conversationEntries?.({ limit: 500 }) ?? [];
3058
3429
  const markDrawn = () => {
3059
3430
  const reply = application.replyElsewhere?.() ?? null;
3060
3431
  drawn = { session: sessionId(), ids: new Set(savedEntries().map((entry) => entry.entry_id).filter((id) => id !== reply?.entry_id)) };
3432
+ seenVersion = null;
3061
3433
  };
3062
3434
  const addSavedTurns = (turns) => {
3063
3435
  for (const turn of turns) {
@@ -3067,6 +3439,7 @@ export async function runMoondogTui({
3067
3439
  };
3068
3440
  // Draws the saved conversation. A reply still running elsewhere is left to the watcher, which draws it live.
3069
3441
  const drawSavedConversation = () => {
3442
+ if (libraryLocation && libraryLocation.session !== sessionId()) libraryLocation = null;
3070
3443
  const reply = application.replyElsewhere?.() ?? null;
3071
3444
  const turns = application.currentConversationTurns?.({ limit: 40 }) ?? application.currentSessionTurns({ limit: 40 });
3072
3445
  const last = reply ? turns.findLastIndex((turn) => turn.role === "user") : -1;
@@ -3087,8 +3460,9 @@ export async function runMoondogTui({
3087
3460
  };
3088
3461
  const followElsewhere = () => {
3089
3462
  const id = application.activeConversationId?.();
3090
- if (!id || id === sessionId()) return;
3463
+ if (!id || id === sessionId() || composingDraft || (elsewhere && !queuePaused && messageQueue.length)) return;
3091
3464
  storeRecall();
3465
+ savePendingConversation();
3092
3466
  if (!application.followActiveConversation?.()) return;
3093
3467
  endElsewhere();
3094
3468
  activeRuntime.restoreSession();
@@ -3096,6 +3470,7 @@ export async function runMoondogTui({
3096
3470
  installRecall(now, recallBySession.get(now) ?? recallFromTurns());
3097
3471
  conversationTitle = "";
3098
3472
  drawSavedConversation();
3473
+ restorePendingConversation();
3099
3474
  markDrawn();
3100
3475
  tui.requestRender(true);
3101
3476
  };
@@ -3144,16 +3519,26 @@ export async function runMoondogTui({
3144
3519
  endElsewhere();
3145
3520
  settleQueue();
3146
3521
  };
3147
- const lookElsewhere = () => {
3148
- if (typeof application.memoryStore?.dataVersion !== "function") return null;
3149
- if ((busy && !elsewhere) || rewindPending || tui.hasOverlay() || profileView || importView || firstRunView) return LOOK_MS.idle;
3150
- followElsewhere();
3522
+ const syncShownConversation = () => {
3523
+ const version = application.memoryStore?.dataVersion?.();
3524
+ if (version === undefined) return;
3151
3525
  if (drawn.session !== sessionId()) markDrawn();
3152
- const version = application.memoryStore.dataVersion();
3153
3526
  if (version !== seenVersion || elsewhere) {
3154
3527
  seenVersion = version;
3155
3528
  showElsewhere();
3529
+ // A draft only mirrored here follows the saved one, so a draft sent or cleared in another window leaves this editor too.
3530
+ if (!composingDraft && JSON.stringify(messageQueue) === JSON.stringify(savedPending.queued) &&
3531
+ application.conversationPending?.()?.draft !== savedPending.draft) {
3532
+ restorePendingConversation();
3533
+ tui.requestRender();
3534
+ }
3156
3535
  }
3536
+ };
3537
+ const lookElsewhere = () => {
3538
+ if (typeof application.memoryStore?.dataVersion !== "function") return null;
3539
+ if ((busy && !elsewhere) || rewindPending || tui.hasOverlay() || profileView || importView || firstRunView) return LOOK_MS.idle;
3540
+ followElsewhere();
3541
+ syncShownConversation();
3157
3542
  return elsewhere ? LOOK_MS.answering : LOOK_MS.idle;
3158
3543
  };
3159
3544
  const watchElsewhere = () => {
@@ -3184,7 +3569,9 @@ export async function runMoondogTui({
3184
3569
  if (importView) {
3185
3570
  if (busy) {
3186
3571
  if (importPage === "signin" && (matchesKey(data, "escape") || matchesKey(data, "ctrl+c"))) importAuthController?.abort();
3187
- if (importPage === "working" && (matchesKey(data, "escape") || matchesKey(data, "ctrl+c"))) lastfmController?.abort();
3572
+ if (importPage === "working" && (matchesKey(data, "escape") || matchesKey(data, "ctrl+c"))) {
3573
+ importReadController?.abort();
3574
+ }
3188
3575
  return { consume: true };
3189
3576
  }
3190
3577
  if (matchesKey(data, "ctrl+c")) {