@doitian/dsh-music 0.1.9 → 0.1.10

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.
package/README.md CHANGED
@@ -2,7 +2,7 @@
2
2
 
3
3
  NetEase Cloud Music ([music.163.com](https://music.163.com)) playback and an AI DJ for DeepSeek Harness.
4
4
 
5
- A **Music** entry in the DSH sidebar opens a player: queue, synced lyrics, QR sign-in, NetEase likes, and an AI DJ that keeps the queue stocked. The agent can drive the same player through seven tools.
5
+ A **Music** entry in the DSH sidebar opens a player: queue, song details and synced lyrics, QR sign-in, NetEase likes, and an AI DJ that keeps the queue stocked. The agent can drive the same player through seven tools.
6
6
 
7
7
  Developing the plugin, or curious how it works? See [docs/DESIGN.md](https://github.com/doitian/dsh-music/blob/main/docs/DESIGN.md).
8
8
 
@@ -42,7 +42,9 @@ Music plays in the Harness window, so keep it open. Playback continues while you
42
42
 
43
43
  ## Using the player
44
44
 
45
- On a wide window the player has two columns: what is playing on the left — cover, the song's controls, transport and lyrics — and what comes next on the right — the AI DJ card and the queue. On a narrow one they stack.
45
+ On a wide window the player has two columns: what is playing on the left — cover, the song's controls, transport, and the song's details or lyrics — and what comes next on the right — the AI DJ card and the queue. On a narrow one they stack.
46
+
47
+ **Details and lyrics.** Under the transport controls, **Details** shows what NetEase knows about the song: its album (edition, release date, label), genre, tags, language and tempo, awards, and the films or shows it was featured in. Below them, the DJ's model writes a short introduction to the song and its singer from what NetEase holds. It loads after everything else, so the song starts at once. Click the introduction to see NetEase's own text instead: a review, and introductions to each singer and to the album. Click one of those paragraphs to read all of it. Without a model, NetEase's text shows directly. Switch to **Lyrics** for the synced lines. The player remembers which one you chose.
46
48
 
47
49
  **Quality.** Pick a level under the transport controls: `standard`, `higher`, `exhigh` (320 kbps, the default), `lossless`, `hires`, or the spatial tiers `jymaster`, `dolby`, `sky`, `jyeffect`. If a track doesn't offer the level, playback steps down until something plays, and the caption shows what was actually served.
48
50
 
@@ -53,6 +55,7 @@ On a wide window the player has two columns: what is playing on the left — cov
53
55
  | ♡ (beside the title, or on a queue row) | Like on your NetEase account. Click again to unlike. |
54
56
  | ✕ (beside the title) | Dislike: the track leaves the queue, and the next one plays. Local only; the DJ stops picking it. |
55
57
  | ✕ (queue row) | Remove the track. An unrated track is also recorded as disliked. |
58
+ | Clear (queue header) | Empty the queue except the song playing. Nothing is rated. |
56
59
 
57
60
  **Skips.** Pressing next before 30 s (or before a quarter of a long track) counts as a skip. One skip lowers a track's rank; two remove it from the DJ's picks, and skipped plays count against the artist. A dislike is not also counted as a skip.
58
61
 
@@ -60,6 +63,8 @@ On a wide window the player has two columns: what is playing on the left — cov
60
63
 
61
64
  Turn it on with the switch in the player's AI DJ card, or with `music_dj`. When fewer than 3 tracks remain, the DJ appends a batch of 5. It only stocks the queue; it never starts or stops playback.
62
65
 
66
+ The queue is saved, so after a restart it's back where you left it, paused, and you can press play before the DJ plans anything.
67
+
63
68
  **How it learns your taste:** from your NetEase likes, and from songs you hear through. A song the DJ picked counts only once you've listened past the skip window, so its own picks can't teach it what you like.
64
69
 
65
70
  **Where it looks:** songs similar to what you've heard and liked, personal FM and liked songs you haven't heard in three days (when signed in), the daily recommendations, new songs, and the four main charts. Signed in, the charts and new songs get fewer slots and your own sources more. Each source is cached for hours and sampled, so batches vary; requests to NetEase are spaced out rather than sent in a burst.
@@ -68,6 +73,8 @@ Turn it on with the switch in the player's AI DJ card, or with `music_dj`. When
68
73
 
69
74
  **Mood brief.** Type a mood in the AI DJ card, such as `雨天 爵士` or `90s cantopop`. The DJ searches NetEase playlists for it. With a model available, the brief is first rewritten into Chinese search terms, once per brief.
70
75
 
76
+ After you change the mood or set a boost, the DJ's next batch replaces its own picks that haven't played yet, so the new direction starts right away. The song playing and songs you queued yourself stay.
77
+
71
78
  **Who chooses:**
72
79
 
73
80
  - **Model tier:** a model picks from the candidates by your taste and the mood, and writes a one-line vibe. It calls the model directly; it is not an agent and starts no conversation.
package/lib/dj.js CHANGED
@@ -218,6 +218,42 @@ export function curationRequest({ target, messages, sessionId }) {
218
218
  return { ...target, messages, sessionId };
219
219
  }
220
220
 
221
+ /** Each NetEase text an introduction is written from is cut to this many characters. */
222
+ const INTRO_SOURCE_CHARS = 1_200;
223
+
224
+ /** What the model is told about a song: its facts, then NetEase's own prose. */
225
+ export function introMaterial(info) {
226
+ const cut = (text) => (text.length > INTRO_SOURCE_CHARS ? `${text.slice(0, INTRO_SOURCE_CHARS)}…` : text);
227
+ const album = info.album ?? {};
228
+ const artists = info.artists ?? [];
229
+ const released = album.publishTime ? new Date(album.publishTime).getUTCFullYear() : null;
230
+ return [
231
+ `Song: ${info.name}${info.alias?.length ? ` (${info.alias.join(' / ')})` : ''}`,
232
+ `Artists: ${artists.map((artist) => artist.name).join(', ') || '(unknown)'}`,
233
+ album.name ? `Album: ${album.name}${[album.subType || album.type, released, album.company].filter(Boolean).map((note) => `, ${note}`).join('')}` : '',
234
+ info.genres?.length ? `Genre: ${info.genres.join(', ')}` : '',
235
+ info.tags?.length ? `Tags: ${info.tags.join(', ')}` : '',
236
+ info.language ? `Language: ${info.language}` : '',
237
+ info.featuredIn?.length ? `Featured in: ${info.featuredIn.join('; ')}` : '',
238
+ info.awards?.length ? `Awards: ${info.awards.join('; ')}` : '',
239
+ info.review?.text ? `\nA listener's review:\n${cut(info.review.text)}` : '',
240
+ ...artists.filter((artist) => artist.intro).map((artist) => `\nAbout ${artist.name}:\n${cut(artist.intro)}`),
241
+ album.intro ? `\nAbout the album:\n${cut(album.intro)}` : '',
242
+ ]
243
+ .filter(Boolean)
244
+ .join('\n');
245
+ }
246
+
247
+ /** A model's prose without the markdown it was asked not to use. */
248
+ function plainProse(text) {
249
+ return String(text ?? '')
250
+ .replace(/^```\w*\s*|```\s*$/g, '')
251
+ .replace(/^#{1,6}\s+.*$/gm, '')
252
+ .replace(/\*\*|__/g, '')
253
+ .replace(/\n{3,}/g, '\n\n')
254
+ .trim();
255
+ }
256
+
221
257
  /**
222
258
  * @typedef {object} Plan
223
259
  * @property {object[]} tracks chosen tracks, in play order.
@@ -284,6 +320,14 @@ export class AiDj {
284
320
  this.modelError = null;
285
321
  /** Guards against overlapping plans when a track ends mid-plan. */
286
322
  this.busy = false;
323
+ /**
324
+ * Ids of the DJ's upcoming picks chosen before the listener last steered —
325
+ * a new mood brief, or a boost either way. The first plan to land after
326
+ * the steer replaces whichever of them are still unplayed.
327
+ */
328
+ this.stale = new Set();
329
+ /** Counts steers, so a plan begun before one knows its own picks are stale. */
330
+ this.steers = 0;
287
331
  /** The sources' answers, each kept for as long as it plausibly stays the same. */
288
332
  this.cache = new TtlCache({ now });
289
333
  /** Every source request goes through this, so a plan never arrives as a burst. */
@@ -569,6 +613,31 @@ export class AiDj {
569
613
  return {};
570
614
  }
571
615
 
616
+ /** The listener changed direction: every upcoming DJ pick is now stale. */
617
+ #steer() {
618
+ this.steers += 1;
619
+ for (const track of this.player.remaining()) {
620
+ if (track.queuedBy === 'dj') this.stale.add(track.id);
621
+ }
622
+ }
623
+
624
+ /** Queue positions of the stale picks still unplayed, last first so each can be removed in turn. */
625
+ #staleUpcoming() {
626
+ const at = [];
627
+ for (let index = this.player.queue.length - 1; index > this.player.index; index -= 1) {
628
+ const track = this.player.queue[index];
629
+ if (track.queuedBy === 'dj' && this.stale.has(track.id)) at.push(index);
630
+ }
631
+ return at;
632
+ }
633
+
634
+ /** Set the mood brief; a different one is a steer. */
635
+ setPrompt(prompt) {
636
+ const next = String(prompt);
637
+ if (next.trim() !== (this.store.settings.djPrompt ?? '').trim()) this.#steer();
638
+ this.store.updateSettings({ djPrompt: next });
639
+ }
640
+
572
641
  /**
573
642
  * Make a fresh boost felt now rather than a batch or two later.
574
643
  *
@@ -584,6 +653,8 @@ export class AiDj {
584
653
  async applyBoost(track, direction) {
585
654
  const effect = { queued: 0, removed: 0 };
586
655
  if (!this.player.dj.enabled || !track?.id) return effect;
656
+ // Before "more" queues its neighbours: they are picked the new way.
657
+ if (direction === 'more' || direction === 'less') this.#steer();
587
658
  const similar = await this.#neighboursOf(track);
588
659
  if (direction === 'more') {
589
660
  const digest = this.store.tasteDigest();
@@ -864,6 +935,48 @@ export class AiDj {
864
935
  return unique;
865
936
  }
866
937
 
938
+ /**
939
+ * An introduction to a song and its artists for the player's details pane,
940
+ * written by the model from what NetEase holds about them, on the same route
941
+ * and under the same identity as curation.
942
+ *
943
+ * @param {object} info the song's details, as `Netease#songInfo` returns them.
944
+ * @param {{lang?: 'en'|'zh'}} [options] the language the panel is showing.
945
+ * @returns {Promise<{text: string, route: string} | null>} `null` when no model route is available.
946
+ * @throws {Error} when the model failed or wrote nothing.
947
+ */
948
+ async introduce(info, { lang = 'en' } = {}) {
949
+ const llm = this.resolveLlm?.();
950
+ if (!llm?.stream) return null;
951
+ const target = await this.#resolveTarget(llm);
952
+ if (!target?.provider || !target?.model) return null;
953
+ const request = curationRequest({
954
+ target,
955
+ sessionId: this.sessionId,
956
+ messages: [
957
+ {
958
+ role: 'user',
959
+ content: [
960
+ {
961
+ type: 'text',
962
+ text:
963
+ 'Introduce the song below to a listener who is playing it now: what the song is, and who sings it. ' +
964
+ 'Rely on the material given; it is from NetEase Cloud Music. Add nothing you are not sure is true, ' +
965
+ 'and when the material is thin, write less rather than guess. ' +
966
+ 'Two or three short paragraphs separated by a blank line, under ' +
967
+ (lang === 'zh' ? '300 characters in all, in Simplified Chinese. ' : '180 words in all, in English. ') +
968
+ 'Plain text only: no title, no headings, no lists, no markdown.',
969
+ },
970
+ { type: 'text', text: introMaterial(info) },
971
+ ],
972
+ },
973
+ ],
974
+ });
975
+ const text = plainProse(await this.#collect(llm.stream(request)));
976
+ if (!text) throw new Error('the model wrote no introduction');
977
+ return { text, route: `${target.provider}/${target.model}` };
978
+ }
979
+
867
980
  // --------------------------------------------------------------- model tier
868
981
 
869
982
  /**
@@ -1217,6 +1330,7 @@ export class AiDj {
1217
1330
  this.player.dj.busy = true;
1218
1331
  this.player.bump();
1219
1332
  try {
1333
+ const steers = this.steers;
1220
1334
  const planned = await this.plan({ prompt: settings.djPrompt ?? '', count: count ?? settings.djBatchSize ?? 5 });
1221
1335
  // The queue can change while the plan is in flight; report only what lands.
1222
1336
  const queued = new Set(this.player.queue.map((track) => track.id));
@@ -1225,6 +1339,19 @@ export class AiDj {
1225
1339
  this.player.dj = { ...this.player.dj, busy: false, error: plan.note ?? 'no tracks found', lastPlanAt: Date.now() };
1226
1340
  return plan;
1227
1341
  }
1342
+ // The first plan after a steer replaces the picks it made stale, so the
1343
+ // new direction plays next. One begun before the latest steer was picked
1344
+ // the old way, so it lands, but is itself stale for the next plan.
1345
+ let replaced = 0;
1346
+ if (steers === this.steers) {
1347
+ for (const index of this.#staleUpcoming()) {
1348
+ this.player.remove(index);
1349
+ replaced += 1;
1350
+ }
1351
+ this.stale.clear();
1352
+ } else {
1353
+ for (const track of plan.tracks) this.stale.add(track.id);
1354
+ }
1228
1355
  // The DJ only stocks the queue; it never changes the transport state.
1229
1356
  // `play: false` preserves whatever the listener chose, so a top-up while
1230
1357
  // paused does not start playback, while a queue refilled after the last
@@ -1245,7 +1372,9 @@ export class AiDj {
1245
1372
  },
1246
1373
  };
1247
1374
  this.player.bump();
1248
- this.logger?.info?.(`[music] DJ added ${plan.tracks.length} track(s) via ${plan.source}`);
1375
+ this.logger?.info?.(
1376
+ `[music] DJ added ${plan.tracks.length} track(s) via ${plan.source}${replaced ? `, replacing ${replaced} stale` : ''}`,
1377
+ );
1249
1378
  return plan;
1250
1379
  } catch (error) {
1251
1380
  this.player.dj = { ...this.player.dj, busy: false, error: error.message };
@@ -1263,12 +1392,14 @@ export class AiDj {
1263
1392
  * @returns {Promise<Plan>}
1264
1393
  */
1265
1394
  async start({ prompt, count = 8 } = {}) {
1266
- this.store.updateSettings({ djEnabled: true, ...(prompt === undefined ? {} : { djPrompt: prompt }) });
1395
+ if (prompt !== undefined) this.setPrompt(prompt);
1396
+ this.store.updateSettings({ djEnabled: true });
1267
1397
  this.player.dj.enabled = true;
1268
1398
  // The batch replaces the queue, so nothing precedes its first track.
1269
1399
  const plan = await this.plan({ prompt: prompt ?? this.store.settings.djPrompt ?? '', count, follows: null });
1270
1400
  if (plan.tracks.length > 0) {
1271
1401
  this.player.setQueue(plan.tracks, { startIndex: 0, play: true, source: plan.source, queuedBy: 'dj' });
1402
+ this.stale.clear();
1272
1403
  this.player.dj.lastPlanAt = Date.now();
1273
1404
  this.player.dj.lastPlan = {
1274
1405
  source: plan.source,
@@ -1289,7 +1420,8 @@ export class AiDj {
1289
1420
  /** Turn continuous mode on or off without touching the queue. */
1290
1421
  setEnabled(enabled, { prompt } = {}) {
1291
1422
  const next = Boolean(enabled);
1292
- this.store.updateSettings({ djEnabled: next, ...(prompt === undefined ? {} : { djPrompt: prompt }) });
1423
+ if (prompt !== undefined) this.setPrompt(prompt);
1424
+ this.store.updateSettings({ djEnabled: next });
1293
1425
  this.player.dj.enabled = next;
1294
1426
  this.player.bump();
1295
1427
  return next;
package/lib/index.js CHANGED
@@ -128,6 +128,7 @@ export function apply(ctx, config = {}) {
128
128
  const player = new Player({ logger });
129
129
  // Restore the persisted DJ preference so continuous mode survives a restart.
130
130
  player.dj.enabled = Boolean(store.settings.djEnabled);
131
+ player.restore(store.savedQueue);
131
132
 
132
133
  const qr = new QrLogin({ api, store, logger });
133
134
 
@@ -229,13 +230,23 @@ export function apply(ctx, config = {}) {
229
230
  // The one place a play is recorded: whenever the current track changes, by
230
231
  // whatever path. Recording it again where the queue is set counted every
231
232
  // played track twice, and an appended one as a play of the current track.
232
- let lastRecorded = null;
233
+ // A restored current track was recorded by the run that played it.
234
+ let lastRecorded = player.current()?.id ?? null;
233
235
  player.subscribe(() => {
234
236
  const current = player.current();
235
237
  if (!current || current.id === lastRecorded) return;
236
238
  lastRecorded = current.id;
237
239
  store.recordPlay(current, { tentative: current.queuedBy === 'dj' });
238
240
  });
241
+
242
+ // Saved only when the queue or cursor moves, not on every position report.
243
+ let savedQueueKey = null;
244
+ player.subscribe(() => {
245
+ const key = `${player.index}:${player.queue.map((track) => track.id).join(',')}`;
246
+ if (key === savedQueueKey) return;
247
+ savedQueueKey = key;
248
+ store.saveQueue(player.queue, player.index);
249
+ });
239
250
  player.onHeard = (track) => store.confirmPlay(track.id);
240
251
 
241
252
  // Plays reach the account's listening history the way the web player's do.
package/lib/netease.js CHANGED
@@ -219,6 +219,55 @@ function normalizeTracks(list) {
219
219
  return (list ?? []).map(normalizeTrack).filter(Boolean);
220
220
  }
221
221
 
222
+ /** Encyclopedia prose without its citation marks (`[38]`) or ragged blank lines. */
223
+ export function cleanText(text) {
224
+ return String(text ?? '')
225
+ .replace(/\s*\[\d+(?:-\d+)?\]/g, '')
226
+ .replace(/\n{3,}/g, '\n\n')
227
+ .trim();
228
+ }
229
+
230
+ /**
231
+ * The song facts in a music-wiki ("音乐百科") answer. The wiki is a page of UI
232
+ * blocks; the facts are the creatives of its basic block, keyed by
233
+ * `creativeType`, with their values in resource titles or text links.
234
+ */
235
+ export function parseSongWiki(data) {
236
+ const facts = { genres: [], tags: [], language: '', bpm: null, awards: [], featuredIn: [], review: null };
237
+ const basic = (data?.data?.blocks ?? []).find((block) => block?.code === 'SONG_PLAY_ABOUT_SONG_BASIC');
238
+ for (const creative of basic?.creatives ?? []) {
239
+ const titles = (creative.resources ?? []).map((resource) => resource?.uiElement?.mainTitle?.title).filter(Boolean);
240
+ const text = creative.uiElement?.textLinks?.[0]?.text ?? '';
241
+ switch (creative.creativeType) {
242
+ case 'songTag':
243
+ facts.genres = titles;
244
+ break;
245
+ case 'songBizTag':
246
+ facts.tags = titles;
247
+ break;
248
+ case 'language':
249
+ facts.language = text;
250
+ break;
251
+ case 'bpm':
252
+ facts.bpm = Number(text) || null;
253
+ break;
254
+ case 'songAward':
255
+ facts.awards = titles;
256
+ break;
257
+ case 'entertainment':
258
+ facts.featuredIn = titles;
259
+ break;
260
+ case 'songComment': {
261
+ const resource = creative.resources?.[0]?.uiElement;
262
+ const body = cleanText(resource?.descriptions?.[0]?.description);
263
+ if (body) facts.review = { text: body, by: String(resource?.mainTitle?.title ?? '').replace(/^乐评来自\s*/, '') };
264
+ break;
265
+ }
266
+ }
267
+ }
268
+ return facts;
269
+ }
270
+
222
271
  /** `[1,2]` — NetEase wants bracketed ids in query strings. */
223
272
  function idList(ids) {
224
273
  return encodeURIComponent(JSON.stringify([...ids].map(Number)));
@@ -493,6 +542,55 @@ export class Netease {
493
542
  };
494
543
  }
495
544
 
545
+ /**
546
+ * What the panel's details pane says about a song: its album, its music-wiki
547
+ * entry (genre, tags, language, BPM, awards, where it was featured, a review)
548
+ * and an introduction to each of its first three artists.
549
+ *
550
+ * Only the song itself is required; each other part is fetched on its own
551
+ * and left empty when it fails, so one missing wiki entry never costs the
552
+ * album and the artists.
553
+ */
554
+ async songInfo(id) {
555
+ const detail = await this.call('/api/song/detail', { query: { ids: JSON.stringify([Number(id)]) } });
556
+ const song = detail?.songs?.[0];
557
+ if (!song) throw new NeteaseError(`song ${id} not found`, { code: detail?.code, endpoint: 'song/detail' });
558
+ const albumRef = song.al ?? song.album ?? {};
559
+ const artistRefs = (song.ar ?? song.artists ?? []).filter((artist) => artist?.id).slice(0, 3);
560
+
561
+ const [album, wiki, artists] = await Promise.all([
562
+ albumRef.id ? this.call(`/api/v1/album/${albumRef.id}`).then((data) => data?.album ?? null, () => null) : null,
563
+ this.call('/api/song/play/about/block/page', { method: 'POST', body: { songId: Number(id) } }).catch(() => null),
564
+ Promise.all(
565
+ artistRefs.map((artist) =>
566
+ this.call('/api/artist/introduction', { query: { id: artist.id } }).then(
567
+ (data) => ({ id: artist.id, name: artist.name, intro: cleanText(data?.briefDesc) }),
568
+ () => ({ id: artist.id, name: artist.name, intro: '' }),
569
+ ),
570
+ ),
571
+ ),
572
+ ]);
573
+
574
+ return {
575
+ id: Number(id),
576
+ name: song.name ?? '',
577
+ alias: [...(song.alia ?? song.alias ?? []), ...(song.tns ?? song.transNames ?? [])].filter(Boolean),
578
+ publishTime: song.publishTime || null,
579
+ album: {
580
+ id: albumRef.id ?? null,
581
+ name: album?.name ?? albumRef.name ?? '',
582
+ type: album?.type ?? albumRef.type ?? '',
583
+ subType: album?.subType ?? albumRef.subType ?? '',
584
+ company: album?.company || albumRef.company || '',
585
+ publishTime: album?.publishTime || albumRef.publishTime || null,
586
+ size: album?.size ?? albumRef.size ?? 0,
587
+ intro: cleanText(album?.description || album?.briefDesc),
588
+ },
589
+ artists,
590
+ ...parseSongWiki(wiki),
591
+ };
592
+ }
593
+
496
594
  /** Playlist header plus its first `limit` tracks. */
497
595
  async playlistDetail(id, { limit = 500 } = {}) {
498
596
  const data = await this.call('/api/v6/playlist/detail', {
package/lib/panel.html CHANGED
@@ -13,10 +13,16 @@
13
13
  <meta name="dsh-music-panel-contract" content="2" />
14
14
  <title>Music · music.163.com</title>
15
15
  <style>
16
+ /* DSH's light palette (base background, primary label, scrollbar). The
17
+ page follows the shell's theme while it sits inside DSH, and the
18
+ system's otherwise; see syncShellTheme. Every other colour is mixed
19
+ from these. */
16
20
  :root {
17
- color-scheme: light dark;
18
- --bg: var(--dsh-background, #ffffff);
19
- --fg: var(--dsh-foreground, #1b1c1e);
21
+ color-scheme: light;
22
+ --bg: #ffffff;
23
+ --fg: #0f1115;
24
+ --scrollbar-thumb: #e5e5e5;
25
+ --scrollbar-thumb-hover: #d4d4d4;
20
26
  --muted: color-mix(in srgb, var(--fg) 56%, transparent);
21
27
  --faint: color-mix(in srgb, var(--fg) 38%, transparent);
22
28
  --line: color-mix(in srgb, var(--fg) 12%, transparent);
@@ -27,6 +33,23 @@
27
33
  --radius: 12px;
28
34
  --gap: 16px;
29
35
  }
36
+ /* DSH's dark palette: the system's choice standalone, the shell's inside DSH. */
37
+ @media (prefers-color-scheme: dark) {
38
+ :root:not([data-theme="light"]) {
39
+ color-scheme: dark;
40
+ --bg: #151517;
41
+ --fg: #f9fafb;
42
+ --scrollbar-thumb: #3c3c3d;
43
+ --scrollbar-thumb-hover: #545557;
44
+ }
45
+ }
46
+ :root[data-theme="dark"] {
47
+ color-scheme: dark;
48
+ --bg: #151517;
49
+ --fg: #f9fafb;
50
+ --scrollbar-thumb: #3c3c3d;
51
+ --scrollbar-thumb-hover: #545557;
52
+ }
30
53
  * { box-sizing: border-box; }
31
54
  html, body { margin: 0; height: 100%; }
32
55
  body {
@@ -54,6 +77,20 @@
54
77
  svg.i.filled { fill: currentColor; }
55
78
  svg.i.small { width: 14px; height: 14px; }
56
79
 
80
+ /* Scrollbars as DSH draws them in its conversation and everywhere else
81
+ (dsh-client-ui-theme's scrollbar.css): a 5px rounded thumb on no
82
+ track, darker under the pointer. */
83
+ @supports not selector(::-webkit-scrollbar) {
84
+ * { scrollbar-width: thin; scrollbar-color: var(--scrollbar-thumb) transparent; }
85
+ }
86
+ ::-webkit-scrollbar { width: 5px; height: 5px; }
87
+ ::-webkit-scrollbar-track { background: none; }
88
+ ::-webkit-scrollbar-thumb { background: var(--scrollbar-thumb); background-clip: content-box; border-radius: 999px; }
89
+ ::-webkit-scrollbar-thumb:hover { background-color: var(--scrollbar-thumb-hover); }
90
+ ::-webkit-scrollbar-corner { background: none; }
91
+ /* Inside a card, the thumb keeps clear of the rounded corners, as DSH's own cards do. */
92
+ .card ::-webkit-scrollbar-track { margin-block: 6px; }
93
+
57
94
  /* ------------------------------------------------------------ layout
58
95
  Wide: the stage (what is playing) on the left, what comes next — the
59
96
  DJ and the queue — on the right, each column scrolling on its own.
@@ -82,9 +119,11 @@
82
119
  .side { overflow: hidden; border-left: 1px solid var(--line); }
83
120
  .side .queue-card { flex: 1; min-height: 0; }
84
121
  .side #queue { overflow: auto; }
85
- /* With a column of its own, the lyrics fill what the stage leaves. */
86
- .stage .lyrics-card { flex: 1; min-height: 160px; }
87
- .stage .lyrics { flex: 1; max-height: none; }
122
+ /* With a column of its own, the details or lyrics fill what the stage
123
+ leaves. The floor is the header and two lines: any higher and a short
124
+ window scrolls the whole column as well as the card. */
125
+ .stage .info-card { flex: 1; min-height: 72px; }
126
+ .stage .lyrics, .stage .details { flex: 1; max-height: none; }
88
127
  }
89
128
 
90
129
  .card { border: 1px solid var(--line); border-radius: var(--radius); background: var(--panel); }
@@ -147,7 +186,15 @@
147
186
  #mute:hover:not(:disabled) { color: var(--fg); }
148
187
  #volume { flex: 0 0 96px; }
149
188
 
150
- .lyrics-card { display: flex; flex-direction: column; min-height: 0; }
189
+ .info-card { display: flex; flex-direction: column; min-height: 0; }
190
+ .tabs { display: flex; gap: 14px; }
191
+ .tab {
192
+ background: none; border: 0; border-bottom: 2px solid transparent; border-radius: 0; padding: 0 0 2px;
193
+ color: var(--muted); font: inherit; text-transform: inherit; letter-spacing: inherit;
194
+ }
195
+ .tab:hover:not(:disabled) { background: none; color: var(--fg); }
196
+ .tab.on { color: var(--fg); border-bottom-color: var(--accent); }
197
+ .lyrics[hidden], .details[hidden] { display: none; }
151
198
  /* The pane is a glance at the current line, not a page: a few lines of
152
199
  synced text, scrolled for the rest. `--lyrics-lines` is the single knob. */
153
200
  .lyrics {
@@ -156,10 +203,44 @@
156
203
  overflow: auto; padding: 2px 12px 14px; font-size: 14px; line-height: 1.6; scrollbar-width: none;
157
204
  }
158
205
  .lyrics::-webkit-scrollbar { display: none; }
159
- .lyrics.collapsed { display: none; }
160
206
  .lyrics p { margin: 0; padding: 2px 0; color: var(--faint); transition: color 0.15s; }
161
207
  .lyrics p.on { color: var(--fg); font-weight: 600; }
162
208
 
209
+ /* The song's facts first, then prose about the song, its artists and its
210
+ album, each clamped to a few lines until clicked. */
211
+ .details {
212
+ max-height: 320px; overflow: auto; padding: 2px 12px 14px;
213
+ display: flex; flex-direction: column; gap: 12px;
214
+ }
215
+ .details .alias { color: var(--muted); margin: 0; }
216
+ .facts { display: grid; grid-template-columns: max-content minmax(0, 1fr); gap: 5px 14px; margin: 0; }
217
+ .facts dt { color: var(--muted); }
218
+ .facts dd { margin: 0; overflow-wrap: anywhere; }
219
+ .chips { display: flex; flex-wrap: wrap; gap: 4px; }
220
+ .chip { padding: 0 8px; border-radius: 999px; background: var(--hover); font-size: 12px; }
221
+ .chip.genre { background: var(--accent-soft); }
222
+ .about h4 {
223
+ margin: 0 0 3px; color: var(--muted); font-size: 11px; font-weight: 600;
224
+ text-transform: uppercase; letter-spacing: 0.6px;
225
+ }
226
+ .about .prose {
227
+ cursor: pointer;
228
+ display: -webkit-box; -webkit-box-orient: vertical; -webkit-line-clamp: 4; overflow: hidden;
229
+ }
230
+ .about .prose.open { display: block; }
231
+ .about .prose p { margin: 0; }
232
+ .about .prose p + p { margin-top: 8px; }
233
+ .about .by { color: var(--muted); font-size: 12px; margin-top: 2px; }
234
+ .about .badge {
235
+ margin-left: 6px; padding: 0 5px; border-radius: 4px; background: var(--accent-soft); color: var(--accent);
236
+ font-size: 10px; letter-spacing: 0.4px;
237
+ }
238
+ .about .written { cursor: pointer; }
239
+ .about .written p { margin: 0; }
240
+ .about .written p + p { margin-top: 8px; }
241
+ .about .writing { color: var(--muted); margin: 0; }
242
+ .details .source { align-self: flex-start; font-size: 12px; }
243
+
163
244
  .need-gesture {
164
245
  background: var(--accent-soft); border: 1px solid color-mix(in srgb, var(--accent) 40%, transparent);
165
246
  border-radius: var(--radius); padding: 8px 12px; font-size: 12px;
@@ -247,7 +328,7 @@
247
328
 
248
329
  .toast {
249
330
  position: fixed; left: 50%; bottom: 18px; transform: translateX(-50%);
250
- background: #1b1c1e; color: #fff; padding: 8px 14px; border-radius: 9px; font-size: 12px;
331
+ background: var(--fg); color: var(--bg); padding: 8px 14px; border-radius: 9px; font-size: 12px;
251
332
  opacity: 0; pointer-events: none; transition: opacity 0.2s; z-index: 40; max-width: 80%;
252
333
  }
253
334
  .toast.on { opacity: 0.94; }
@@ -258,7 +339,7 @@
258
339
  dialog::backdrop { background: rgba(0, 0, 0, 0.45); }
259
340
  #qr { display: block; margin: 12px auto; width: 220px; height: 220px; image-rendering: pixelated; border-radius: 8px; background: #fff; padding: 8px; }
260
341
  .hint { color: var(--muted); font-size: 12px; text-align: center; }
261
- .lyrics .hint { text-align: left; }
342
+ .lyrics .hint, .details .hint { text-align: left; margin: 0; }
262
343
  .row-actions { display: flex; gap: 6px; justify-content: flex-end; margin-top: 14px; }
263
344
  </style>
264
345
  </head>
@@ -313,15 +394,15 @@
313
394
  <input type="range" id="volume" min="0" max="1" step="0.01" value="0.8" />
314
395
  </div>
315
396
 
316
- <div class="card lyrics-card">
397
+ <div class="card info-card">
317
398
  <div class="card-head">
318
- <span data-i18n="lyrics">Lyrics</span>
319
- <span class="grow"></span>
320
- <!-- Label and title are state-dependent, so the script owns them
321
- (applyStaticStrings cannot know which way the pane is now). -->
322
- <button id="lyrics-toggle" class="link" type="button" aria-expanded="true">Hide</button>
399
+ <div class="tabs" role="tablist">
400
+ <button id="tab-details" class="tab" type="button" role="tab" data-i18n="details">Details</button>
401
+ <button id="tab-lyrics" class="tab" type="button" role="tab" data-i18n="lyrics">Lyrics</button>
402
+ </div>
323
403
  </div>
324
- <div class="lyrics" id="lyrics"><p class="hint">—</p></div>
404
+ <div class="details" id="details" role="tabpanel"><p class="hint">—</p></div>
405
+ <div class="lyrics" id="lyrics" role="tabpanel" hidden><p class="hint">—</p></div>
325
406
  </div>
326
407
  </section>
327
408
 
@@ -365,7 +446,11 @@
365
446
  </div>
366
447
 
367
448
  <div class="card queue-card">
368
- <div class="card-head"><span data-i18n="queue">Queue</span> <span id="counts"></span></div>
449
+ <div class="card-head">
450
+ <span data-i18n="queue">Queue</span> <span id="counts"></span>
451
+ <span class="grow"></span>
452
+ <button id="queue-clear" class="link" type="button" data-i18n="clearQueue" data-i18n-title="clearQueueTitle">Clear</button>
453
+ </div>
369
454
  <div id="queue"></div>
370
455
  </div>
371
456
  </aside>
@@ -423,10 +508,24 @@
423
508
  likeNeedsSignIn: '登录后才能在网易云标记喜欢',
424
509
  mute: '静音',
425
510
  lyrics: '歌词',
426
- lyricsHide: '收起',
427
- lyricsShow: '展开',
428
- lyricsToggleHide: '收起歌词面板',
429
- lyricsToggleShow: '展开歌词面板',
511
+ details: '详情',
512
+ noDetails: '暂无这首歌的信息',
513
+ album: '专辑',
514
+ albumTracks: '{n} 首',
515
+ genre: '曲风',
516
+ tags: '标签',
517
+ language: '语种',
518
+ featuredIn: '影视节目',
519
+ awards: '获奖',
520
+ aboutSong: '关于这首歌',
521
+ aboutAlbum: '关于专辑',
522
+ reviewBy: '乐评来自 {name}',
523
+ intro: '简介',
524
+ introWriting: '正在撰写简介…',
525
+ introFromNetease: '查看网易云音乐的介绍',
526
+ introFromAi: '查看 AI 简介',
527
+ introToNetease: '点击查看网易云音乐的介绍',
528
+ expand: '点击展开或收起',
430
529
  queue: '播放队列',
431
530
  djModel: 'AI DJ 模型',
432
531
  djModelToggleShow: '展开模型设置',
@@ -458,6 +557,8 @@
458
557
  queueEmpty: '队列为空,用 AI DJ 或让助手补歌',
459
558
  remove: '移除',
460
559
  removed: '已移除',
560
+ clearQueue: '清空',
561
+ clearQueueTitle: '清空队列,保留正在播放的歌曲;不会给歌曲打分',
461
562
  loading: '加载中…',
462
563
  instrumental: '纯音乐,无歌词',
463
564
  other: '其他…',
@@ -525,10 +626,24 @@
525
626
  likeNeedsSignIn: 'Sign in to NetEase to like tracks',
526
627
  mute: 'Mute',
527
628
  lyrics: 'Lyrics',
528
- lyricsHide: 'Hide',
529
- lyricsShow: 'Show',
530
- lyricsToggleHide: 'Collapse the lyrics pane',
531
- lyricsToggleShow: 'Expand the lyrics pane',
629
+ details: 'Details',
630
+ noDetails: 'No details for this song',
631
+ album: 'Album',
632
+ albumTracks: '{n} tracks',
633
+ genre: 'Genre',
634
+ tags: 'Tags',
635
+ language: 'Language',
636
+ featuredIn: 'Featured in',
637
+ awards: 'Awards',
638
+ aboutSong: 'About the song',
639
+ aboutAlbum: 'About the album',
640
+ reviewBy: 'Review by {name}',
641
+ intro: 'Introduction',
642
+ introWriting: 'Writing an introduction…',
643
+ introFromNetease: 'Show what NetEase says',
644
+ introFromAi: 'Show the AI introduction',
645
+ introToNetease: 'Click to show what NetEase says',
646
+ expand: 'Click to expand or collapse',
532
647
  queue: 'Queue',
533
648
  djModel: 'DJ model',
534
649
  djModelToggleShow: 'Show the model settings',
@@ -560,6 +675,8 @@
560
675
  queueEmpty: 'Queue empty — use the AI DJ or ask the assistant to add songs',
561
676
  remove: 'Remove',
562
677
  removed: 'Removed',
678
+ clearQueue: 'Clear',
679
+ clearQueueTitle: 'Clear the queue, keeping the song playing; no song is rated',
563
680
  loading: 'Loading…',
564
681
  instrumental: 'Instrumental',
565
682
  other: 'Other…',
@@ -703,10 +820,11 @@
703
820
  document.documentElement.lang = LANG === 'zh' ? 'zh-CN' : 'en';
704
821
  } catch { /* headless */ }
705
822
  applyStaticStrings();
706
- // The toggles' labels and titles depend on the collapse state, not on a
707
- // fixed key, so they are painted rather than carried as data-i18n.
708
- paintLyricsToggle();
823
+ // The model toggle's label depends on its fold, not on a fixed key, so
824
+ // it is painted rather than carried as data-i18n.
709
825
  paintDjModelToggle();
826
+ // The details carry translated labels around NetEase's own text.
827
+ if (infoView === 'details') repaintDetails();
710
828
  // The gesture hint carries markup; drop it so render() rebuilds it in
711
829
  // the new language.
712
830
  $('gesture')?.remove();
@@ -722,6 +840,42 @@
722
840
  }
723
841
 
724
842
  /** Follow the shell's language while this page lives inside it. */
843
+ /** The shell's colours this page takes on, by the shell's variable name. */
844
+ const SHELL_COLORS = [
845
+ ['--dsw-alias-bg-base', '--bg'],
846
+ ['--dsw-alias-label-primary', '--fg'],
847
+ ['--dsh-scrollbar-thumb', '--scrollbar-thumb'],
848
+ ['--dsh-scrollbar-thumb-hover', '--scrollbar-thumb-hover'],
849
+ ];
850
+
851
+ /**
852
+ * Follow the shell's theme. DSH marks dark with `data-ds-dark-theme` on
853
+ * its body and paints from token variables there; this page takes the
854
+ * mark, then the live colours, so a custom DSH theme carries over too.
855
+ * A theme switch rewrites those attributes and styles, so watching them
856
+ * catches every switch. Standalone, the system's preference decides.
857
+ */
858
+ function syncShellTheme() {
859
+ try {
860
+ const shell = window.parent?.document;
861
+ if (!shell?.body || shell === document) return;
862
+ const copy = () => {
863
+ const root = document.documentElement;
864
+ root.dataset.theme = shell.body.hasAttribute('data-ds-dark-theme') ? 'dark' : 'light';
865
+ const computed = getComputedStyle(shell.body);
866
+ for (const [from, to] of SHELL_COLORS) {
867
+ const value = computed.getPropertyValue(from).trim();
868
+ if (value) root.style.setProperty(to, value);
869
+ else root.style.removeProperty(to);
870
+ }
871
+ };
872
+ copy();
873
+ if (typeof MutationObserver !== 'function') return;
874
+ const observer = new MutationObserver(copy);
875
+ for (const node of [shell.documentElement, shell.body]) observer.observe(node, { attributes: true, attributeFilter: ['style', 'class', 'data-ds-dark-theme'] });
876
+ } catch { /* standalone, or the shell is out of reach */ }
877
+ }
878
+
725
879
  function watchShellLocale() {
726
880
  try {
727
881
  const root = window.parent?.document?.documentElement;
@@ -738,9 +892,23 @@
738
892
  let lyricTrackId = null;
739
893
  /** Bumped per request so a slow reply for a skipped track is discarded. */
740
894
  let lyricRequest = 0;
741
- /** Local-storage key for whether the lyrics pane is collapsed. */
742
- const LYRICS_PREF = 'dsh-music.lyrics.collapsed';
743
- let lyricsCollapsed = readLyricsPref();
895
+ /** Local-storage key for which pane the info card shows: `details` or `lyrics`. */
896
+ const INFO_VIEW_PREF = 'dsh-music.info.view';
897
+ let infoView = readInfoViewPref();
898
+ /** Track whose details belong in the pane, as `lyricTrackId` is for lyrics. */
899
+ let detailsTrackId = null;
900
+ let detailsRequest = 0;
901
+ /** Details already fetched, by track id, so switching back is instant. */
902
+ const detailsCache = new Map();
903
+ /**
904
+ * Model-written introductions by `<track id>:<language>`: `'pending'`
905
+ * while one is being written, then `{text}`, empty when none could be.
906
+ */
907
+ const intros = new Map();
908
+ /** Whether the last introduction came back empty, so the next track shows NetEase's prose while it waits. */
909
+ let introsUnavailable = false;
910
+ /** Which introduction the details show: `ai`, or NetEase's own (`netease`). Back to `ai` per track. */
911
+ let introSource = 'ai';
744
912
  /** Local-storage key for whether the DJ model form is unfolded. */
745
913
  const DJ_MODEL_PREF = 'dsh-music.djmodel.expanded';
746
914
  let djModelExpanded = readDjModelPref();
@@ -1051,24 +1219,17 @@
1051
1219
  $('np-title').textContent = track ? track.name : t('nothingPlaying');
1052
1220
  $('np-artists').textContent = track ? (track.artists || []).join(' / ') : '';
1053
1221
  $('np-album').textContent = track ? track.album || '' : '';
1054
- // Lyrics belong to the track, and this page fetches them itself on
1055
- // every poll — not from the local transport's `applySource`, which
1056
- // only ever runs when this page owns the audio element. In the normal
1057
- // case the shell engine plays, so that path is dead and the pane
1058
- // stayed empty forever.
1059
- const trackId = track?.id ?? null;
1060
- if (trackId !== lyricTrackId) {
1061
- lyricTrackId = trackId;
1062
- if (trackId) loadLyrics(trackId);
1063
- else {
1064
- lyric = null;
1065
- lyricLine = -1;
1066
- $('lyrics').innerHTML = '<p class="hint">—</p>';
1067
- }
1068
- }
1222
+ // Details and lyrics belong to the track, and this page fetches them
1223
+ // itself on every poll — not from the local transport's `applySource`,
1224
+ // which only ever runs when this page owns the audio element. In the
1225
+ // normal case the shell engine plays, so that path is dead and the
1226
+ // pane stayed empty forever.
1227
+ syncInfo(track?.id ?? null);
1228
+ loadIntro();
1069
1229
  setIcon($('play'), state.playing ? 'pause' : 'play', { filled: true });
1070
1230
  $('mode').textContent = { list: t('modeList'), single: t('modeSingle'), shuffle: t('modeShuffle') }[state.mode] || t('modeList');
1071
1231
  $('counts').textContent = state.counts ? `(${state.counts.queued})` : '';
1232
+ $('queue-clear').disabled = (state.queue?.length ?? 0) <= (state.current ? 1 : 0);
1072
1233
  $('dj-toggle').classList.toggle('on', Boolean(state.dj?.enabled));
1073
1234
  paintHistory();
1074
1235
  // The mood brief is persisted player setting, not part of the DJ status
@@ -1301,38 +1462,212 @@
1301
1462
  $('t-dur').textContent = fmt(duration);
1302
1463
  }
1303
1464
 
1304
- // ---------------------------------------------------------------- lyrics
1305
- /** Collapsed preference, remembered across reloads when storage is open. */
1306
- function readLyricsPref() {
1307
- try { return localStorage.getItem(LYRICS_PREF) === '1'; } catch { return false; }
1465
+ // ------------------------------------------------------ details + lyrics
1466
+ /** The pane shown, remembered across reloads when storage is open; details by default. */
1467
+ function readInfoViewPref() {
1468
+ try { return localStorage.getItem(INFO_VIEW_PREF) === 'lyrics' ? 'lyrics' : 'details'; } catch { return 'details'; }
1308
1469
  }
1309
1470
 
1310
- function saveLyricsPref(collapsed) {
1311
- try { localStorage.setItem(LYRICS_PREF, collapsed ? '1' : '0'); } catch { /* storage denied */ }
1471
+ function saveInfoViewPref(view) {
1472
+ try { localStorage.setItem(INFO_VIEW_PREF, view); } catch { /* storage denied */ }
1312
1473
  }
1313
1474
 
1314
- /** Reflect `lyricsCollapsed` in the pane and in the header button. */
1315
- function paintLyricsToggle() {
1316
- $('lyrics').classList.toggle('collapsed', lyricsCollapsed);
1317
- const button = $('lyrics-toggle');
1318
- button.textContent = t(lyricsCollapsed ? 'lyricsShow' : 'lyricsHide');
1319
- button.title = t(lyricsCollapsed ? 'lyricsToggleShow' : 'lyricsToggleHide');
1320
- button.setAttribute('aria-expanded', lyricsCollapsed ? 'false' : 'true');
1475
+ /** Reflect `infoView` in the tabs and the panes. */
1476
+ function paintInfoTabs() {
1477
+ for (const view of ['details', 'lyrics']) {
1478
+ const on = infoView === view;
1479
+ $('tab-' + view).classList.toggle('on', on);
1480
+ $('tab-' + view).setAttribute('aria-selected', on ? 'true' : 'false');
1481
+ $(view).hidden = !on;
1482
+ }
1321
1483
  }
1322
1484
 
1323
- $('lyrics-toggle').onclick = () => {
1324
- lyricsCollapsed = !lyricsCollapsed;
1325
- saveLyricsPref(lyricsCollapsed);
1326
- paintLyricsToggle();
1327
- // A hidden pane has no scroll position to keep, so re-expanding puts
1328
- // the highlighted line back in view instead of waiting for the next
1329
- // line change to scroll there.
1330
- if (!lyricsCollapsed) {
1485
+ /**
1486
+ * Bring the visible pane up to the track. Only the visible one: a hidden
1487
+ * pane is neither fetched nor painted, and catches up when it is shown.
1488
+ */
1489
+ function syncInfo(trackId) {
1490
+ if (infoView === 'details') {
1491
+ if (trackId === detailsTrackId) return;
1492
+ detailsTrackId = trackId;
1493
+ if (trackId) loadDetails(trackId);
1494
+ else $('details').innerHTML = '<p class="hint">—</p>';
1495
+ return;
1496
+ }
1497
+ if (trackId === lyricTrackId) return;
1498
+ lyricTrackId = trackId;
1499
+ if (trackId) loadLyrics(trackId);
1500
+ else {
1501
+ lyric = null;
1502
+ lyricLine = -1;
1503
+ $('lyrics').innerHTML = '<p class="hint">—</p>';
1504
+ }
1505
+ }
1506
+
1507
+ function showInfo(view) {
1508
+ if (view === infoView) return;
1509
+ infoView = view;
1510
+ saveInfoViewPref(view);
1511
+ paintInfoTabs();
1512
+ syncInfo(state?.current?.id ?? null);
1513
+ // A hidden pane kept no scroll position, so showing the lyrics puts the
1514
+ // current line back in view instead of waiting for the next line.
1515
+ if (view === 'lyrics') {
1331
1516
  lyricLine = -1;
1332
1517
  paintLyrics();
1333
1518
  }
1519
+ }
1520
+
1521
+ $('tab-details').onclick = () => showInfo('details');
1522
+ $('tab-lyrics').onclick = () => showInfo('lyrics');
1523
+ paintInfoTabs();
1524
+
1525
+ // The introduction's switch, or the written one itself, swaps it with
1526
+ // NetEase's prose; clamped prose opens in place.
1527
+ $('details').onclick = (event) => {
1528
+ const source = event.target.closest?.('[data-source]')?.dataset.source ?? (event.target.closest?.('.written') ? 'netease' : null);
1529
+ if (source) {
1530
+ introSource = source;
1531
+ repaintDetails({ keepScroll: true });
1532
+ return;
1533
+ }
1534
+ const prose = event.target.closest?.('.about .prose');
1535
+ if (prose) prose.classList.toggle('open');
1334
1536
  };
1335
1537
 
1538
+ async function loadDetails(id) {
1539
+ const request = ++detailsRequest;
1540
+ introSource = 'ai';
1541
+ const cached = detailsCache.get(id);
1542
+ if (cached) {
1543
+ paintDetails(cached);
1544
+ return;
1545
+ }
1546
+ $('details').innerHTML = `<p class="hint">${esc(t('loading'))}</p>`;
1547
+ try {
1548
+ const info = await api('/info/' + id);
1549
+ detailsCache.set(id, info);
1550
+ if (detailsCache.size > 30) detailsCache.delete(detailsCache.keys().next().value);
1551
+ if (request !== detailsRequest) return;
1552
+ paintDetails(info);
1553
+ } catch (error) {
1554
+ if (request !== detailsRequest) return;
1555
+ $('details').innerHTML = `<p class="hint">${esc(error.message)}</p>`;
1556
+ }
1557
+ }
1558
+
1559
+ /** Paint the shown track's details again: a language switch, an introduction, the switch. */
1560
+ function repaintDetails(options) {
1561
+ const info = detailsCache.get(detailsTrackId);
1562
+ if (info) paintDetails(info, options);
1563
+ }
1564
+
1565
+ /**
1566
+ * Ask for the shown track's introduction, once its details are painted.
1567
+ *
1568
+ * Lazy on purpose: a model call takes seconds, so it waits for the poll
1569
+ * after the details land — playback and the NetEase facts never wait on
1570
+ * it — and it is asked only for the track the visible pane shows.
1571
+ */
1572
+ async function loadIntro() {
1573
+ if (infoView !== 'details' || !detailsTrackId || !detailsCache.has(detailsTrackId)) return;
1574
+ const id = detailsTrackId;
1575
+ const key = `${id}:${LANG}`;
1576
+ if (intros.has(key)) return;
1577
+ intros.set(key, 'pending');
1578
+ if (intros.size > 60) intros.delete(intros.keys().next().value);
1579
+ let text = '';
1580
+ try {
1581
+ const answer = await api(`/intro/${id}?lang=${LANG}`);
1582
+ text = typeof answer?.text === 'string' ? answer.text : '';
1583
+ } catch { /* NetEase's prose stands in */ }
1584
+ intros.set(key, { text });
1585
+ introsUnavailable = !text;
1586
+ if (infoView === 'details' && detailsTrackId === id) repaintDetails({ keepScroll: true });
1587
+ }
1588
+
1589
+ /** NetEase dates are midnight in China; read them there, as YYYY-MM-DD. */
1590
+ function chinaDate(ms) {
1591
+ try {
1592
+ return new Date(ms).toLocaleDateString('sv-SE', { timeZone: 'Asia/Shanghai' });
1593
+ } catch {
1594
+ return new Date(ms).toISOString().slice(0, 10);
1595
+ }
1596
+ }
1597
+
1598
+ function paintDetails(info, { keepScroll = false } = {}) {
1599
+ const facts = [];
1600
+ const fact = (label, html) => facts.push(`<dt>${esc(t(label))}</dt><dd>${html}</dd>`);
1601
+ const chips = (list, kind = '') =>
1602
+ `<span class="chips">${list.map((item) => `<span class="chip ${kind}">${esc(item)}</span>`).join('')}</span>`;
1603
+
1604
+ const album = info.album ?? {};
1605
+ if (album.name) {
1606
+ const notes = [
1607
+ album.subType || album.type,
1608
+ album.publishTime ? chinaDate(album.publishTime) : '',
1609
+ album.company,
1610
+ album.size > 1 ? t('albumTracks', { n: album.size }) : '',
1611
+ ].filter(Boolean);
1612
+ fact('album', esc(album.name) + (notes.length ? ` <span class="muted">· ${esc(notes.join(' · '))}</span>` : ''));
1613
+ }
1614
+ // A genre is a path such as 流行-华语流行; its leaf names it.
1615
+ if (info.genres?.length) fact('genre', chips(info.genres.map((genre) => genre.split('-').pop()), 'genre'));
1616
+ if (info.tags?.length) fact('tags', chips(info.tags));
1617
+ const spoken = [info.language, info.bpm ? `${info.bpm} BPM` : ''].filter(Boolean);
1618
+ if (spoken.length) fact('language', esc(spoken.join(' · ')));
1619
+ if (info.featuredIn?.length) fact('featuredIn', esc(info.featuredIn.join(';')));
1620
+ if (info.awards?.length) fact('awards', esc(info.awards.join(';')));
1621
+
1622
+ const netease = [];
1623
+ // NetEase separates paragraphs with a line break, often indented with
1624
+ // full-width spaces; each becomes its own paragraph, spaced apart.
1625
+ const paragraphs = (text) =>
1626
+ String(text)
1627
+ .split(/\n+/)
1628
+ .map((line) => line.trim())
1629
+ .filter(Boolean)
1630
+ .map((line) => `<p>${esc(line)}</p>`)
1631
+ .join('');
1632
+ const section = (title, text, by = '') =>
1633
+ netease.push(
1634
+ `<section class="about"><h4>${esc(title)}</h4><div class="prose" title="${esc(t('expand'))}">${paragraphs(text)}</div>` +
1635
+ (by ? `<div class="by">${esc(by)}</div>` : '') +
1636
+ '</section>',
1637
+ );
1638
+ if (info.review?.text) section(t('aboutSong'), info.review.text, info.review.by ? t('reviewBy', { name: info.review.by }) : '');
1639
+ for (const artist of info.artists ?? []) if (artist.intro) section(artist.name, artist.intro);
1640
+ if (album.intro) section(t('aboutAlbum'), album.intro);
1641
+
1642
+ // The model's introduction leads; NetEase's prose is a click away. While
1643
+ // it is written, NetEase's prose shows if the model was last unavailable.
1644
+ const intro = intros.get(`${info.id}:${LANG}`);
1645
+ const written = typeof intro === 'object' && intro.text ? intro.text : '';
1646
+ const waiting = intro === undefined || intro === 'pending';
1647
+ const head = `<h4>${esc(t('intro'))}<span class="badge">AI</span></h4>`;
1648
+ const swap = (to, label) => `<button class="link source" type="button" data-source="${to}">${esc(t(label))}</button>`;
1649
+ let about;
1650
+ if (introSource === 'ai' && written) {
1651
+ about =
1652
+ `<section class="about">${head}<div class="written" title="${esc(t('introToNetease'))}">${paragraphs(written)}</div></section>` +
1653
+ (netease.length ? swap('netease', 'introFromNetease') : '');
1654
+ } else if (introSource === 'ai' && waiting && !introsUnavailable) {
1655
+ about =
1656
+ `<section class="about">${head}<p class="writing">${esc(t('introWriting'))}</p></section>` +
1657
+ (netease.length ? swap('netease', 'introFromNetease') : '');
1658
+ } else {
1659
+ about = (written ? swap('ai', 'introFromAi') : '') + netease.join('');
1660
+ }
1661
+
1662
+ const alias = info.alias?.length ? `<p class="alias">${esc(info.alias.join(' / '))}</p>` : '';
1663
+ const scrolled = $('details').scrollTop;
1664
+ $('details').innerHTML =
1665
+ facts.length || about || alias
1666
+ ? alias + (facts.length ? `<dl class="facts">${facts.join('')}</dl>` : '') + about
1667
+ : `<p class="hint">${esc(t('noDetails'))}</p>`;
1668
+ $('details').scrollTop = keepScroll ? scrolled : 0;
1669
+ }
1670
+
1336
1671
  async function loadLyrics(id) {
1337
1672
  const request = ++lyricRequest;
1338
1673
  lyric = null;
@@ -1367,7 +1702,7 @@
1367
1702
  }
1368
1703
 
1369
1704
  function paintLyrics() {
1370
- if (!lyric) return;
1705
+ if (!lyric || infoView !== 'lyrics') return;
1371
1706
  const at = positionMs();
1372
1707
  let active = -1;
1373
1708
  for (let index = 0; index < lyric.length; index++) {
@@ -1834,6 +2169,15 @@
1834
2169
  };
1835
2170
  $('dj-prompt').onchange = () => api('/dj', { method: 'POST', body: { prompt: $('dj-prompt').value, enabled: state?.dj?.enabled } }).then((data) => { state = data; render(); }).catch((error) => toast(error.message));
1836
2171
 
2172
+ // Not row-by-row removal, which reads each row as a dislike.
2173
+ $('queue-clear').onclick = async () => {
2174
+ try {
2175
+ state = await api('/queue', { method: 'POST', body: { action: 'clear', keepCurrent: true } });
2176
+ render();
2177
+ pokeEngine();
2178
+ } catch (error) { toast(failureText(error)); }
2179
+ };
2180
+
1837
2181
  $('queue').onclick = async (event) => {
1838
2182
  const like = event.target.closest('[data-like]');
1839
2183
  const jump = event.target.closest('[data-jump]')?.dataset.jump;
@@ -1873,6 +2217,7 @@
1873
2217
  paintStaticIcons();
1874
2218
  applyLocale();
1875
2219
  watchShellLocale();
2220
+ syncShellTheme();
1876
2221
  refresh();
1877
2222
  setInterval(refresh, 1500);
1878
2223
  void loadModelPicker();
package/lib/router.js CHANGED
@@ -21,12 +21,19 @@
21
21
 
22
22
  import { Readable } from 'node:stream';
23
23
 
24
+ import { TtlCache } from './cache.js';
24
25
  import { DEFAULT_LEVEL, LEVELS, isLevel } from './netease.js';
25
26
  import { BOOST_DIRECTIONS, TASTE_LEVELS } from './session.js';
26
27
 
27
28
  /** Resolved CDN URLs are reused for this long (they live 20 minutes). */
28
29
  const URL_CACHE_MS = 15 * 60 * 1000;
29
30
 
31
+ /** Song details are kept this long: a wiki or an introduction is edited rarely. */
32
+ const INFO_TTL_MS = 6 * 60 * 60 * 1000;
33
+
34
+ /** A written introduction is kept longer: each one costs a model call. */
35
+ const INTRO_TTL_MS = 7 * 24 * 60 * 60 * 1000;
36
+
30
37
  /**
31
38
  * Version of the page/engine boundary, advertised on `/health`.
32
39
  *
@@ -129,6 +136,15 @@ export class MusicRouter {
129
136
  this.pendingUrls = new Map();
130
137
  /** What the last stream request actually resolved, for the UI and health. */
131
138
  this.lastAudio = null;
139
+ /** Song details for the panel, which barely change; each costs up to six requests. */
140
+ this.infoCache = new TtlCache({ maxEntries: 200 });
141
+ /** Model-written introductions, per track and language. */
142
+ this.introCache = new TtlCache({ maxEntries: 400 });
143
+ }
144
+
145
+ /** A song's details, shared by the details pane and the introduction written from them. */
146
+ songInfo(id) {
147
+ return this.infoCache.get(`info:${id}`, INFO_TTL_MS, () => this.api.songInfo(id));
132
148
  }
133
149
 
134
150
  /**
@@ -527,14 +543,18 @@ export class MusicRouter {
527
543
  return sendJson(res, 200, await this.snapshot());
528
544
  }
529
545
  if (route === '/queue' && method === 'POST') {
530
- const { action, tracks, index } = await readJson(req);
546
+ const { action, tracks, index, keepCurrent } = await readJson(req);
531
547
  let removal = null;
532
548
  if (action === 'replace' && Array.isArray(tracks)) this.player.setQueue(tracks, { source: 'user' });
533
549
  else if (action === 'append' && Array.isArray(tracks)) this.player.append(tracks, { source: 'user' });
534
550
  else if (action === 'insert' && Array.isArray(tracks)) this.player.insertNext(tracks, { source: 'user' });
535
551
  else if (action === 'remove' || action === 'jump') removal = this.#queueAction(action, index);
536
- else if (action === 'clear') this.player.clear();
537
- else return sendJson(res, 400, { error: `unknown queue action "${action}"` });
552
+ else if (action === 'clear') {
553
+ // Unlike `remove`, clearing is housekeeping, not a judgement: nothing is rated.
554
+ if (keepCurrent) this.player.clearKeepingCurrent();
555
+ else this.player.clear();
556
+ this.player.requestExtension();
557
+ } else return sendJson(res, 400, { error: `unknown queue action "${action}"` });
538
558
  // Answer with the queue as it now stands, but record the judgement first:
539
559
  // the snapshot's hearts should already show it.
540
560
  if (removal?.dropped && removal.wasCurrent) await this.removeFromQueue(removal.track, true);
@@ -561,6 +581,32 @@ export class MusicRouter {
561
581
  const id = Number(route.slice('/lyric/'.length));
562
582
  return sendJson(res, 200, await this.api.lyric(id));
563
583
  }
584
+ if (route.startsWith('/info/') && method === 'GET') {
585
+ const id = Number(route.slice('/info/'.length));
586
+ if (!Number.isInteger(id) || id <= 0) return sendJson(res, 400, { error: 'invalid track id' });
587
+ return sendJson(res, 200, await this.songInfo(id));
588
+ }
589
+ /**
590
+ * A model-written introduction to the song. Always 200: with no model, or a
591
+ * failed one, `text` is empty and the panel shows NetEase's own prose. Only
592
+ * a written one is cached, so a model set up later is used at once.
593
+ */
594
+ if (route.startsWith('/intro/') && method === 'GET') {
595
+ const id = Number(route.slice('/intro/'.length));
596
+ if (!Number.isInteger(id) || id <= 0) return sendJson(res, 400, { error: 'invalid track id' });
597
+ const lang = query.get('lang') === 'zh' ? 'zh' : 'en';
598
+ try {
599
+ const intro = await this.introCache.get(`intro:${id}:${lang}`, INTRO_TTL_MS, async () => {
600
+ const written = await this.dj.introduce(await this.songInfo(id), { lang });
601
+ if (!written) throw new Error('no model route is available');
602
+ return written;
603
+ });
604
+ return sendJson(res, 200, intro);
605
+ } catch (error) {
606
+ this.logger?.debug?.(`[music] no introduction for ${id}: ${error.message}`);
607
+ return sendJson(res, 200, { text: '', reason: error.message });
608
+ }
609
+ }
564
610
  if (route === '/charts' && method === 'GET') {
565
611
  return sendJson(res, 200, await this.api.toplists());
566
612
  }
@@ -707,7 +753,7 @@ export class MusicRouter {
707
753
  `[music] DJ model route set to ${this.dj.model.provider ?? '(none)'}/${this.dj.model.model ?? '(none)'} from the player`,
708
754
  );
709
755
  }
710
- if (prompt !== undefined) this.store.updateSettings({ djPrompt: String(prompt) });
756
+ if (prompt !== undefined) this.dj.setPrompt(prompt);
711
757
  if (enabled !== undefined) this.dj.setEnabled(enabled);
712
758
  if (replan || (enabled && this.player.queue.length === 0)) {
713
759
  // Planning is slow; answer immediately and let the panel poll the result.
package/lib/session.js CHANGED
@@ -40,6 +40,9 @@ const BOOST_MAX_MINUTES = 12 * 60;
40
40
  /** Boosts held at once; the oldest goes first. */
41
41
  const MAX_BOOSTS = 10;
42
42
 
43
+ /** Queue entries kept across a restart; the oldest played ones go first. */
44
+ const MAX_SAVED_QUEUE = 500;
45
+
43
46
  /** QR codes are refreshed before the API reports them expired. */
44
47
  const QR_TTL_MS = 110_000;
45
48
 
@@ -94,6 +97,11 @@ function emptyState() {
94
97
  * passing mood does not become a standing preference.
95
98
  */
96
99
  boosts: [],
100
+ /**
101
+ * The player's queue and cursor, so a restart picks up where it left off
102
+ * instead of waiting on the DJ's first plan.
103
+ */
104
+ queue: { tracks: [], index: -1 },
97
105
  };
98
106
  }
99
107
 
@@ -205,6 +213,19 @@ export class SessionStore {
205
213
  return this.state.settings;
206
214
  }
207
215
 
216
+ // ----------------------------------------------------------------- queue
217
+
218
+ get savedQueue() {
219
+ return this.state.queue ?? { tracks: [], index: -1 };
220
+ }
221
+
222
+ /** Keep the queue for the next run, dropping the oldest played tracks past the bound. */
223
+ saveQueue(tracks, index) {
224
+ const drop = Math.max(Math.min(tracks.length - MAX_SAVED_QUEUE, index), 0);
225
+ this.state.queue = { tracks: tracks.slice(drop, drop + MAX_SAVED_QUEUE), index: index - drop };
226
+ this.touch();
227
+ }
228
+
208
229
  // --------------------------------------------------------------- history
209
230
 
210
231
  /**
package/lib/state.js CHANGED
@@ -249,6 +249,31 @@ export class Player {
249
249
  return this.snapshot();
250
250
  }
251
251
 
252
+ /**
253
+ * Empty the queue but for the track at the cursor, which plays on
254
+ * undisturbed: its play stays open, so it is neither ended nor restarted.
255
+ */
256
+ clearKeepingCurrent() {
257
+ const current = this.current();
258
+ if (!current) return this.clear();
259
+ this.queue = [current];
260
+ this.index = 0;
261
+ this.bump({ transport: true });
262
+ return this.snapshot();
263
+ }
264
+
265
+ /**
266
+ * Put back a queue saved by an earlier run, paused at its cursor. Nothing is
267
+ * finished or bumped: no play was open, and nobody is subscribed yet.
268
+ */
269
+ restore({ tracks, index } = {}) {
270
+ const queue = Array.isArray(tracks) ? tracks.filter((track) => track?.id) : [];
271
+ if (queue.length === 0) return;
272
+ this.queue = queue;
273
+ this.index = Math.min(Math.max(Number(index) || 0, 0), queue.length - 1);
274
+ this.playing = false;
275
+ }
276
+
252
277
  // --------------------------------------------------------------- transport
253
278
 
254
279
  /** Index to advance to, honouring the repeat/shuffle mode. */
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doitian/dsh-music",
3
- "version": "0.1.9",
3
+ "version": "0.1.10",
4
4
  "description": "NetEase Cloud Music (music.163.com) player and AI DJ for DeepSeek Harness: a sidebar page with in-app playback, QR sign-in, and agent tools that curate the queue.",
5
5
  "keywords": [
6
6
  "dsh",