Files
furumi-web/tests/player_queue_sources.test.cjs
T
sanapachandClaude Opus 5.5 6f3ed4b7ee Check Jam participant commands against the host queue
The server checked a participant's queue_remove/queue_clear against the
host state of the last report, but the host browser runs its pending
commands in one batch: after a move, a checked index can name a private
item. Participant commands are now stamped `jam_participant`, and the
host browser refuses to remove, clear, add or bring back its private
items for them, judged on the queue it is about to change.

A guest that stops controlling a Jam drops the host's private
placeholders from its own queue, so they are not saved or relayed as
the guest's queue.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-19 19:21:51 +02:00

378 lines
19 KiB
JavaScript

const assert = require('node:assert/strict');
const {readFileSync} = require('node:fs');
const {test} = require('node:test');
const vm = require('node:vm');
const template = readFileSync(`${__dirname}/../templates/player/scripts.html`, 'utf8');
// Queue items received from trusted devices that this player cannot play.
const podcast = {
id: -11, title: 'Episode 42', unavailable: true, stream_url: '',
source: {kind: 'podcast_episode', episode_id: 'ep1:x'},
wire_track: {id: 0, title: 'Episode 42', source: {kind: 'podcast_episode', episode_id: 'ep1:x'}},
};
const privateItem = {
id: -12, title: 'Private item', unavailable: true, stream_url: '',
source: {kind: 'private'}, wire_track: {id: 0, title: 'Private item', source: {kind: 'private'}},
};
const remoteMusic = {id: -13, title: 'Remote', unavailable: true, stream_url: '', wire_track: {id: 4, title: 'Remote'}};
const song = id => ({id, title: `Song ${id}`, stream_url: `/api/player/stream/${id}`});
function player(queue) {
// Exercise the production methods with audio and store stubs.
const methods = template.slice(
template.indexOf(' _queueItemSourceKind(track)'),
template.indexOf(' _saveState()'),
);
const audio = {paused: false, src: 'old', pause() { this.paused = true; }, removeAttribute(name) { if (name === 'src') this.src = ''; }, load() {}};
const stores = {queue: Object.assign({syncCurrentIndexToTrack() {}}, queue)};
const context = vm.createContext({
audio, T: {queuePodcastUnplayable: 'Podcast · not playable', queuePrivateItem: 'Private item · hidden'},
Alpine: {store: name => stores[name]},
});
vm.runInContext('this.methods = {' + methods + '};', context);
return Object.assign(context.methods, {audio, currentTrack: null, currentTime: 0, volume: 0.5, shuffle: false, repeatMode: 'off'});
}
test('podcast and private items are labelled and never played locally', () => {
const p = player({tracks: [], currentIndex: 0});
assert.equal(p._isUnplayableQueueItem(podcast), true);
assert.equal(p._isUnplayableQueueItem(privateItem), true);
assert.equal(p._isUnplayableQueueItem(remoteMusic), false);
assert.equal(p._isUnplayableQueueItem(song(1)), false);
assert.equal(p._unplayableQueueLabel(podcast), 'Podcast · not playable');
assert.equal(p._unplayableQueueLabel(privateItem), 'Private item · hidden');
assert.equal(p._unplayableQueueLabel(song(1)), '');
// A browser item that only carries the verbatim wire item is recognised too.
assert.equal(p._isUnplayableQueueItem({id: -1, wire_track: podcast.wire_track}), true);
});
test('skipping finds the next playable item in the direction of travel', () => {
const p = player({tracks: [], currentIndex: 0});
const tracks = [song(1), podcast, privateItem, song(2)];
assert.equal(p._playableQueueIndex(tracks, 1, 1), 3);
assert.equal(p._playableQueueIndex(tracks, 2, -1), 0);
assert.equal(p._playableQueueIndex([podcast], 0, 1), -1);
});
test('showing an unplayable item stops and unloads the previous audio', () => {
const p = player({tracks: [podcast], currentIndex: 0});
p.isPlaying = true;
p._showUnplayableQueueItem(podcast);
assert.equal(p.audio.paused, true);
assert.equal(p.audio.src, '');
assert.equal(p.isPlaying, false);
assert.equal(p.currentTrack, podcast);
assert.equal(p._historyTrack, null);
});
test('persisted queue keeps external items verbatim and in order', () => {
const tracks = [song(1), podcast, remoteMusic, {id: 'pending', federation_pending: true}, song(2)];
const p = player({tracks, currentIndex: 4});
p.currentTrack = tracks[4];
p.currentTime = 12.3;
const state = p._buildStatePayload();
assert.deepEqual(JSON.parse(JSON.stringify(state.queue_items)), [
{kind: 'library', track_id: 1},
{kind: 'external', track: podcast.wire_track},
{kind: 'external', track: remoteMusic.wire_track},
{kind: 'library', track_id: 2},
]);
// The pending federation entry is not persisted, as before.
assert.equal(state.queue_items_position, 3);
// The legacy id list is unchanged for rollback.
assert.deepEqual(JSON.parse(JSON.stringify(state.queue)), [1, -11, -13, 2]);
assert.equal(state.current_track_id, 2);
});
test('restoring merges library tracks and external items', () => {
const p = player({tracks: [], currentIndex: 0});
const restored = p._restoredQueueTracks([
{kind: 'library', track_id: 1},
{kind: 'external', track: podcast},
{kind: 'library', track_id: 99},
{kind: 'library', track_id: 2},
], [song(2), song(1)]);
assert.deepEqual(Array.from(restored.tracks, track => track.id), [1, -11, 2]);
assert.equal(restored.positions[3], 2);
assert.equal(restored.positions[2], undefined);
});
// Production methods by name, for flows that span several of them.
function method(name) {
const start = template.indexOf(`\n ${name}(`);
assert.ok(start >= 0, `method ${name} not found`);
const end = template.indexOf('\n },\n', start);
return template.slice(start + 1, end + 11);
}
function activePlayer(queueTracks, currentIndex, audioState = {}, options = {}) {
// The browser as the active (local) playback device.
const names = [
'_executeRemoteCommand', '_applyRemotePlaybackState', '_tickRemoteProgress',
'_devicePlaybackStatePayload', '_remotePlaybackPayload', '_trackDuration',
'_pauseLocal', '_playLocal', 'resume', 'next', 'prev', 'playQueueIndex', 'seek',
'_skipUnplayableCurrentItem', '_knownPosition', '_currentItemHasLocalAudio',
'_showUnplayableQueueItem', '_syncLocalPlaybackState',
'_queueItemSourceKind', '_isUnplayableQueueItem', '_playableQueueIndex',
'_jamParticipantCommandAllowed', '_dropJamPlaceholders',
];
const audio = Object.assign({
paused: true, currentTime: 0, duration: NaN, src: '',
played: [],
pause() { this.paused = true; },
play() { this.paused = false; this.played.push(this.src); return Promise.resolve(); },
removeAttribute(name) { if (name === 'src') this.src = ''; },
load() { this.currentTime = 0; },
addEventListener() {}, removeEventListener() {},
}, audioState);
const queue = {
tracks: queueTracks, currentIndex,
_tracksWithJamDefaults: tracks => tracks,
syncCurrentIndexToTrack(track) {
const index = this.tracks.indexOf(track);
if (index >= 0) this.currentIndex = index;
},
// Simplified local queue edits, as the host applies remote commands.
_removeLocal(index) { if (index >= 0 && index < this.tracks.length) this.tracks.splice(index, 1); },
_moveTrackLocal(from, to) { this.tracks.splice(to, 0, this.tracks.splice(from, 1)[0]); },
_clearLocal() { this.tracks = []; },
_addToEndLocal(tracks) { this.tracks.push(...tracks); },
};
const stores = {queue, devices: {heartbeat() {}}};
const context = vm.createContext({audio, Alpine: {store: name => stores[name]}});
if (options.random != null) vm.runInContext(`Math.random = () => ${options.random};`, context);
vm.runInContext('this.methods = {' + names.map(method).join('\n') + '};', context);
return Object.assign(context.methods, {
audio, queue,
currentTrack: queueTracks[currentIndex] || null, currentTime: 0, duration: 0, progress: 0,
isPlaying: false, shuffle: false, repeatMode: 'off', volume: 0.5,
_remoteStateBaseTime: 0, _remoteStateReceivedAt: 0,
_isLocalPlaybackDevice: () => true, _shouldSendRemote: () => false,
_shouldMirrorRemoteLocally: () => false,
_setVolumeLocal(v) { this.volume = v; }, _updateMediaSession() {}, _saveState() {},
_recordHistory() {}, _resetPlaybackTracking() {}, _mirrorRemoteTrack() {},
});
}
const episode = Object.assign({}, podcast, {duration_seconds: 1800});
test('handoff of a podcast episode keeps its position for the next handoff', () => {
for (const audioTime of [95, 0]) {
// <audio> still holds a music track (95 s) or the page is fresh (0 s).
const p = activePlayer([song(1)], 0, {currentTime: audioTime, src: '/api/player/stream/1'});
p._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [song(1), episode], index: 1, track: episode,
position_seconds: 1200, duration_seconds: 1800, paused: false,
}});
assert.equal(p.currentTrack, episode);
assert.equal(p.currentTime, 1200);
assert.equal(p.isPlaying, false);
assert.equal(p.audio.src, '', 'the previous track is unloaded');
const reported = p._devicePlaybackStatePayload();
assert.equal(reported.position_seconds, 1200);
assert.equal(reported.position_unknown, undefined, 'a handed-off position is known');
assert.equal(reported.index, 1);
assert.equal(reported.paused, true);
}
});
test('library tracks still report the audio position', () => {
const p = activePlayer([song(1)], 0, {currentTime: 42, src: '/api/player/stream/1'});
p.currentTime = 40;
assert.equal(p._devicePlaybackStatePayload().position_seconds, 42);
});
test('resume on an unplayable item skips it, also with repeat one', () => {
for (const repeatMode of ['one', 'off', 'all']) {
const p = activePlayer([podcast], 0);
p.repeatMode = repeatMode;
p.currentTime = 30;
p.resume();
p.next();
assert.equal(p.currentTrack, podcast);
assert.equal(p.isPlaying, false);
assert.equal(p.currentTime, 30, 'the item keeps its position');
assert.deepEqual(p.audio.played, []);
}
const p = activePlayer([song(1), podcast, song(2)], 1);
p.repeatMode = 'one';
p.resume();
assert.equal(p.currentTrack.id, 2);
assert.deepEqual(p.audio.played, ['/api/player/stream/2']);
// Repeat all wraps around to the first playable item.
const wrap = activePlayer([song(1), podcast], 1);
wrap.repeatMode = 'all';
wrap.resume();
assert.equal(wrap.currentTrack.id, 1);
});
test('an episode reached without its position reports it as unknown, never as 0', () => {
// Next from the last music track lands on a trailing episode.
const p = activePlayer([song(1), episode], 0, {currentTime: 200, src: '/api/player/stream/1'});
p.isPlaying = true;
p.currentTime = 200;
p.next();
assert.equal(p.currentTrack, episode);
assert.equal(p.isPlaying, false);
let reported = p._devicePlaybackStatePayload();
assert.equal(reported.index, 1);
assert.equal(reported.position_unknown, true);
// Still unknown after Play finds nothing to skip to.
p.resume();
assert.equal(p._devicePlaybackStatePayload().position_unknown, true);
// A seek is an explicit position.
p.seek(600);
reported = p._devicePlaybackStatePayload();
assert.equal(reported.position_seconds, 600);
assert.equal(reported.position_unknown, undefined);
// Music never reports the flag.
p.playQueueIndex(0);
assert.equal(p.currentTrack.id, 1);
assert.equal(p._devicePlaybackStatePayload().position_unknown, undefined);
// Another browser or a Jam guest plays the episode row (position 0 sent).
const remote = activePlayer([song(1), episode], 0, {currentTime: 30, src: '/api/player/stream/1'});
remote._executeRemoteCommand({command: 'play_from_index', payload: {
tracks: [song(1), episode], index: 1, track: episode, position_seconds: 0, paused: false,
}});
assert.equal(remote.currentTrack, episode);
assert.equal(remote._devicePlaybackStatePayload().position_unknown, true);
// A transfer passes on what the previous device did not know.
const relay = activePlayer([song(1)], 0);
relay._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [song(1), episode], index: 1, track: episode, position_seconds: 0,
position_unknown: true, paused: true,
}});
assert.equal(relay._devicePlaybackStatePayload().position_unknown, true);
// A mirrored state with a known position keeps it.
const mirror = activePlayer([song(1), episode], 0);
mirror._syncLocalPlaybackState({tracks: [song(1), episode], index: 1, track: episode, position_seconds: 900, paused: true});
assert.equal(mirror._devicePlaybackStatePayload().position_seconds, 900);
assert.equal(mirror._devicePlaybackStatePayload().position_unknown, undefined);
});
test('repeat all and shuffle continue past a trailing unplayable item', () => {
const wrap = activePlayer([song(1), episode], 0, {currentTime: 200, src: '/api/player/stream/1'});
wrap.repeatMode = 'all';
wrap.isPlaying = true;
wrap.next();
assert.equal(wrap.currentTrack.id, 1);
assert.equal(wrap.queue.currentIndex, 0);
assert.deepEqual(wrap.audio.played, ['/api/player/stream/1']);
// Shuffle picks the episode (index 1 of 3) and continues with music
// (searching towards the pick from the current item).
const shuffled = activePlayer([song(1), episode, song(2)], 2, {src: '/api/player/stream/2'}, {random: 0.5});
shuffled.shuffle = true;
shuffled.next();
assert.equal(shuffled.currentTrack.id, 1);
assert.equal(shuffled.isPlaying, false, 'the stub audio does not fire play events');
assert.deepEqual(shuffled.audio.played, ['/api/player/stream/1']);
// A trailing episode picked by shuffle wraps to the first playable item.
const trailing = activePlayer([song(1), song(2), episode], 1, {src: '/api/player/stream/2'}, {random: 0.9});
trailing.shuffle = true;
trailing.next();
assert.equal(trailing.currentTrack.id, 1);
// Without repeat the queue ends on the episode, as before.
const stop = activePlayer([song(1), episode], 0, {src: '/api/player/stream/1'});
stop.next();
assert.equal(stop.currentTrack, episode);
assert.equal(stop.isPlaying, false);
});
test('prev and seek work on a handed-off episode', () => {
const p = activePlayer([song(1), song(3)], 0, {currentTime: 95, src: '/api/player/stream/1'});
p._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [song(1), episode], index: 1, track: episode,
position_seconds: 1200, duration_seconds: 1800, paused: false,
}});
// Seeking moves the episode's own position (nothing is loaded in <audio>).
p.seek(1500);
assert.equal(p.currentTime, 1500);
assert.equal(p._devicePlaybackStatePayload().position_seconds, 1500);
// Prev goes to the previous item instead of restarting the episode.
p.prev();
assert.equal(p.currentTrack.id, 1);
assert.deepEqual(p.audio.played, ['/api/player/stream/1']);
// At the start of the queue Prev leaves the episode and its position alone.
const first = activePlayer([episode, song(1)], 0);
first._executeRemoteCommand({command: 'transfer_state', payload: {
tracks: [episode, song(1)], index: 0, track: episode, position_seconds: 1200, paused: true,
}});
first.prev();
assert.equal(first.currentTrack, episode);
assert.equal(first.currentTime, 1200);
});
test('the Jam host keeps its private items against stale participant commands', () => {
const a = song(1);
const b = song(2);
const p = activePlayer([a, episode, b], 0, {src: '/api/player/stream/1'});
// One poll batch: the server checked index 2 against the old order [A, P, B].
for (const command of [
{command: 'queue_move', payload: {from_index: 1, to_index: 2, jam_participant: true}},
{command: 'queue_remove', payload: {index: 2, jam_participant: true}},
]) p._executeRemoteCommand(command);
assert.deepEqual(p.queue.tracks, [a, b, episode]);
p._executeRemoteCommand({command: 'queue_clear', payload: {jam_participant: true}});
assert.equal(p.queue.tracks.length, 3);
p._executeRemoteCommand({command: 'queue_add_end', payload: {tracks: [privateItem], jam_participant: true}});
assert.equal(p.queue.tracks.length, 3);
// A full queue from a stale view brings back nothing the host removed.
p._executeRemoteCommand({command: 'play_from_index', payload: {
tracks: [a, episode, episode, b], index: 0, track: a, jam_participant: true,
}});
assert.deepEqual(p.queue.tracks, [a, b, episode]);
p._executeRemoteCommand({command: 'play_from_index', payload: {
tracks: [a, b], index: 0, track: a, jam_participant: true,
}});
assert.deepEqual(p.queue.tracks, [a, b, episode]);
// Music is still theirs to change, and the host's own commands are not limited.
p._executeRemoteCommand({command: 'queue_remove', payload: {index: 0, jam_participant: true}});
assert.deepEqual(p.queue.tracks, [b, episode]);
p._executeRemoteCommand({command: 'play_from_index', payload: {
tracks: [episode, b], index: 1, track: b, jam_participant: true,
}});
assert.deepEqual(p.queue.tracks, [episode, b]);
p._executeRemoteCommand({command: 'queue_remove', payload: {index: 0}});
assert.deepEqual(p.queue.tracks, [b]);
});
test('leaving a Jam drops the host placeholders from the guest queue', () => {
const placeholder = Object.assign({}, privateItem);
const p = activePlayer([song(1), placeholder, song(2)], 1);
p.currentTrack = placeholder;
p._dropJamPlaceholders();
assert.deepEqual(Array.from(p.queue.tracks, track => track.id), [1, 2]);
// The current placeholder hands over to the next item, paused.
assert.equal(p.queue.currentIndex, 1);
assert.equal(p.currentTrack.id, 2);
assert.equal(p.isPlaying, false);
assert.deepEqual(p.audio.played, []);
const music = activePlayer([song(1), placeholder, song(2)], 2);
music._dropJamPlaceholders();
assert.equal(music.queue.currentIndex, 1);
assert.equal(music.currentTrack.id, 2);
const only = activePlayer([placeholder], 0);
only._dropJamPlaceholders();
assert.deepEqual(only.queue.tracks, []);
assert.equal(only.currentTrack, null);
// The guest's own podcast episodes stay.
const own = activePlayer([episode, song(1)], 0);
own._dropJamPlaceholders();
assert.equal(own.queue.tracks.length, 2);
});
test('the devices store drops placeholders when the guest stops controlling a Jam', () => {
const start = template.indexOf('\n _apply(data) {');
const apply = template.slice(start, template.indexOf('\n },\n', start));
assert.match(apply, /const wasControllingJam = this\.isControllingRemoteJam\(\);/);
assert.match(apply, /if \(wasControllingJam && !this\.isControllingRemoteJam\(\)\) \{\s*Alpine\.store\('player'\)\?\._dropJamPlaceholders\(\);/);
const clear = template.slice(template.indexOf('\n clearJamSelection() {'));
assert.match(clear.slice(0, clear.indexOf('\n },\n')), /if \(wasControllingJam\) Alpine\.store\('player'\)\?\._dropJamPlaceholders\(\);/);
});