@doitian/dsh-music 0.1.5 → 0.1.6

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/cordis.patch.yml CHANGED
@@ -9,7 +9,8 @@
9
9
  # apiPrefix route prefix (default `music`) — keep it `music` unless
10
10
  # you also rebuild the browser half.
11
11
  # dataDir where session.json lives (default $DSH_HOME/music).
12
- # audioLevel exhigh (320 kbps, default) | standard | higher | lossless
12
+ # audioLevel exhigh (320 kbps, default); also standard, higher,
13
+ # lossless, hires, jymaster, dolby, sky, jyeffect.
13
14
  # requestTimeoutMs NetEase request deadline (default 15000).
14
15
  # dj.provider model route for the AI DJ's model tier, e.g. opencode-go.
15
16
  # dj.model exact model id, e.g. deepseek-v4.1-flash.
@@ -23,14 +24,17 @@
23
24
  # conversation.
24
25
  #
25
26
  # Route resolution, highest first: the player's picker -> `dj.provider`/`dj.model`
26
- # -> the deployment's own `agent-default-model` (the model the agent loop runs
27
- # on, which is why "use my session model" needs no configuration) -> discovery,
28
- # whose first row is arbitrary. The DJ is not an agent and starts none: each
29
- # plan is one stateless leaf call, so there is no session to rotate or dispose.
27
+ # -> the session's default model (`agent-default-model`, which is why "use my
28
+ # session model" needs no configuration) -> discovery, whose first row is
29
+ # arbitrary. Only the choice of model is shared with the session: the DJ is not
30
+ # an agent and starts none. It makes stateless leaf calls — one to curate each
31
+ # plan, and one to rewrite a mood brief into search terms the first time that
32
+ # brief is seen — so there is no session to rotate or dispose.
30
33
  #
31
- # Without `dj.provider`/`dj.model` the DJ still works: it falls back to scoring
32
- # similar songs, the daily recommendations and the charts by the listener's
33
- # liked artists, novelty and feedback.
34
+ # With no model route at all the DJ still works: it scores its candidates —
35
+ # similar songs, personal FM, rested likes, the daily recommendations, the
36
+ # charts and any mood brief — by brief match, artist affinity, and the
37
+ # listener's likes, dislikes and skips.
34
38
  - insert:
35
39
  - id: music
36
40
  name: '@doitian/dsh-music'
package/lib/dj.js CHANGED
@@ -32,6 +32,7 @@
32
32
  import { createHash, randomUUID } from 'node:crypto';
33
33
 
34
34
  import { Pacer, TtlCache, sampleInOrder } from './cache.js';
35
+ import { isHeard } from './session.js';
35
36
 
36
37
  /**
37
38
  * Render a model-tier failure so its stable code survives.
@@ -63,8 +64,17 @@ const MAX_SEEDS = 4;
63
64
  /** How far back in the history a seed may come from, so seeds stay current. */
64
65
  const SEED_HISTORY = 20;
65
66
 
66
- /** Liked tracks offered back to the pool per plan. */
67
- const LIKED_SAMPLE = 6;
67
+ /** Seeds taken from what was played; the rest come from likes. */
68
+ const HISTORY_SEEDS = 2;
69
+
70
+ /** The newest likes whose artists inform the taste picture. */
71
+ const LIKED_TASTE = 200;
72
+
73
+ /** A liked track's artist outweighs a play of it: a like is a deliberate act. */
74
+ const LIKED_ARTIST_WEIGHT = 2;
75
+
76
+ /** Track details per lookup; one oversized id list is a request NetEase may refuse. */
77
+ const DETAIL_BATCH = 50;
68
78
 
69
79
  /** A liked track played more recently than this is not offered back yet. */
70
80
  const LIKED_REST_MS = 3 * 24 * 60 * 60 * 1000;
@@ -80,7 +90,14 @@ const ORIGINS = ['prompt', 'liked', 'fm', 'similar', 'daily', 'new', 'chart'];
80
90
  * no single one can crowd discovery out of the pool; without a brief they sum
