From 6f3ed4b7eeda08450f1aa969766e68def06028c6 Mon Sep 17 00:00:00 2001 From: Sanapach Date: Thu, 19 Nov 2026 19:21:51 +0200 Subject: [PATCH] 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 --- src/player/mod.rs | 83 +++++++++++++++++++++++++++++ templates/player/scripts.html | 79 +++++++++++++++++++++++++++ tests/player_queue_sources.test.cjs | 76 ++++++++++++++++++++++++++ 3 files changed, 238 insertions(+) diff --git a/src/player/mod.rs b/src/player/mod.rs index 5ac0131..51fbfd5 100644 --- a/src/player/mod.rs +++ b/src/player/mod.rs @@ -629,6 +629,7 @@ impl PlayerDeviceHub { .map(|playback| playback.tracks.clone()) .unwrap_or_default(); restore_jam_command_payload(command, &mut payload, &host_tracks)?; + stamp_jam_participant_command(&mut payload); } (jam.host_user_id, target_id) } else { @@ -1793,6 +1794,66 @@ mod jam_command_tests { assert!(restore_jam_command_payload("queue_clear", &mut payload, &[library(1)]).is_ok()); } + #[test] + fn participant_commands_reach_the_host_stamped() { + let hub = PlayerDeviceHub::default(); + hub.heartbeat(1, "host", None, None, None); + let jam = hub + .create_jam(1, "Host", "host", vec![(2, "Guest".to_string())]) + .unwrap(); + let jam_id = jam.jams[0].id.clone(); + hub.heartbeat(2, "guest", None, None, None); + hub.join_jam(2, "Guest", "guest", &jam_id).unwrap(); + let tracks = host_tracks(); + hub.heartbeat( + 1, + "host", + None, + Some(&jam_id), + Some(PlayerDevicePlaybackStateDto { + track: Some(tracks[0].clone()), + tracks, + index: 0, + position_seconds: 0.0, + duration_seconds: 100.0, + paused: false, + shuffle: false, + repeat_mode: "off".into(), + volume: 0.5, + updated_at_ms: 0, + position_unknown: false, + }), + ); + // Move the episode to the end, then remove index 2: the cached host + // state still has music there, so only the host can refuse it. + for (command, payload) in [ + ( + "queue_move", + serde_json::json!({"from_index": 1, "to_index": 2}), + ), + ("queue_remove", serde_json::json!({"index": 2})), + ("pause", serde_json::Value::Null), + ] { + hub.enqueue_command(2, None, Some(&jam_id), command, payload) + .unwrap(); + } + hub.enqueue_command( + 1, + None, + Some(&jam_id), + "queue_remove", + serde_json::json!({"index": 0}), + ) + .unwrap(); + let commands = hub.poll(1, "host", None, Some(&jam_id), None).commands; + let stamped: Vec = commands + .iter() + .map(|command| command.payload[JAM_PARTICIPANT_KEY] == true) + .collect(); + assert_eq!(stamped, [true, true, true, false]); + assert_eq!(commands[1].payload["index"], 2); + } + #[test] fn redacted_current_episode_has_no_duration() { let tracks = host_tracks(); @@ -6323,6 +6384,28 @@ fn restore_jam_command_payload( Ok(()) } +/// Marks a Jam participant command for the host browser. +/// +/// `restore_jam_command_payload` checks the command against the host state of +/// the host's last report. The host browser runs its pending commands in one +/// batch, so an earlier command (a move, an insert) can make a checked index +/// name a private item there. The host browser applies the same rules to its +/// own queue for stamped commands (`_jamParticipantCommandAllowed`). +fn stamp_jam_participant_command(payload: &mut serde_json::Value) { + if !payload.is_object() { + *payload = serde_json::json!({}); + } + if let Some(object) = payload.as_object_mut() { + object.insert( + JAM_PARTICIPANT_KEY.to_string(), + serde_json::Value::Bool(true), + ); + } +} + +/// Command payload key set by the server on Jam participant commands. +const JAM_PARTICIPANT_KEY: &str = "jam_participant"; + fn stamp_jam_queue_tracks(payload: &mut serde_json::Value, user_id: i64, user_name: &str) { let Some(tracks) = payload .get_mut("tracks") diff --git a/templates/player/scripts.html b/templates/player/scripts.html index cdcd1b2..83890f7 100644 --- a/templates/player/scripts.html +++ b/templates/player/scripts.html @@ -1398,6 +1398,9 @@ document.addEventListener('alpine:init', () => { if (!command || !command.command) return; const payload = command.payload || {}; const queue = Alpine.store('queue'); + // The server stamps Jam participant commands. It checks them against + // the host state it saw last; this queue is the one they change. + if (payload.jam_participant === true && !this._jamParticipantCommandAllowed(command.command, payload, queue)) return; this._remoteExecuting = true; try { if (typeof payload.shuffle === 'boolean') this.shuffle = payload.shuffle; @@ -1523,6 +1526,76 @@ document.addEventListener('alpine:init', () => { Alpine.store('queue')?.syncCurrentIndexToTrack(track); }, + _jamParticipantCommandAllowed(command, payload, queue) { + // Jam participants cannot remove, clear away, add or bring back the + // host's private items (podcast episodes). Commands run in a batch, + // so an index the server checked can name another item by now. + const tracks = queue?.tracks || []; + const isPrivate = track => this._isUnplayableQueueItem(track); + if (command === 'queue_remove') { + const index = Number(payload.index); + if (!Number.isInteger(index)) return !tracks.some(isPrivate); + return !isPrivate(tracks[index]); + } + if (command === 'queue_clear') return !tracks.some(isPrivate); + if (command === 'queue_add_end' || command === 'queue_add_next') { + return !(Array.isArray(payload.tracks) ? payload.tracks : []).some(isPrivate); + } + if (command === 'play_track' || command === 'play_from_index' || command === 'transfer_state') { + const incoming = Array.isArray(payload.tracks) ? payload.tracks.filter(Boolean) : []; + if (incoming.length === 0) return !isPrivate(payload.track); + // A full queue replaces this one: it must hold exactly the private + // items this queue holds now (none dropped, repeated or added). + const key = track => { + const source = track?.source || track?.wire_track?.source || {}; + return `${source.kind || ''}:${source.episode_id || ''}`; + }; + const counts = list => { + const result = new Map(); + list.filter(isPrivate).forEach(track => result.set(key(track), (result.get(key(track)) || 0) + 1)); + return result; + }; + const mine = counts(tracks); + const theirs = counts(incoming); + return mine.size === theirs.size && [...theirs].every(([item, count]) => mine.get(item) === count); + } + return true; + }, + + _dropJamPlaceholders() { + // A Jam guest's queue shows the host's private items as placeholders. + // They stand for someone else's items and never become this user's + // own queue (persisted, relayed to their devices) after the Jam. + const queue = Alpine.store('queue'); + if (!queue) return; + const isPlaceholder = track => this._queueItemSourceKind(track) === 'private'; + const tracks = Array.isArray(queue.tracks) ? queue.tracks : []; + if (!tracks.some(isPlaceholder) && !isPlaceholder(this.currentTrack)) return; + const currentIndex = Math.max(0, Number(queue.currentIndex || 0)); + const kept = tracks.filter(track => !isPlaceholder(track)); + let index = kept.indexOf(tracks[currentIndex]); + // A removed current item is followed by the next item that stays. + if (index < 0) index = tracks.slice(0, currentIndex).filter(track => !isPlaceholder(track)).length; + queue.tracks = kept; + queue.currentIndex = Math.max(0, Math.min(index, kept.length - 1)); + if (!isPlaceholder(this.currentTrack)) return; + const next = kept[queue.currentIndex] || null; + if (next) { + this._playLocal(next, { paused: true }); + return; + } + this._pauseLocal(); + audio.removeAttribute('src'); + audio.load(); + this.currentTrack = null; + this._historyTrack = null; + this._localSourceTrackId = null; + this._positionUnknown = false; + this.currentTime = 0; + this.duration = 0; + this.progress = 0; + }, + _queueItemsPayload(tracks) { // Library tracks by id; everything else verbatim with its source. return (tracks || []).map(track => { @@ -1919,6 +1992,7 @@ document.addEventListener('alpine:init', () => { _apply(data) { const previousJamId = this.currentJamId; + const wasControllingJam = this.isControllingRemoteJam(); this.activeDeviceId = data.active_device_id || null; this.devices = Array.isArray(data.devices) ? data.devices : []; this.jams = Array.isArray(data.jams) ? data.jams : []; @@ -1936,6 +2010,9 @@ document.addEventListener('alpine:init', () => { if (!this.isActive() && !this.shouldPlayJamLocally()) { Alpine.store('player')?._pauseLocal(); } + if (wasControllingJam && !this.isControllingRemoteJam()) { + Alpine.store('player')?._dropJamPlaceholders(); + } this._maybeShowRemoteHint(); }, @@ -2436,11 +2513,13 @@ document.addEventListener('alpine:init', () => { }, clearJamSelection() { + const wasControllingJam = this.isControllingRemoteJam(); this.currentJamId = null; this.jamPanelOpen = false; this.jamPanelJamId = null; this._setJamLocalPlayback(false, { pauseLocal: true }); sessionStorage.removeItem('furu_player_jam_id'); + if (wasControllingJam) Alpine.store('player')?._dropJamPlaceholders(); }, }); diff --git a/tests/player_queue_sources.test.cjs b/tests/player_queue_sources.test.cjs index aaa3ed1..33200b6 100644 --- a/tests/player_queue_sources.test.cjs +++ b/tests/player_queue_sources.test.cjs @@ -114,6 +114,7 @@ function activePlayer(queueTracks, currentIndex, audioState = {}, options = {}) '_skipUnplayableCurrentItem', '_knownPosition', '_currentItemHasLocalAudio', '_showUnplayableQueueItem', '_syncLocalPlaybackState', '_queueItemSourceKind', '_isUnplayableQueueItem', '_playableQueueIndex', + '_jamParticipantCommandAllowed', '_dropJamPlaceholders', ]; const audio = Object.assign({ paused: true, currentTime: 0, duration: NaN, src: '', @@ -131,6 +132,11 @@ function activePlayer(queueTracks, currentIndex, audioState = {}, options = {}) 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]}}); @@ -299,3 +305,73 @@ test('prev and seek work on a handed-off episode', () => { 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\(\);/); +});