aboutsummaryrefslogtreecommitdiffstats
path: root/packages/meshbay-hub/tests
diff options
context:
space:
mode:
Diffstat (limited to 'packages/meshbay-hub/tests')
-rwxr-xr-xpackages/meshbay-hub/tests/harness/music_queue_probe.py308
-rw-r--r--packages/meshbay-hub/tests/test_hook_ordering.py3
-rw-r--r--packages/meshbay-hub/tests/test_music_queue.py115
-rw-r--r--packages/meshbay-hub/tests/test_queue_ops.py319
-rw-r--r--packages/meshbay-hub/tests/test_transport_contracts.py1
5 files changed, 746 insertions, 0 deletions
diff --git a/packages/meshbay-hub/tests/harness/music_queue_probe.py b/packages/meshbay-hub/tests/harness/music_queue_probe.py
new file mode 100755
index 0000000..f74ceb2
--- /dev/null
+++ b/packages/meshbay-hub/tests/harness/music_queue_probe.py
@@ -0,0 +1,308 @@
+#!/usr/bin/env python3
+"""
+The queue verbs, driven through the real interface in a real browser.
+
+`queue-ops.js` is unit-tested on its own, but everything between a right-click
+and the reducer is not reachable that way: whether the menu opens at all,
+whether the dots button survived being put inside a row that used to be one
+big `<button>` (a button cannot contain a button — the browser reparents the
+inner one and the row comes apart), and whether "play next" reaches the player
+with its `op` intact through two components and the shell.
+
+So this renders the shipped `GroupPage` and the shipped `MusicPlayerBar`
+against a stub node, presses the real controls, and reports the queue after
+each one — read where a person reads it, out of the player's own queue panel.
+
+ music_queue_probe.py
+
+Prints JSON: one entry per step, with the play order and the playing track.
+
+Playback itself cannot happen here: the stub never returns a transport, so
+every track stays loading for ever. That is deliberate and is not what is
+being measured — the queue is.
+"""
+import http.server
+import json
+import socketserver
+import subprocess
+import sys
+import tempfile
+import threading
+import time
+from pathlib import Path
+
+STATIC = Path(__file__).resolve().parents[2] / "src" / "meshbay_hub" / "static"
+PORT = 8751
+RECORDS = []
+socketserver.TCPServer.allow_reuse_address = True
+
+FRAME = r"""<!doctype html><html><head><meta charset=utf-8>
+<link rel="stylesheet" href="/style.css"></head><body>
+<nav class="nav"><div class="nav-left"><a class="nav-brand" href="#/">MeshBay</a></div></nav>
+<div class="layout"><main class="main"><div id="root"></div></main></div>
+<script>
+// Four albums of three tracks, each track titled so the queue can be read back
+// unambiguously: "A2-t3" is the third track of the second album and nothing
+// else. A fixture whose rows cannot be told apart measures nothing.
+const ENTRIES = [];
+let n = 0;
+for (let a = 1; a <= 4; a++) {
+ for (let i = 1; i <= 3; i++) {
+ ENTRIES.push({
+ id: 'e' + (++n), name: `A${a}-t${i}.flac`, display_title: `A${a}-t${i}`,
+ path: `musique/Artiste ${a}/Album ${a}`, type: 'audio',
+ artist: `Artiste ${a}`, album: `Album ${a}`,
+ track_no: i, duration: 200, size: 1024 * 1024, added_at: 1750000000 + n,
+ });
+ }
+}
+
+const ACK = {
+ is_node_admin: false,
+ enabled_apps: ['files', 'music'],
+ tmdb_enabled: false, musicbrainz_enabled: false,
+ video_directories: [], music_directories: ['musique'], photo_directories: [],
+};
+
+window.MeshBayTransport = function () {
+ const self = {
+ connected: false, memberRole: 'member', supportsAppOps: true,
+ sessionKeys: null, gekRaw: null,
+ newNodeBundle: null, newNodeBundleRecovery: null,
+ async connect() { self.connected = true; return ACK; },
+ async fetchIndex() {
+ return { entries: ENTRIES, dirs: ['musique'],
+ roots: [{ name: 'musique', available: true, writable: false,
+ removable: false }] };
+ },
+ async fetchChatHistory() { return { messages: [], hasMore: false }; },
+ async fetchLinkPreview() { return { ok: false }; },
+ close() {},
+ };
+ return new Proxy(self, {
+ get(target, prop) {
+ if (prop in target) return target[prop];
+ if (typeof prop === 'string' && prop.startsWith('on')) return undefined;
+ if (typeof prop === 'symbol') return undefined;
+ return () => new Promise(() => {});
+ },
+ set(target, prop, value) { target[prop] = value; return true; },
+ });
+};
+</script>
+<script type="module">
+import { html, render, useState, useCallback } from '/vendor/htm-preact.js';
+import { initLocale } from '/i18n.js';
+import { GroupPage } from '/group-page.js';
+import { MusicPlayerBar } from '/music-player.js';
+
+const LOGS = [];
+addEventListener('error', (e) => LOGS.push('error: ' + (e.message || e)));
+addEventListener('unhandledrejection',
+ (e) => LOGS.push('rejection: ' + ((e.reason && (e.reason.stack || e.reason.message)) || e.reason)));
+
+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
+const waitFor = async (sel, tries = 60) => {
+ for (let i = 0; i < tries; i++) {
+ const el = document.querySelector(sel);
+ if (el) return el;
+ await sleep(50);
+ }
+ return null;
+};
+
+// The shell's two jobs, and only those: hold the queue, and pass `op` through.
+// app.js does more (a transport fast path, the stop button); the contract this
+// exercises is the shape of what it hands the player.
+function Harness() {
+ const [queue, setQueue] = useState(null);
+ const onPlayQueue = useCallback((tracks, startIndex, source, op) => {
+ setQueue({ tracks, startIndex, nonce: Date.now(), op: op || 'replace' });
+ }, []);
+ return html`
+ <${GroupPage} groupId="g1" token="t" username="me" userId="u1"
+ group=${{ id: 'g1', name: 'un groupe', owner_username: 'me', is_admin: false }}
+ userPrefs=${{ default_tab: 'music', media_page_size: '50' }}
+ onPlayQueue=${onPlayQueue} />
+ ${queue && html`<${MusicPlayerBar} getConnection=${() => new Promise(() => {})}
+ queue=${queue} userPrefs=${{}} onClose=${() => setQueue(null)} />`}
+ `;
+}
+
+const steps = [];
+
+// The queue as a person sees it: the player's own panel, opened and closed.
+async function queueNow(label, extra) {
+ const open = document.querySelector('.music-player-extra .music-player-btn');
+ if (!open) { steps.push({ step: label, bar: false, ...extra }); return; }
+ open.click();
+ const panel = await waitFor('.music-detail .music-tracklist');
+ const rows = [...document.querySelectorAll('.music-detail .music-tracklist .music-track-row')];
+ steps.push({
+ step: label,
+ bar: true,
+ play: rows.map((r) => r.querySelector('.music-track-title').textContent),
+ playing: (rows.findIndex((r) => r.classList.contains('active'))),
+ nowPlaying: (document.querySelector('.music-player-title') || {}).textContent || null,
+ ...extra,
+ });
+ const close = document.querySelector('.music-detail .video-close');
+ if (close) close.click();
+ await sleep(120);
+}
+
+const rightClick = (el) => el.dispatchEvent(new MouseEvent('contextmenu', {
+ bubbles: true, cancelable: true, clientX: 200, clientY: 200 }));
+
+const menuLabels = () => [...document.querySelectorAll('.ctx-menu .ctx-menu-item')]
+ .map((b) => b.querySelector('.ctx-menu-label').textContent);
+
+const clickMenu = async (i) => {
+ const items = [...document.querySelectorAll('.ctx-menu .ctx-menu-item')];
+ items[i].click();
+ await sleep(200);
+};
+
+(async () => {
+ const fail = (why) => parent.postMessage(
+ { error: why, logs: LOGS.slice(0, 12),
+ text: (document.getElementById('root').textContent || '').slice(0, 400) }, '*');
+ try {
+ await initLocale();
+ render(html`<${Harness} />`, document.getElementById('root'));
+
+ if (!await waitFor('.music-card')) return fail('no album grid');
+ const cards = [...document.querySelectorAll('.music-card')];
+ if (cards.length < 4) return fail('expected 4 albums, got ' + cards.length);
+
+ // 1. Open album 1 and play its second track — the ordinary path, through a
+ // row that is no longer one big button.
+ cards[0].click();
+ if (!await waitFor('.music-detail .music-tracklist')) return fail('no detail modal');
+ const rows = [...document.querySelectorAll('.music-detail .music-tracklist .music-track-main')];
+ if (rows.length !== 3) return fail('album 1 has ' + rows.length + ' rows');
+ rows[1].click();
+ await sleep(250);
+ await queueNow('play a track');
+
+ // 2. Right-click album 2 → "add to queue".
+ rightClick(document.querySelectorAll('.music-card')[1]);
+ await sleep(150);
+ if (!document.querySelector('.ctx-menu')) return fail('right-click opened no menu');
+ const labels = menuLabels();
+ await clickMenu(2);
+ await queueNow('append album 2', { menu: labels });
+
+ // 3. Dots on album 3 → "play next". The other affordance, and the verb
+ // that has to land at pos + 1 rather than at the end.
+ const dots = document.querySelectorAll('.music-card .ctx-dots');
+ if (dots.length < 3) return fail('only ' + dots.length + ' dots buttons');
+ dots[2].click();
+ await sleep(150);
+ if (!document.querySelector('.ctx-menu')) return fail('dots opened no menu');
+ await clickMenu(1);
+ await queueNow('play next album 3');
+
+ // 4. Shuffle on and off again: the playing track must not change, and the
+ // queue must still hold everything appended to it.
+ document.querySelector('.music-player-transport .music-player-btn').click();
+ await sleep(200);
+ await queueNow('shuffle on');
+ document.querySelector('.music-player-transport .music-player-btn').click();
+ await sleep(200);
+ await queueNow('shuffle off');
+
+ // 5. Replace: playing an album outright discards everything above.
+ document.querySelectorAll('.music-card')[3].click();
+ if (!await waitFor('.music-detail .music-detail-meta .admin-btn')) return fail('no play-all');
+ document.querySelector('.music-detail .music-detail-meta .admin-btn').click();
+ await sleep(250);
+ await queueNow('replace with album 4');
+
+ parent.postMessage({ steps, logs: LOGS.slice(0, 8) }, '*');
+ } catch (err) {
+ fail(String((err && err.stack) || err));
+ }
+})();
+</script></body></html>"""
+
+PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head>
+<body style="margin:0"><div id="frames"></div><script>
+addEventListener('message', (e) => {
+ fetch('/log', { method: 'POST', body: JSON.stringify(e.data) });
+});
+const f = document.createElement('iframe');
+f.src = '/case';
+f.style.cssText = 'width:1100px;height:800px;border:0;display:block';
+document.getElementById('frames').appendChild(f);
+</script></body></html>"""
+
+
+class H(http.server.BaseHTTPRequestHandler):
+ def log_message(self, *a):
+ pass
+
+ def do_POST(self):
+ length = int(self.headers.get("Content-Length") or 0)
+ if self.path == "/log":
+ RECORDS.append(json.loads(self.rfile.read(length).decode()))
+ else:
+ self.rfile.read(length)
+ self.send_response(204)
+ self.end_headers()
+
+ def _send(self, body: bytes, ctype: str) -> None:
+ self.send_response(200)
+ self.send_header("Content-Type", ctype)
+ self.send_header("Content-Length", str(len(body)))
+ self.end_headers()
+ self.wfile.write(body)
+
+ def do_GET(self):
+ path = self.path.split("?")[0]
+ if path == "/":
+ self._send(PAGE.encode(), "text/html; charset=utf-8")
+ elif path == "/case":
+ self._send(FRAME.encode(), "text/html; charset=utf-8")
+ elif path == "/v1/groups/g1/nodes":
+ self._send(b'{"nodes": [{"node_id": "n1"}]}', "application/json")
+ else:
+ asset = (STATIC / path.lstrip("/")).resolve()
+ if not str(asset).startswith(str(STATIC)) or not asset.is_file():
+ self.send_response(404)
+ self.end_headers()
+ return
+ self._send(asset.read_bytes(),
+ "text/css" if asset.suffix == ".css"
+ else "text/javascript" if asset.suffix == ".js"
+ else "application/octet-stream")
+
+
+def main() -> int:
+ with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv:
+ threading.Thread(target=srv.serve_forever, daemon=True).start()
+ with tempfile.TemporaryDirectory(ignore_cleanup_errors=True) as profile:
+ proc = subprocess.Popen(
+ ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox",
+ f"--user-data-dir={profile}", "--window-size=1100,900",
+ f"http://127.0.0.1:{PORT}/"],
+ stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL)
+ for _ in range(400):
+ if RECORDS:
+ break
+ time.sleep(0.1)
+ proc.terminate()
+ try:
+ proc.wait(timeout=10)
+ except subprocess.TimeoutExpired:
+ proc.kill()
+ proc.wait()
+ if not RECORDS:
+ print(json.dumps({"error": "no measurement"}), file=sys.stderr)
+ return 1
+ print(json.dumps(RECORDS[0], indent=1))
+ return 0
+
+
+if __name__ == "__main__":
+ raise SystemExit(main())
diff --git a/packages/meshbay-hub/tests/test_hook_ordering.py b/packages/meshbay-hub/tests/test_hook_ordering.py
index 28ec93e..994ca2e 100644
--- a/packages/meshbay-hub/tests/test_hook_ordering.py
+++ b/packages/meshbay-hub/tests/test_hook_ordering.py
@@ -49,6 +49,9 @@ STATIC_FILES = [
# `useMemo` chain in the tree — a dozen derived lists, each depending on
# the one above it, which is precisely the shape this checks.
"search-page.js",
+ # The shared pop-up menu (docs/playlists.md §10.1), reached from the media
+ # views rather than imported by the shell.
+ "menu.js",
]
pytestmark = pytest.mark.skipif(not APP.exists(), reason="SPA sources unavailable")
diff --git a/packages/meshbay-hub/tests/test_music_queue.py b/packages/meshbay-hub/tests/test_music_queue.py
new file mode 100644
index 0000000..a53047d
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_music_queue.py
@@ -0,0 +1,115 @@
+"""
+Play, play next, add to queue — pressed in a real browser.
+
+`test_queue_ops.py` executes the reducer directly, which is where the index
+arithmetic is proved. It cannot reach any of this: whether a right-click opens
+a menu at all, whether the dots button still works now that a track row is a
+div holding two buttons rather than one big one, and whether `op` survives the
+trip from the menu through the view, the page's wrapper and the shell.
+
+That last one is not hypothetical. Both wrappers took `(tracks, startIndex)`
+and forwarded two arguments, so every "add to queue" in a group arrived at the
+player as a plain play and silently replaced the queue. Nothing about that
+reads as wrong at either end; this probe is what found it.
+
+The probe renders the shipped `GroupPage` and `MusicPlayerBar`, presses the
+real controls, and reads the queue out of the player's own panel.
+"""
+
+import json
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+HARNESS = Path(__file__).parent / "harness" / "music_queue_probe.py"
+STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("google-chrome") is None or not (STATIC / "queue-ops.js").exists(),
+ reason="Chrome or the SPA sources are not available")
+
+ALBUM = {n: [f"A{n}-t1", f"A{n}-t2", f"A{n}-t3"] for n in (1, 2, 3, 4)}
+
+
+@pytest.fixture(scope="module")
+def steps():
+ proc = subprocess.run(["python3", str(HARNESS)],
+ capture_output=True, text=True, timeout=300)
+ assert proc.returncode == 0, f"probe failed: {proc.stdout}{proc.stderr}"
+ out = json.loads(proc.stdout)
+ assert "error" not in out, out
+ assert not out.get("logs"), f"the page logged: {out['logs']}"
+ return {s["step"]: s for s in out["steps"]}
+
+
+def test_playing_a_track_queues_its_album(steps):
+ """The ordinary path, through a row that is no longer one single button."""
+ s = steps["play a track"]
+ assert s["play"] == ALBUM[1]
+ assert s["playing"] == 1
+ assert s["nowPlaying"] == "A1-t2"
+
+
+def test_right_click_opens_the_three_queue_verbs(steps):
+ """Three items, in the order the menu promises. Their labels are whatever
+ the browser's locale renders, so this counts them rather than reading them
+ — the point is that the menu opened and is not empty."""
+ assert len(steps["append album 2"]["menu"]) == 3
+
+
+def test_add_to_queue_appends_and_leaves_the_playhead_alone(steps):
+ """The bug this file exists for: this used to replace the queue."""
+ s = steps["append album 2"]
+ assert s["play"] == ALBUM[1] + ALBUM[2]
+ assert s["nowPlaying"] == "A1-t2", "appending moved what was playing"
+
+
+def test_play_next_lands_after_the_playing_track(steps):
+ """Reached through the dots button rather than a right-click, so both
+ affordances are exercised."""
+ s = steps["play next album 3"]
+ assert s["play"] == ["A1-t1", "A1-t2"] + ALBUM[3] + ["A1-t3"] + ALBUM[2]
+ assert s["nowPlaying"] == "A1-t2"
+
+
+def test_shuffling_keeps_everything_that_was_queued(steps):
+ on = steps["shuffle on"]
+ assert sorted(on["play"]) == sorted(ALBUM[1] + ALBUM[2] + ALBUM[3])
+ assert on["playing"] == 0 and on["nowPlaying"] == "A1-t2", (
+ "shuffle moved the track that was already playing")
+
+
+def test_shuffling_off_returns_to_the_order_tracks_were_added_in(steps):
+ """Not to the play order "play next" built: unshuffled *is* the order the
+ tracks arrived in, and that is what it has always meant. A track inserted
+ next while shuffled keeps its place only while shuffle is on."""
+ s = steps["shuffle off"]
+ assert s["play"] == ALBUM[1] + ALBUM[2] + ALBUM[3]
+ assert s["nowPlaying"] == "A1-t2"
+
+
+def test_play_all_replaces_everything(steps):
+ s = steps["replace with album 4"]
+ assert s["play"] == ALBUM[4]
+ assert s["playing"] == 0
+
+
+# ── the wrappers, read rather than driven ────────────────────────────────────
+#
+# The probe proves the chain works for the group page. Search mounts the same
+# view through a wrapper of its own, and there is no cheap way to drive that
+# page's index fetch here — so this reads the one thing that broke.
+
+@pytest.mark.parametrize("name", ["group-page.js", "search-page.js"])
+def test_the_music_wrapper_names_the_op_it_forwards(name):
+ """A wrapper that takes two arguments forwards two, and the third is lost
+ without a word. Both of these did exactly that."""
+ src = (STATIC / name).read_text()
+ marker = ("const onPlayQueue = useCallback((tracks, startIndex, op)"
+ if name == "group-page.js"
+ else "const handleMusicPlay = useCallback((tracks, startIndex, op)")
+ assert marker in src, (
+ f"{name}'s music wrapper no longer names `op`; every 'add to queue' "
+ f"and 'play next' reaching it becomes a plain play")
diff --git a/packages/meshbay-hub/tests/test_queue_ops.py b/packages/meshbay-hub/tests/test_queue_ops.py
new file mode 100644
index 0000000..64b5ca1
--- /dev/null
+++ b/packages/meshbay-hub/tests/test_queue_ops.py
@@ -0,0 +1,319 @@
+"""
+The music player's queue: replace, append, play-next, remove, reshuffle.
+
+The queue was replaceable and nothing else — every `onPlayQueue` reset
+`tracks`, `order` and `pos` together, which is all an album needs. Playlists
+add "play next" and "add to queue", which do not replace, and the three
+`useState`s they would have been built on cannot express an append correctly:
+`setOrder` needs the length `setTracks` is about to produce and cannot see it,
+so two enqueues batched into one tick both read the stale length and write
+indices past the end of `tracks`. `queue-ops.js` is one reducer over one state
+object, which is the only shape in which that is not a defect.
+
+The whole module is executed here rather than a regex-extracted function of it:
+it has no imports precisely so that it can be, and a copy of the reducer in a
+test would keep agreeing with the original right up until one of them changed.
+
+See docs/playlists.md §9.
+"""
+
+import json
+import re
+import shutil
+import subprocess
+from pathlib import Path
+
+import pytest
+
+STATIC = Path(__file__).resolve().parents[1] / "src" / "meshbay_hub" / "static"
+SRC = STATIC / "queue-ops.js"
+
+pytestmark = pytest.mark.skipif(
+ shutil.which("node") is None or not SRC.exists(),
+ reason="node or the SPA sources are not available")
+
+IMPORT = re.compile(r"^\s*import\b", re.M)
+EXPORT = re.compile(r"^export \{[^}]*\};?\s*$", re.M)
+
+
+@pytest.fixture(scope="module")
+def module_source():
+ text = SRC.read_text()
+ assert not IMPORT.search(text), (
+ "queue-ops.js has gained an import. It is executed standalone here, "
+ "and the queue is untested from the moment it cannot be — keep the "
+ "module free of imports, or this test needs a bundler")
+ stripped, n = EXPORT.subn("", text)
+ assert n == 1, (
+ "queue-ops.js no longer ends in a single export statement — the test "
+ "can no longer strip it to run the module")
+ return stripped
+
+
+def _run(tmp_path, module_source, body):
+ script = tmp_path / "case.js"
+ script.write_text(f"{module_source}\n{body}\n")
+ out = subprocess.run(
+ ["node", str(script)], capture_output=True, text=True, timeout=30)
+ assert out.returncode == 0, out.stderr
+ return json.loads(out.stdout)
+
+
+def _tracks(*ids):
+ return [{"id": i, "name": f"{i}.flac", "size": 1, "groupId": "g"} for i in ids]
+
+
+def _reduce(tmp_path, module_source, actions, start=None):
+ """Fold `actions` over the reducer, one after another, and report the end
+ state as ids so a test reads as the play order it means."""
+ body = f"""
+ let s = {json.dumps(start) if start else "emptyQueue()"};
+ for (const a of {json.dumps(actions)}) {{
+ // A deterministic shuffle: reverses the order, then keepFirst is
+ // pulled to the front by the reducer itself. Real randomness would
+ // make every shuffle assertion a coin toss.
+ s = queueReducer(s, {{ ...a, rand: () => 0 }});
+ }}
+ console.log(JSON.stringify({{
+ play: s.order.map((i) => s.tracks[i].id),
+ pos: s.pos,
+ playing: s.order.length ? s.tracks[s.order[s.pos]].id : null,
+ nTracks: s.tracks.length,
+ }}));
+ """
+ return _run(tmp_path, module_source, body)
+
+
+# ── replace: the path that already worked, pinned ────────────────────────────
+
+def test_replace_unshuffled_is_the_plain_order_from_the_requested_index(
+ tmp_path, module_source):
+ """What playing track 3 of an album has always done. If this changes,
+ every album in the application changed with it."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c", "d"), "startIndex": 2},
+ ])
+ assert out["play"] == ["a", "b", "c", "d"]
+ assert out["pos"] == 2
+ assert out["playing"] == "c"
+
+
+def test_replace_shuffled_keeps_the_requested_track_first(tmp_path, module_source):
+ """Shuffling on a chosen track must not start a different one."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c", "d"),
+ "startIndex": 2, "shuffle": True},
+ ])
+ assert out["pos"] == 0
+ assert out["playing"] == "c"
+ assert sorted(out["play"]) == ["a", "b", "c", "d"]
+
+
+def test_replace_discards_the_previous_queue(tmp_path, module_source):
+ """Loading a playlist replaces; it does not accumulate (docs §9.1)."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b")},
+ {"type": "replace", "tracks": _tracks("x", "y", "z")},
+ ])
+ assert out["play"] == ["x", "y", "z"]
+ assert out["nTracks"] == 3
+
+
+# ── append and play-next ─────────────────────────────────────────────────────
+
+def test_append_to_an_empty_queue_plays_it(tmp_path, module_source):
+ """Enqueueing with nothing playing has to start something, or the button
+ does nothing at all the first time it is pressed."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "append", "tracks": _tracks("a", "b")},
+ ])
+ assert out["play"] == ["a", "b"]
+ assert out["playing"] == "a"
+
+
+def test_append_goes_to_the_end_and_does_not_move_the_playhead(
+ tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c"), "startIndex": 1},
+ {"type": "append", "tracks": _tracks("x", "y")},
+ ])
+ assert out["play"] == ["a", "b", "c", "x", "y"]
+ assert out["playing"] == "b"
+
+
+def test_play_next_lands_immediately_after_what_is_playing(
+ tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c"), "startIndex": 0},
+ {"type": "insertNext", "tracks": _tracks("x")},
+ ])
+ assert out["play"] == ["a", "x", "b", "c"]
+ assert out["playing"] == "a"
+
+
+def test_play_next_on_the_last_track_still_lands_after_it(tmp_path, module_source):
+ """The splice index is past the end of `order`; a slice must cope rather
+ than dropping the entry silently."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b"), "startIndex": 1},
+ {"type": "insertNext", "tracks": _tracks("x")},
+ ])
+ assert out["play"] == ["a", "b", "x"]
+ assert out["playing"] == "b"
+
+
+def test_play_next_while_shuffled_inserts_into_the_play_order(
+ tmp_path, module_source):
+ """Not into `tracks` — the played sequence is `order`, and "next" means
+ next in what is actually being played."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c", "d"),
+ "startIndex": 0, "shuffle": True},
+ {"type": "insertNext", "tracks": _tracks("x")},
+ ])
+ assert out["play"][0] == "a"
+ assert out["play"][1] == "x"
+ assert out["playing"] == "a"
+
+
+def test_appending_nothing_is_not_a_change(tmp_path, module_source):
+ """An album card with no tracks must not clear the playhead."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b"), "startIndex": 1},
+ {"type": "append", "tracks": []},
+ ])
+ assert out["play"] == ["a", "b"]
+ assert out["playing"] == "b"
+
+
+# ── the defect this module exists to prevent ─────────────────────────────────
+
+def test_two_appends_in_one_tick_do_not_write_indices_past_the_end(
+ tmp_path, module_source):
+ """*The* reason the queue is a reducer (docs §9.3).
+
+ Two `useState`s updated from one event both read the length captured when
+ the handler was built, so the second append's indices collide with the
+ first's — a double click on "add to queue" produced a queue playing the
+ wrong tracks, or holes. Folding through the reducer is what a batched
+ render does, and every index has to be distinct and in range.
+ """
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b")},
+ {"type": "append", "tracks": _tracks("x")},
+ {"type": "append", "tracks": _tracks("y")},
+ ])
+ assert out["play"] == ["a", "b", "x", "y"], (
+ "an append read a stale track count — this is the three-useState bug")
+ assert out["nTracks"] == 4
+
+
+def test_many_appends_stay_in_range(tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a")},
+ ] + [{"type": "append", "tracks": _tracks(f"t{n}")} for n in range(20)])
+ assert out["play"] == ["a"] + [f"t{n}" for n in range(20)]
+ assert out["nTracks"] == 21
+
+
+# ── removal ──────────────────────────────────────────────────────────────────
+
+def test_removing_the_playing_track_slides_the_next_one_in(tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c"), "startIndex": 1},
+ {"type": "removeAt", "at": 1},
+ ])
+ assert out["play"] == ["a", "c"]
+ assert out["playing"] == "c"
+
+
+def test_removing_before_the_playhead_keeps_the_same_track_playing(
+ tmp_path, module_source):
+ """The index moved; what is playing must not."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c"), "startIndex": 2},
+ {"type": "removeAt", "at": 0},
+ ])
+ assert out["play"] == ["b", "c"]
+ assert out["playing"] == "c"
+
+
+def test_removing_the_last_remaining_track_does_not_leave_pos_dangling(
+ tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a")},
+ {"type": "removeAt", "at": 0},
+ ])
+ assert out["play"] == []
+ assert out["pos"] == 0
+ assert out["playing"] is None
+
+
+def test_removing_out_of_range_is_not_a_change(tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b"), "startIndex": 1},
+ {"type": "removeAt", "at": 7},
+ ])
+ assert out["play"] == ["a", "b"]
+ assert out["playing"] == "b"
+
+
+# ── shuffle ──────────────────────────────────────────────────────────────────
+
+def test_shuffling_on_mid_album_does_not_interrupt_what_is_playing(
+ tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c", "d"), "startIndex": 2},
+ {"type": "reshuffle", "shuffle": True},
+ ])
+ assert out["pos"] == 0
+ assert out["playing"] == "c"
+ assert sorted(out["play"]) == ["a", "b", "c", "d"]
+
+
+def test_shuffling_off_returns_to_the_album_order_at_the_same_track(
+ tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b", "c", "d"),
+ "startIndex": 2, "shuffle": True},
+ {"type": "reshuffle", "shuffle": False},
+ ])
+ assert out["play"] == ["a", "b", "c", "d"]
+ assert out["playing"] == "c"
+
+
+def test_shuffle_after_an_append_covers_the_appended_tracks(
+ tmp_path, module_source):
+ """`order` is rebuilt from `tracks.length`, so it has to have grown."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b")},
+ {"type": "append", "tracks": _tracks("x", "y")},
+ {"type": "reshuffle", "shuffle": True},
+ ])
+ assert sorted(out["play"]) == ["a", "b", "x", "y"]
+ assert out["playing"] == "a"
+
+
+def test_shuffling_a_queue_holding_the_same_track_twice_keeps_the_right_copy(
+ tmp_path, module_source):
+ """A queue could not hold duplicates until "add to queue" existed, and the
+ first reshuffle recovered the current index by searching `tracks` for the
+ playing entry's id — which finds the *first* copy. Enqueue a track that is
+ already in the queue, play the second copy, toggle shuffle, and playback
+ jumped backwards. `order[pos]` is the index and needs no search."""
+ out = _reduce(tmp_path, module_source, [
+ {"type": "replace", "tracks": _tracks("a", "b")},
+ {"type": "append", "tracks": _tracks("a")},
+ {"type": "skipTo", "pos": 2},
+ {"type": "reshuffle", "shuffle": False},
+ ])
+ assert out["pos"] == 2, "the reshuffle jumped to the first copy of 'a'"
+ assert out["playing"] == "a"
+
+
+def test_reshuffling_an_empty_queue_does_not_throw(tmp_path, module_source):
+ out = _reduce(tmp_path, module_source, [
+ {"type": "reshuffle", "shuffle": True},
+ ])
+ assert out["play"] == []
+ assert out["pos"] == 0
diff --git a/packages/meshbay-hub/tests/test_transport_contracts.py b/packages/meshbay-hub/tests/test_transport_contracts.py
index c10f183..5c535a3 100644
--- a/packages/meshbay-hub/tests/test_transport_contracts.py
+++ b/packages/meshbay-hub/tests/test_transport_contracts.py
@@ -43,6 +43,7 @@ SPLIT_FILES = [APP, GROUP_PAGE, CHAT_APP, STATIC / "files-app.js",
STATIC / "photos-app-settings.js",
STATIC / "helloworld-app.js",
STATIC / "helloworld-app-settings.js",
+ STATIC / "menu.js",
STATIC / "auth-page.js", STATIC / "explore-page.js",
CREATE_GROUP]