81
91
  * to 48, and a brief adds up to 23 that match it.
82
92
  */
83
- const QUOTA = { promptPlaylists: 15, promptSongs: 8, similar: 14, daily: 8, new: 6, chart: 8 };
93
+ const QUOTA = { promptPlaylists: 15, promptSongs: 8, similar: 14, liked: 6, daily: 8, new: 6, chart: 8 };
94
+
95
+ /**
96
+ * Signed in, the account's own signals — the daily list, likes, FM — know the
97
+ * listener; the charts and the new-song feed only know the market. They keep a
98
+ * few slots for discovery and give the rest to the personal sources.
99
+ */
100
+ const SIGNED_IN_QUOTA = { ...QUOTA, liked: 9, daily: 12, new: 3, chart: 4 };
84
101
 
85
102
  const HOUR = 60 * 60 * 1000;
86
103
 
@@ -366,23 +383,31 @@ export class AiDj {
366
383
 
367
384
  /**
368
385
  * The tracks similarity expands from: what is playing and what was recently
369
- * heard through, topped up with likes when the history is thin.
386
+ * heard through, and random likes — each filling in when the other is thin.
370
387
  *
371
388
  * A rejected track never seeds. The ✕ records a dislike and then moves on, so
372
389
  * seeding from the raw history would make the very next plan fetch more of
373
390
  * exactly what was just turned down.
374
391
  */
375
392
  #seeds(digest) {
376
- const rejected = (id) => this.store.taste(id) === 'disliked' || digest.skipCounts.has(id);
393
+ const usable = (id) => id && this.store.taste(id) !== 'disliked' && !digest.skipCounts.has(id);
394
+ const heard = [
395
+ this.player.current()?.id,
396
+ ...this.store.state.history.slice(0, SEED_HISTORY).filter(isHeard).map((entry) => entry.id),
397
+ ].filter(usable);
398
+ const liked = sampleInOrder(this.store.feedback.likes.filter(usable), MAX_SEEDS);
377
399
  const seeds = [];
378
- const offer = (id) => {
379
- if (seeds.length < MAX_SEEDS && id && !rejected(id) && !seeds.includes(id)) seeds.push(id);
400
+ const take = (ids, limit) => {
401
+ for (const id of ids) {
402
+ if (seeds.length >= limit) return;
403
+ if (!seeds.includes(id)) seeds.push(id);
404
+ }
380
405
  };
381
- offer(this.player.current()?.id);
382
- for (const entry of this.store.state.history.slice(0, SEED_HISTORY)) {
383
- if (!entry.skipped) offer(entry.id);
384
- }
385
- for (const id of this.store.feedback.likes) offer(id);
406
+ // Half from what is playing and was heard, half from likes: seeding only
407
+ // from plays lets the DJ's own picks decide what it picks next.
408
+ take(heard, HISTORY_SEEDS);
409
+ take(liked, MAX_SEEDS);
410
+ take(heard, MAX_SEEDS);
386
411
  return seeds;
387
412
  }
388
413
 
@@ -397,7 +422,7 @@ export class AiDj {
397
422
  this.store.state.history.filter((entry) => (entry.at ?? 0) > restedSince).map((entry) => entry.id),
398
423
  );
399
424
  const ids = this.store.feedback.likes.filter((id) => !excluded.has(id) && !heardRecently.has(id));
400
- return sampleInOrder(ids, LIKED_SAMPLE);
425
+ return sampleInOrder(ids, this.#quota().liked);
401
426
  }
402
427
 
403
428
  /**
@@ -428,11 +453,15 @@ export class AiDj {
428
453
  liked: settled(this.#tracksByIds(this.#likedSample(excluded))),
429
454
  fm: settled(this.#fmTracks()),
430
455
  similar: settled(this.#similarTracks(seeds, excluded)),
431
- daily: settled(this.#feedTracks(`daily:${this.#account()}`, TTL.daily, () => this.api.recommendSongs(30), QUOTA.daily, excluded)),
432
- new: settled(this.#feedTracks('new', TTL.new, () => this.api.personalizedNewsongs(30), QUOTA.new, excluded)),
456
+ daily: settled(this.#feedTracks(`daily:${this.#account()}`, TTL.daily, () => this.api.recommendSongs(30), this.#quota().daily, excluded)),
457
+ new: settled(this.#feedTracks('new', TTL.new, () => this.api.personalizedNewsongs(30), this.#quota().new, excluded)),
433
458
  chart: settled(this.#chartTracks(excluded)),
434
459
  };
435
460
 
461
+ // The newest likes, for the taste picture; cached per track, so only new
462
+ // likes cost a lookup after the first plan.
463
+ const likedTaste = this.#tracksByIds(this.store.feedback.likes.slice(0, LIKED_TASTE)).catch(() => []);
464
+
436
465
  const pool = [];
437
466
  const seen = new Set();
438
467
  for (const origin of ORIGINS) {
@@ -447,7 +476,11 @@ export class AiDj {
447
476
  const covered = trimmed.some((track) => !track.picUrl)
448
477
  ? await this.pacer.run(() => this.api.withCovers(trimmed)).catch(() => trimmed)
449
478
  : trimmed;
450
- return { pool: covered, digest, terms: briefing ? (await briefing).terms : [] };
479
+ return {
480
+ pool: covered,
481
+ digest: this.#withLikes(digest, await likedTaste),
482
+ terms: briefing ? (await briefing).terms : [],
483
+ };
451
484
  }
452
485
 
453
486
  /**
@@ -465,14 +498,42 @@ export class AiDj {
465
498
  async #tracksByIds(ids) {
466
499
  if (ids.length === 0 || !this.api.songDetail) return [];
467
500
  const missing = ids.filter((id) => this.cache.peek(`track:${id}`) === undefined);
468
- if (missing.length > 0) {
469
- for (const track of await this.pacer.run(() => this.api.songDetail(missing))) {
501
+ for (let offset = 0; offset < missing.length; offset += DETAIL_BATCH) {
502
+ const batch = missing.slice(offset, offset + DETAIL_BATCH);
503
+ for (const track of await this.pacer.run(() => this.api.songDetail(batch))) {
470
504
  if (track?.id) this.cache.set(`track:${track.id}`, track, TTL.track);
471
505
  }
472
506
  }
473
507
  return ids.map((id) => this.cache.peek(`track:${id}`)).filter(Boolean);
474
508
  }
475
509
 
510
+ /** The pool's quotas: personal sources take over once there is an account. */
511
+ #quota() {
512
+ return this.api.authenticated ? SIGNED_IN_QUOTA : QUOTA;
513
+ }
514
+
515
+ /**
516
+ * Fold the account's likes into the taste picture.
517
+ *
518
+ * The history only knows what played through this plugin, and much of that
519
+ * the DJ chose itself; the likes are what the listener chose, anywhere. So
520
+ * a liked track's artists count toward the favourites — twice what a play
521
+ * counts — and the model is shown liked songs by name, not only the few that
522
+ * happen to be in the history.
523
+ */
524
+ #withLikes(digest, liked) {
525
+ if (liked.length === 0) return digest;
526
+ const scores = this.store.heardArtists();
527
+ for (const track of liked) {
528
+ for (const artist of track.artists ?? []) scores.set(artist, (scores.get(artist) ?? 0) + LIKED_ARTIST_WEIGHT);
529
+ }
530
+ return {
531
+ ...digest,
532
+ topArtists: [...scores].sort((a, b) => b[1] - a[1]).slice(0, 8).map(([artist]) => artist),
533
+ liked: sampleInOrder(liked, 15).map((track) => `${track.name} — ${(track.artists ?? []).join('/')}`),
534
+ };
535
+ }
536
+
476
537
  /** A cached list, sampled down to its quota of eligible tracks. */
477
538
  async #feedTracks(key, ttlMs, load, quota, excluded) {
478
539
  const tracks = await this.cache.get(key, ttlMs, () => this.pacer.run(load));
@@ -500,8 +561,8 @@ export class AiDj {
500
561
  );
501
562
  const eligible = (tracks) => (tracks ?? []).filter((track) => track?.id && !excluded.has(track.id));
502
563
  const [first = [], ...rest] = lists.map(eligible);
503
- const lead = first.slice(0, QUOTA.similar);
504
- return [...lead, ...sampleInOrder(rest.flat(), QUOTA.similar - lead.length)];
564
+ const lead = first.slice(0, this.#quota().similar);
565
+ return [...lead, ...sampleInOrder(rest.flat(), this.#quota().similar - lead.length)];
505
566
  }
506
567
 
507
568
  /**
@@ -543,7 +604,7 @@ export class AiDj {
543
604
  */
544
605
  async #chartTracks(excluded) {
545
606
  const charts = await Promise.all(CHARTS.map((id) => this.#playlist(id, TTL.chart).catch(() => null)));
546
- return this.#samplePlaylists(charts.filter(Boolean), QUOTA.chart, excluded);
607
+ return this.#samplePlaylists(charts.filter(Boolean), this.#quota().chart, excluded);
547
608
  }
548
609
 
549
610
  /**
@@ -559,7 +620,7 @@ export class AiDj {
559
620
  `songs:${terms[0]}`,
560
621
  TTL.search,
561
622
  () => this.api.searchSongs(terms[0], { limit: 30 }).then((result) => result.tracks),
562
- QUOTA.promptSongs,
623
+ this.#quota().promptSongs,
563
624
  excluded,
564
625
  ).catch(() => []);
565
626
  const playlists = (async () => {
@@ -586,7 +647,7 @@ export class AiDj {
586
647
  }
587
648
  const ids = [...chosen.keys()].slice(0, BRIEF_PLAYLISTS);
588
649
  const loaded = await Promise.all(ids.map((id) => this.#playlist(id, TTL.playlist).catch(() => null)));
589
- return this.#samplePlaylists(loaded.filter(Boolean), QUOTA.promptPlaylists, excluded);
650
+ return this.#samplePlaylists(loaded.filter(Boolean), this.#quota().promptPlaylists, excluded);
590
651
  })().catch(() => []);
591
652
  // Playlist tracks first: they are the stronger match for a mood.
592
653
  return { tracks: [...(await playlists), ...(await songs)], terms };
@@ -721,10 +782,10 @@ export class AiDj {
721
782
  * Decide which provider route to call.
722
783
  *
723
784
  * An explicit pin always wins. Otherwise the deployment's own model selection
724
- * is inherited — `agent-default-model`, which is the same choice the composer
725
- * picker writes and therefore the model the agent loop runs on — so the
726
- * session model and the DJ's model are two separable decisions that agree
727
- * by default. Only when neither exists does discovery run.
785
+ * is inherited — `agent-default-model`, the same choice the composer picker
786
+ * writes and new conversations start on — so the session model and the DJ's
787
+ * model are two separable decisions that agree by default. Only the choice
788
+ * is inherited; the call itself stays a leaf call. Only when neither exists does discovery run.
728
789
  *
729
790
  * Discovery is a convenience, not a recommendation: the catalogue's first
730
791
  * entry is arbitrary, so pinning both fields is the only way to know which
@@ -922,11 +983,7 @@ export class AiDj {
922
983
  #rank({ pool, digest, count, follows }) {
923
984
  const favourites = new Set(digest.topArtists);
924
985
  const currentArtists = new Set(this.player.current()?.artists ?? []);
925
- const playedArtists = new Map();
926
- for (const entry of this.store.state.history.slice(0, 60)) {
927
- if (entry.skipped) continue;
928
- for (const artist of entry.artists ?? []) playedArtists.set(artist, (playedArtists.get(artist) ?? 0) + 1);
929
- }
986
+ const playedArtists = this.store.heardArtists(60);
930
987
 
931
988
  const scored = pool.map((track) => {
932
989
  let score = Math.random() * 0.8;
@@ -1037,7 +1094,7 @@ export class AiDj {
1037
1094
  // `play: false` preserves whatever the listener chose, so a top-up while
1038
1095
  // paused does not start playback, while a queue refilled after the last
1039
1096
  // track ended still resumes because `playing` was already true.
1040
- this.player.append(plan.tracks, { source: plan.source, play: false });
1097
+ this.player.append(plan.tracks, { source: plan.source, play: false, queuedBy: 'dj' });
1041
1098
  this.player.dj = {
1042
1099
  ...this.player.dj,
1043
1100
  busy: false,
@@ -1076,7 +1133,7 @@ export class AiDj {
1076
1133
  // The batch replaces the queue, so nothing precedes its first track.
1077
1134
  const plan = await this.plan({ prompt: prompt ?? this.store.settings.djPrompt ?? '', count, follows: null });
1078
1135
  if (plan.tracks.length > 0) {
1079
- this.player.setQueue(plan.tracks, { startIndex: 0, play: true, source: plan.source });
1136
+ this.player.setQueue(plan.tracks, { startIndex: 0, play: true, source: plan.source, queuedBy: 'dj' });
1080
1137
  this.player.dj.lastPlanAt = Date.now();
1081
1138
  this.player.dj.lastPlan = {
1082
1139
  source: plan.source,
package/lib/index.js CHANGED
@@ -149,8 +149,9 @@ export function apply(ctx, config = {}) {
149
149
  * The deployment's default model selection: the route a freshly created agent
150
150
  * starts on, and the same choice the composer/command model picker writes.
151
151
  *
152
- * This is the seam that makes the agent-loop model and the DJ's model two
153
- * separate decisions. `agent-default-model` owns the first; `dj.provider` /
152
+ * This is the seam that makes the session's model and the DJ's model two
153
+ * separate decisions; only the choice is shared, since the DJ calls its model
154
+ * directly rather than through an agent. `agent-default-model` owns the first; `dj.provider` /
154
155
  * `dj.model` owns the second; and the DJ follows the session model when the
155
156
  * plugin pins nothing, instead of picking an arbitrary first route.
156
157
  */
@@ -224,13 +225,17 @@ export function apply(ctx, config = {}) {
224
225
  .catch((error) => logger.warn(`[music] account check failed: ${error.message}`));
225
226
 
226
227
  // ---------------------------------------------------------- history + DJ
228
+ // The one place a play is recorded: whenever the current track changes, by
229
+ // whatever path. Recording it again where the queue is set counted every
230
+ // played track twice, and an appended one as a play of the current track.
227
231
  let lastRecorded = null;
228
232
  player.subscribe(() => {
229
233
  const current = player.current();
230
234
  if (!current || current.id === lastRecorded) return;
231
235
  lastRecorded = current.id;
232
- store.recordPlay(current);
236
+ store.recordPlay(current, { tentative: current.queuedBy === 'dj' });
233
237
  });
238
+ player.onHeard = (track) => store.confirmPlay(track.id);
234
239
 
235
240
  // A periodic sweep catches the cases the track-end hook misses: a paused
236
241
  // panel, a failed track, or a DJ that was switched on with a short queue.
@@ -391,7 +396,6 @@ export function apply(ctx, config = {}) {
391
396
  if (mode === 'append') player.append(tracks, { source: 'agent' });
392
397
  else if (mode === 'next') player.insertNext(tracks, { source: 'agent' });
393
398
  else player.setQueue(tracks, { startIndex: 0, play: true, source: 'agent' });
394
- store.recordPlay(player.current() ?? tracks[0]);
395
399
 
396
400
  const summary = player.summary();
397
401
  return {
package/lib/panel.html CHANGED
@@ -1551,10 +1551,9 @@
1551
1551
  await sendTaste(track, 'none', event?.currentTarget);
1552
1552
  return;
1553
1553
  }
1554
- if (await sendTaste(track, 'disliked', event?.currentTarget)) {
1555
- toast(t('disliked'));
1556
- control({ action: 'next' });
1557
- }
1554
+ // The host takes a disliked track out of the queue, and moves on when it
1555
+ // was playing; pressing next here as well would skip a second track.
1556
+ if (await sendTaste(track, 'disliked', event?.currentTarget)) toast(t('disliked'));
1558
1557
  };
1559
1558
 
1560
1559
  $('dj-toggle').onclick = async () => {
package/lib/router.js CHANGED
@@ -389,6 +389,14 @@ export class MusicRouter {
389
389
  }
390
390
 
391
391
  this.store.setTaste(id, level);
392
+ // A disliked track leaves the queue wherever it sits — the playing one
393
+ // too, which moves playback on to the next. Every dislike comes through
394
+ // here, so the transport's ✕, the legacy feedback route and a row removal
395
+ // all agree, and the page no longer presses next on top of it.
396
+ if (level === 'disliked') {
397
+ const at = this.player.queue.findIndex((track) => track.id === id);
398
+ if (at >= 0) this.player.remove(at);
399
+ }
392
400
  return { ok: true, id, level };
393
401
  }
394
402
 
@@ -485,7 +493,6 @@ export class MusicRouter {
485
493
  return sendJson(res, 400, { error: 'tracks must be a non-empty array' });
486
494
  }
487
495
  this.player.setQueue(tracks, { startIndex, source: 'user' });
488
- this.store.recordPlay(this.player.current() ?? tracks[0]);
489
496
  return sendJson(res, 200, await this.snapshot());
490
497
  }
491
498
  if (route === '/queue' && method === 'POST') {
package/lib/session.js CHANGED
@@ -74,6 +74,14 @@ function emptyState() {
74
74
  };
75
75
  }
76
76
 
77
+ /**
78
+ * Whether a play is evidence of taste: neither skipped, nor a DJ pick still
79
+ * waiting to be heard through. Plays recorded before either flag existed count.
80
+ */
81
+ export function isHeard(entry) {
82
+ return !entry.skipped && !entry.tentative;
83
+ }
84
+
77
85
  /**
78
86
  * JSON-document store for the plugin's data directory.
79
87
  *
@@ -177,38 +185,60 @@ export class SessionStore {
177
185
  // --------------------------------------------------------------- history
178
186
 
179
187
  /**
180
- * Record a play and return the durable taste picture the DJ reasons over.
188
+ * Record a play.
189
+ *
190
+ * A `tentative` play is one the DJ chose. It counts as heard — and so as
191
+ * taste — only once {@link confirmPlay} says the listener got past the skip
192
+ * window. Otherwise every track the DJ queued would read as approval of
193
+ * itself, and a few batches of charts would teach the DJ the charts are
194
+ * what the listener likes. It still counts as played for avoiding repeats.
195
+ *
181
196
  * @param {{id: number, name: string, artists: string[]}} track
197
+ * @param {{tentative?: boolean}} [options]
182
198
  */
183
- recordPlay(track) {
199
+ recordPlay(track, { tentative = false } = {}) {
184
200
  this.state.history.unshift({
185
201
  id: track.id,
186
202
  name: track.name,
187
203
  artists: track.artists ?? [],
188
204
  at: Date.now(),
205
+ ...(tentative ? { tentative: true } : {}),
189
206
  });
190
207
  if (this.state.history.length > MAX_HISTORY) this.state.history.length = MAX_HISTORY;
191
208
  this.touch();
192
209
  }
193
210
 
211
+ /** The listener heard a tentative play through: it now counts as taste. */
212
+ confirmPlay(trackId) {
213
+ const play = this.state.history.find((entry) => entry.id === Number(trackId));
214
+ if (!play?.tentative) return;
215
+ delete play.tentative;
216
+ this.touch();
217
+ }
218
+
194
219
  /** Recent track ids, newest first — used to avoid repeats. */
195
220
  recentIds(limit = 50) {
196
221
  return this.state.history.slice(0, limit).map((entry) => entry.id);
197
222
  }
198
223
 
199
- /** Most-played artists, most frequent first. A skipped play is not a play. */
224
+ /** Most-played artists, most frequent first. Only plays heard through count. */
200
225
  topArtists(limit = 8) {
201
- const counts = new Map();
202
- for (const entry of this.state.history.slice(0, 150)) {
203
- if (entry.skipped) continue;
204
- for (const artist of entry.artists) counts.set(artist, (counts.get(artist) ?? 0) + 1);
205
- }
206
- return [...counts.entries()]
226
+ return [...this.heardArtists().entries()]
207
227
  .sort((a, b) => b[1] - a[1])
208
228
  .slice(0, limit)
209
229
  .map(([artist]) => artist);
210
230
  }
211
231
 
232
+ /** Artist → plays heard through, among the recent history. */
233
+ heardArtists(window = 150) {
234
+ const counts = new Map();
235
+ for (const entry of this.state.history.slice(0, window)) {
236
+ if (!isHeard(entry)) continue;
237
+ for (const artist of entry.artists ?? []) counts.set(artist, (counts.get(artist) ?? 0) + 1);
238
+ }
239
+ return counts;
240
+ }
241
+
212
242
  /**
213
243
  * One track's taste level: `liked`, `disliked`, or `none` (never rated).
214
244
  * @param {number|string} trackId
package/lib/state.js CHANGED
@@ -33,6 +33,14 @@ const SEEK_EPSILON_MS = 1_000;
33
33
  const SKIP_WINDOW_MS = 30_000;
34
34
  const SKIP_WINDOW_FRACTION = 0.25;
35
35
 
36
+ /**
37
+ * Mark who queued a track. A track the DJ chose has to be heard through
38
+ * before it counts as taste; one the listener chose counts at once.
39
+ */
40
+ function tag(track, queuedBy) {
41
+ return queuedBy && track?.id ? { ...track, queuedBy } : track;
42
+ }
43
+
36
44
  export class Player {
37
45
  /**
38
46
  * @param {object} [options]
@@ -82,6 +90,14 @@ export class Player {
82
90
  * @type {((track: object) => void) | undefined}
83
91
  */
84
92
  this.onSkip = undefined;
93
+ /**
94
+ * Called once with the current track when the listener has heard it
95
+ * through: past the skip window, or to its end.
96
+ * @type {((track: object) => void) | undefined}
97
+ */
98
+ this.onHeard = undefined;
99
+ /** The track `onHeard` was last called for, so it fires once per play. */
100
+ this.heardId = null;
85
101
  }
86
102
 
87
103
  /** Subscribe to state changes. @returns {() => void} unsubscribe */
@@ -117,8 +133,12 @@ export class Player {
117
133
  }
118
134
 
119
135
  /** Replace the whole queue. `startIndex` selects what plays first. */
120
- setQueue(tracks, { startIndex = 0, play = true, source } = {}) {
121
- const normalized = tracks.map((track) => normalizeTrack(track) ?? track).filter((track) => track?.id);
136
+ setQueue(tracks, { startIndex = 0, play = true, source, queuedBy } = {}) {
137
+ const normalized = tracks
138
+ .map((track) => normalizeTrack(track) ?? track)
139
+ .filter((track) => track?.id)
140
+ .map((track) => tag(track, queuedBy));
141
+ this.heardId = null;
122
142
  this.queue = normalized;
123
143
  this.index = normalized.length === 0 ? -1 : Math.min(Math.max(startIndex, 0), normalized.length - 1);
124
144
  this.pendingSeek = null;
@@ -130,11 +150,11 @@ export class Player {
130
150
  }
131
151
 
132
152
  /** Append tracks, de-duplicating against the queue tail. */
133
- append(tracks, { source, play = true } = {}) {
153
+ append(tracks, { source, play = true, queuedBy } = {}) {
134
154
  const existing = new Set(this.queue.map((track) => track.id));
135
155
  const added = [];
136
156
  for (const raw of tracks) {
137
- const track = normalizeTrack(raw) ?? raw;
157
+ const track = tag(normalizeTrack(raw) ?? raw, queuedBy);
138
158
  if (!track?.id || existing.has(track.id)) continue;
139
159
  existing.add(track.id);
140
160
  added.push(track);
@@ -183,14 +203,17 @@ export class Player {
183
203
  /** Remove one queue position. */
184
204
  remove(index) {
185
205
  if (index < 0 || index >= this.queue.length) return this.snapshot();
206
+ const wasCurrent = index === this.index;
186
207
  this.queue.splice(index, 1);
187
208
  if (this.queue.length === 0) {
188
209
  this.index = -1;
189
210
  this.playing = false;
190
211
  } else if (index < this.index) {
191
212
  this.index -= 1;
192
- } else if (index === this.index) {
193
- this.index = Math.min(this.index, this.queue.length - 1);
213
+ } else if (wasCurrent) {
214
+ // The next track takes the removed one's place. Past the end, the queue
215
+ // wraps to its start, as `next` does, rather than going back a track.
216
+ if (this.index >= this.queue.length) this.index = 0;
194
217
  this.pendingSeek = 0;
195
218
  }
196
219
  this.bump({ transport: true });
@@ -236,6 +259,7 @@ export class Player {
236
259
  const left = this.current();
237
260
  const skipped = !auto && step > 0 && this.#heardBriefly();
238
261
  this.index = this.#nextIndex(step);
262
+ if (this.current() !== left) this.heardId = null;
239
263
  this.pendingSeek = 0;
240
264
  this.playing = true;
241
265
  this.reported = { ...this.reported, position: 0, duration: 0, error: null, at: Date.now() };
@@ -257,8 +281,31 @@ export class Player {
257
281
  if (!current || this.reported.trackId !== current.id) return false;
258
282
  const position = Number(this.reported.position) || 0;
259
283
  if (position <= 0) return false;
260
- const duration = Number(this.reported.duration) || Number(current.duration) || 0;
261
- return position < Math.max(SKIP_WINDOW_MS, duration * SKIP_WINDOW_FRACTION);
284
+ return position < this.#skipWindow(current);
285
+ }
286
+
287
+ /** How much of `track` must play before moving on is no longer a skip. */
288
+ #skipWindow(track) {
289
+ const duration = Number(this.reported.duration) || Number(track.duration) || 0;
290
+ return Math.max(SKIP_WINDOW_MS, duration * SKIP_WINDOW_FRACTION);
291
+ }
292
+
293
+ /**
294
+ * Tell the taste record, once per play, that the current track was heard
295
+ * through — past the skip window, or to its end. The two windows are one:
296
+ * a track is either skipped or heard, never both and never neither once it
297
+ * has played that far.
298
+ */
299
+ #noteHeard({ ended = false } = {}) {
300
+ const current = this.current();
301
+ if (!current || this.heardId === current.id || this.reported.trackId !== current.id) return;
302
+ if (!ended && (Number(this.reported.position) || 0) < this.#skipWindow(current)) return;
303
+ this.heardId = current.id;
304
+ try {
305
+ this.onHeard?.(current);
306
+ } catch (error) {
307
+ this.logger?.warn?.(`[music] heard listener failed: ${error.message}`);
308
+ }
262
309
  }
263
310
 
264
311
  #notifySkip(track) {
@@ -272,6 +319,7 @@ export class Player {
272
319
  /** Jump to an explicit queue position. */
273
320
  jump(index) {
274
321
  if (index < 0 || index >= this.queue.length) return this.snapshot();
322
+ if (index !== this.index) this.heardId = null;
275
323
  this.index = index;
276
324
  this.pendingSeek = 0;
277
325
  this.playing = true;
@@ -355,6 +403,8 @@ export class Player {
355
403
  this.lastError = this.reported.error;
356
404
  }
357
405
 
406
+ this.#noteHeard({ ended: Boolean(ended) });
407
+
358
408
  let advanced = false;
359
409
  if (ended || error) {
360
410
  this.logger?.info?.(`[music] track ${ended ? 'ended' : 'failed'}, advancing`);
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@doitian/dsh-music",
3
- "version": "0.1.5",
3
+ "version": "0.1.6",
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",