diff options
Diffstat (limited to 'packages/meshbay-hub/tests/harness')
4 files changed, 987 insertions, 3 deletions
diff --git a/packages/meshbay-hub/tests/harness/cast_session_probe.py b/packages/meshbay-hub/tests/harness/cast_session_probe.py new file mode 100644 index 0000000..573dd95 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/cast_session_probe.py @@ -0,0 +1,521 @@ +#!/usr/bin/env python3 +""" +A television chosen once, then photos and a film sent to it. + +Casting a photo or opening a film on a television chosen elsewhere is a claim +about four pieces at once: the cast button (cast-session.js), the lightbox +that follows it, the player that opens as a remote, and the native bridge the +page talks to. This renders the shipped `GroupPage` against a stub node and a +stub bridge that records what the page asks of it, and walks it as a reader +would: open an album, choose the television, page on, start a slideshow, +then open a film from Videos and stop casting from its remote. + +A second case renders the same page with no bridge at all — a browser — where +no cast button may appear. + + cast_session_probe.py Chrome, then Firefox +""" + +import http.server +import json +import shutil +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 = 8763 +RECORDS = [] +FINISHED = threading.Event() +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> +// A module that fails to load never reaches its own catch: say so. +const report = (error) => parent.postMessage({ error }, '*'); +// Scripts only: the music case's stub track is three bytes no <audio> +// element can decode, which is expected and is not the page failing. +addEventListener('error', (e) => { + if (!(e instanceof ErrorEvent) && !(e.target && e.target.tagName === 'SCRIPT')) return; + report(`${e.message || 'load error'} ${e.filename || (e.target && e.target.src) || ''}` + + `:${e.lineno || ''}`); +}, true); +addEventListener('unhandledrejection', + (e) => report(String((e.reason && e.reason.stack) || e.reason))); +const WITH_BRIDGE = !location.search.includes('nobridge'); +const ENTRIES = []; +for (let i = 1; i <= 3; i++) { + ENTRIES.push({ id: 'p' + i, name: 'photo' + i + '.png', path: 'photos/Trip', + type: 'image', size: 1000, added_at: 1750000000 + i }); +} +ENTRIES.push({ id: 'film', name: 'A.Film.mkv', display_title: 'A Film', + path: 'videos/films', type: 'video', duration: 6000, size: 1024, added_at: 1750000100 }); + +const ACK = { + is_node_admin: false, enabled_apps: ['video', 'photo'], + tmdb_enabled: true, tmdb_language: 'en-US', + video_directories: ['videos'], music_directories: [], photo_directories: ['photos'], +}; + +// A camera-sized picture, made here: 4000×3000, which the television must +// receive as 1440×1080. +let PHOTO = null; +async function photoBytes() { + if (PHOTO) return PHOTO; + const c = document.createElement('canvas'); + c.width = 4000; c.height = 3000; + const g = c.getContext('2d'); + g.fillStyle = '#3a7'; g.fillRect(0, 0, 4000, 3000); + const blob = await new Promise((r) => c.toBlob(r, 'image/png')); + PHOTO = new Uint8Array(await blob.arrayBuffer()); + return PHOTO; +} + +window.MeshBayCrypto = { + importGEK: async () => 'gek', + b64encode: (x) => String(x), + decryptChunkBin: async (_g, _f, _i, _n, ct) => ct, +}; + +window.MeshBayTransport = function () { + const self = { + connected: false, memberRole: 'member', supportsAppOps: true, + sessionKeys: null, gekRaw: 'k', + newNodeBundle: null, newNodeBundleRecovery: null, + async connect() { self.connected = true; return ACK; }, + async fetchIndex() { + return { entries: ENTRIES, dirs: ['photos', 'videos'], + roots: [{ name: 'photos', available: true, writable: false, removable: false }, + { name: 'videos', available: true, writable: false, removable: false }] }; + }, + async fetchMediaMeta() { return { confidence: 0 }; }, + // One chunk per photo: every photo is the same picture. + async fetchChunk() { return { nonce: 'n', ct: await photoBytes() }; }, + addReconnectListener() { return () => {}; }, + 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; }, + }); +}; + +// The native side, as the Electron preload and the Android shim present it, +// recording every cast call. +window.CALLS = []; +// What the stub receiver reports: the music case moves it along. +window.TV = { state: 'IDLE', position: 0, idle: null }; +if (WITH_BRIDGE) { + let connected = false, v = 0; + const rec = (name, arg) => { CALLS.push({ name, arg }); }; + window.meshbay = { + hubBase: () => '', + setLocale: async () => true, + capabilities: { lanCast: true, nodeAdmin: false, localFolders: false, nativeSave: false }, + cast: { + start: async (o) => { + rec('start', o && { codec: o.codec }); + return { url: 'http://tv/stream.mp4?t=x' }; + }, + push: async () => true, + stop: async () => { rec('stop'); return true; }, + subtitle: async () => null, + finish: async () => true, + file: async (f) => { + let info = { type: f.type, size: f.bytes.length, title: f.title || null, + artist: f.artist || null, album: f.album || null, cover: !!f.cover }; + if (f.type.startsWith('image/')) { + const bmp = await createImageBitmap(new Blob([f.bytes], { type: f.type })); + info = { ...info, width: bmp.width, height: bmp.height, + jpeg: f.bytes[0] === 0xff && f.bytes[1] === 0xd8 }; + } + rec('file', info); + return { url: 'http://tv/file?t=x&v=' + (++v) }; + }, + status: async () => ({ active: true, url: null, chromecast: { + connected, playerState: TV.state, position: TV.position, idleReason: TV.idle } }), + scan: async () => { rec('scan'); return true; }, + devices: async () => ({ devices: [{ id: 'tv1', name: 'Salon' }], scanning: false }), + chromecastConnect: async (o) => { + rec('connect', o); connected = true; + return { deviceName: 'Salon' }; + }, + chromecastReload: async (o) => { rec('reload', o); return { playerState: 'IDLE' }; }, + chromecastDisconnect: async () => { rec('disconnect'); connected = false; return true; }, + chromecastPause: async () => { rec('pause'); TV.state = 'PAUSED'; return {}; }, + chromecastPlay: async () => { rec('play'); TV.state = 'PLAYING'; return {}; }, + chromecastSeek: async (t) => { rec('seek', t); TV.position = t; return {}; }, + }, + }; +} +</script> +<script type="module"> +import { html, render } from '/vendor/htm-preact.js'; +import { initLocale } from '/i18n.js'; +import { GroupPage } from '/group-page.js'; + +const sleep = (ms) => new Promise((r) => setTimeout(r, ms)); +const $ = (sel) => document.querySelector(sel); +const $$ = (sel) => [...document.querySelectorAll(sel)]; +async function until(pred, what, tries = 200) { + for (let i = 0; i < tries; i++) { if (pred()) return; await sleep(50); } + throw new Error('timed out waiting for ' + what); +} +const calls = (name) => CALLS.filter((c) => c.name === name); +const files = () => calls('file').map((c) => c.arg); +// Files is always first; then the enabled apps in their registry order. +const videosTab = () => $$('.group-tab')[1]; +const count = () => (($('.photo-lightbox-count') || {}).textContent || '').trim(); + +// The music bar, with a television already chosen: two tracks of one album. +async function music() { + const { MusicPlayerBar } = await import('/music-player.js'); + const { castSession } = await import('/cast-session.js'); + const out = {}; + castSession.choose({ id: 'tv1', name: 'Salon' }); + // Which hashes were fetched, so a cover can be traced to where it came from. + window.FETCHED = []; + const transport = { connected: true, async waitForReconnect() {}, + async fetchChunk(id) { + FETCHED.push(id); + return { nonce: 'n', ct: new Uint8Array([1, 2, 3]) }; + }, + // The node's MusicBrainz answer: a cover for the other album only. + async fetchMusicMeta(id) { + CALLS.push({ name: 'musicMeta', arg: id }); + return id === 't3' ? { confidence: 1, cover_thumb_hash: 'mb-cover' } + : { confidence: 0 }; + } }; + const getConnection = async () => ({ transport, gek: 'gek' }); + // One has no cover of its own but Two, of the same album, has; Three is of + // another album whose only cover is the one the node found. + const track = (n, title, album, hash) => ({ id: 't' + n, name: title + '.mp3', size: 3, + groupId: 'g1', display_title: title, artist: 'Some Band', album, duration: 200, + thumb_hash: hash }); + const queue = { tracks: [track(1, 'One', 'An Album', null), track(2, 'Two', 'An Album', 'cover2'), + track(3, 'Three', 'Another Album', null)], startIndex: 0, nonce: 1 }; + render(html`<${MusicPlayerBar} getConnection=${getConnection} queue=${queue} + userPrefs=${{}} onClose=${() => {}} />`, document.getElementById('root')); + + await until(() => calls('connect').length === 1, 'the first track on the television'); + out.first = { file: files()[0], connect: calls('connect')[0].arg, + coverFetched: FETCHED.includes('cover2') }; + TV.state = 'PLAYING'; TV.position = 12; + await until(() => ($$('.music-player-time')[0] || {}).textContent === '0:12', + "the television's clock in the bar"); + out.barButton = !!$('.music-player-bar .cast-btn.casting'); + out.volumeDisabled = $('.music-player-volume input').disabled; + + $('.music-player-play').click(); + await until(() => calls('pause').length === 1, 'pause on the television'); + const slider = $('.music-player-seek input'); + slider.value = '30'; + slider.dispatchEvent(new Event('input', { bubbles: true })); + await until(() => calls('seek').length === 1, 'a seek on the television'); + out.seek = calls('seek')[0].arg; + + // The television finishes the track: the next one goes, once. + TV.state = 'IDLE'; TV.idle = 'FINISHED'; + await until(() => calls('reload').length === 1, 'the next track on the television'); + out.second = { file: files()[1], reload: calls('reload')[0].arg, + title: $('.music-player-title').textContent.trim() }; + TV.state = 'PLAYING'; TV.idle = null; TV.position = 1; + await sleep(2500); + out.filesAfterSettling = files().length; + + // Three: the cover comes from the node's answer for its album. + TV.state = 'IDLE'; TV.idle = 'FINISHED'; + await until(() => calls('reload').length === 2, 'the third track on the television'); + out.third = { file: files()[2], mbCover: FETCHED.includes('mb-cover'), + metaAsked: calls('musicMeta').map((c) => c.arg) }; + TV.state = 'PLAYING'; TV.idle = null; + + // Stopping the cast lets the television go. + await castSession.end(); + await sleep(200); + out.afterStop = { disconnects: calls('disconnect').length, + barCasting: !!$('.music-player-bar .cast-btn.casting') }; + parent.postMessage(out, '*'); +} + +(async () => { + const out = { bridge: !!window.meshbay }; + if (location.search.includes('music')) { + try { await initLocale(); await music(); } + catch (err) { + parent.postMessage({ calls: CALLS, error: String((err && err.stack) || err) }, '*'); + } + return; + } + try { + await initLocale(); + render(html`<${GroupPage} groupId="g1" token="t" username="me" userId="u1" + group=${{ id: 'g1', name: 'a group', owner_username: 'me', is_admin: false }} + userPrefs=${{ default_tab: 'photo', media_page_size: '50' }} />`, + document.getElementById('root')); + + await until(() => $('.photo-album-card'), 'the album card'); + out.landingButton = !!$('.photo-toolbar .cast-btn'); + $('.photo-album-card').click(); + await until(() => $('.photo-album-bar'), 'the album'); + out.albumButton = !!$('.photo-album-bar .cast-btn'); + + if (!window.meshbay) { + videosTab().click(); + await until(() => $('.video-toolbar'), 'the videos toolbar'); + out.videosButton = !!$('.video-toolbar .cast-btn'); + parent.postMessage(out, '*'); + return; + } + + // Choose the television from the album: the first photo opens and goes. + $('.photo-album-bar .cast-btn').click(); + await until(() => $$('.cast-menu .ctx-menu-item').some((b) => b.textContent.includes('Salon')), + 'the receiver in the menu'); + $$('.cast-menu .ctx-menu-item').find((b) => b.textContent.includes('Salon')).click(); + await until(() => $('.photo-lightbox'), 'the lightbox to open on choosing'); + await until(() => calls('connect').length === 1, 'the first photo to reach the television'); + out.first = { count: count(), image: files()[0], connect: calls('connect')[0].arg, + lightboxCasting: !!$('.photo-lightbox .cast-btn.casting') }; + + // Next photo: the receiver is connected, so it is reloaded. + $('.photo-nav-next').click(); + await until(() => calls('reload').length === 1, 'the second photo'); + out.second = { count: count(), reload: calls('reload')[0].arg, images: files().length }; + + // Slideshow: on by itself to the last photo, then off. + const play = $$('.photo-lightbox .video-top-bar .video-close') + .find((b) => b.getAttribute('aria-pressed') !== null); + play.click(); + await until(() => count() === '3 / 3', 'the slideshow to reach the last photo', 160); + await until(() => play.getAttribute('aria-pressed') === 'false', 'the slideshow to end', 160); + out.slideshow = { count: count(), images: files().length, + reloads: calls('reload').length }; + + // Close the lightbox; Videos shows the same television; a film opens as its remote. + $$('.photo-lightbox .video-top-bar .video-close').pop().click(); + await until(() => !$('.photo-lightbox'), 'the lightbox to close'); + videosTab().click(); + await until(() => $('.video-toolbar'), 'the videos toolbar'); + out.videosCasting = !!$('.video-toolbar .cast-btn.casting'); + await until(() => $('.video-card'), 'the film card'); + $('.video-card').click(); + await until(() => $('.video-detail .admin-btn'), 'the film modal'); + $('.video-detail .admin-btn').click(); + await until(() => $('.video-remote'), 'the player as a remote'); + out.remote = { device: $('.video-remote-device').textContent.trim(), + pickerOpen: !!$('.video-player-overlay .cast-picker') }; + + // Stop from the remote: forgotten for the session. + $$('.video-remote button').pop().click(); + await until(() => !$('.video-remote'), 'the remote to go'); + $$('.video-player-overlay .video-top-bar .video-close').pop().click(); + await until(() => !$('.video-player-overlay'), 'the player to close'); + await sleep(100); + out.afterStop = { videosCasting: !!$('.video-toolbar .cast-btn.casting'), + disconnects: calls('disconnect').length }; + parent.postMessage(out, '*'); + } catch (err) { + parent.postMessage({ ...out, calls: CALLS, error: String((err && err.stack) || err) }, '*'); + } +})(); +</script></body></html>""" + +# Firefox headless runs a page only while taking its screenshot, which is taken +# once the page has loaded: an image that does not answer until the case has +# reported keeps it loading (the same hold as invitation_probe.py). +HOLD_TAG = '<img src="/hold" style="position:fixed;left:-4px;top:-4px;width:1px">' + +PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head> +<body style="margin:0"> +<iframe src="/case{query}" style="width:1100px;height:800px;border:0"></iframe> +<script> +addEventListener('message', (e) => fetch('/log', { method: 'POST', body: JSON.stringify(e.data) })); +</script>{hold}</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())) + FINISHED.set() + 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, _, query = self.path.partition("?") + if path == "/hold": + FINISHED.wait(90) + self._send(b"", "image/gif") + elif path == "/": + q = f"?{query.replace('engine=firefox', '').strip('&')}" if query else "" + hold = HOLD_TAG if "engine=firefox" in query else "" + page = PAGE.replace("{query}", q if q != "?" else "").replace("{hold}", hold) + 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 browse(engine: str, query: str) -> dict | None: + RECORDS.clear() + FINISHED.clear() + sep = "&" if query else "?" + url = f"http://127.0.0.1:{PORT}/{query}{sep + 'engine=firefox' if engine == 'firefox' else ''}" + # Firefox is a snap here, and needs its profile under $HOME (invitation_probe.py). + snap = Path.home() / "snap" / "firefox" / "common" + parent = (str(snap if snap.is_dir() else Path.home()) if engine == "firefox" else None) + with tempfile.TemporaryDirectory(ignore_cleanup_errors=True, prefix="meshbay-probe-", + dir=parent) as profile: + if engine == "chrome": + cmd = ["google-chrome", "--headless=new", "--disable-gpu", "--no-sandbox", + f"--user-data-dir={profile}", "--window-size=1100,900", url] + else: + cmd = ["firefox", "--headless", "--profile", profile, "--window-size=1100,900", + "--screenshot", str(Path(profile) / "shot.png"), url] + proc = subprocess.Popen(cmd, stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + deadline = time.time() + 90 + while not RECORDS and time.time() < deadline: + time.sleep(0.2) + proc.terminate() + try: + proc.wait(timeout=20) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + return RECORDS[0] if RECORDS else None + + +def check(engine: str, cast: dict, plain: dict) -> list[str]: + bad = [] + if "error" in cast: + return [f"{engine}: {cast['error']}"] + if not cast["landingButton"]: + bad.append("no cast button on the Photos landing") + if not cast["albumButton"]: + bad.append("no cast button in the album bar") + first = cast["first"] + if first["count"] != "1 / 3": + bad.append(f"choosing a television did not open the first photo: {first['count']}") + img = first["image"] + if not (img["type"] == "image/jpeg" and img["jpeg"] and img["width"] == 1440 + and img["height"] == 1080): + bad.append(f"the photo did not leave as a 1440x1080 JPEG: {img}") + if first["connect"] != {"deviceId": "tv1", "mediaUrl": "http://tv/file?t=x&v=1", + "startAt": 0}: + bad.append(f"connect: {first['connect']}") + if not first["lightboxCasting"]: + bad.append("the lightbox's cast button does not say it is casting") + if cast["second"]["count"] != "2 / 3" or cast["second"]["reload"] != { + "mediaUrl": "http://tv/file?t=x&v=2", "startAt": 0}: + bad.append(f"next photo: {cast['second']}") + if cast["slideshow"]["count"] != "3 / 3" or cast["slideshow"]["images"] != 3: + bad.append(f"slideshow: {cast['slideshow']}") + if not cast["videosCasting"]: + bad.append("Videos does not show the television chosen in Photos") + if cast["remote"]["device"] != "Salon" or cast["remote"]["pickerOpen"]: + bad.append(f"the film did not open as the television's remote: {cast['remote']}") + if cast["afterStop"]["videosCasting"] or cast["afterStop"]["disconnects"] < 1: + bad.append(f"stopping from the remote: {cast['afterStop']}") + if "error" in plain: + bad.append(f"no bridge: {plain['error']}") + elif plain["landingButton"] or plain["albumButton"] or plain["videosButton"]: + bad.append(f"a cast button without a bridge: {plain}") + return [f"{engine}: {b}" for b in bad] + + +def check_music(engine: str, m: dict) -> list[str]: + if "error" in m: + return [f"{engine}: music: {m['error']}"] + bad = [] + f = m["first"]["file"] + if not (f["type"] == "audio/mpeg" and f["title"] == "One" and f["artist"] == "Some Band" + and f["album"] == "An Album" and f["cover"] and m["first"]["coverFetched"]): + bad.append(f"the first track left without its album's cover: {m['first']}") + third = m["third"] + if not (third["file"]["title"] == "Three" and third["file"]["cover"] and third["mbCover"]): + bad.append(f"the node's cover did not reach the television: {third}") + if "t1" in third["metaAsked"] or "t2" in third["metaAsked"]: + bad.append(f"the node was asked for a cover a track already had: {third['metaAsked']}") + if m["first"]["connect"] != {"deviceId": "tv1", "mediaUrl": "http://tv/file?t=x&v=1", + "startAt": 0}: + bad.append(f"connect: {m['first']['connect']}") + if not m["barButton"]: + bad.append("the music bar's cast button does not say it is casting") + if not m["volumeDisabled"]: + bad.append("the volume slider still acts while casting") + if m["seek"] != 30: + bad.append(f"seek: {m['seek']}") + s = m["second"] + if s["file"]["title"] != "Two" or s["title"] != "Two" or s["reload"] != { + "mediaUrl": "http://tv/file?t=x&v=2", "startAt": 0}: + bad.append(f"the end of a track did not move the queue on: {s}") + if m["filesAfterSettling"] != 2: + bad.append(f"a finished track moved the queue on more than once: {m['filesAfterSettling']}") + if m["afterStop"]["disconnects"] < 1 or m["afterStop"]["barCasting"]: + bad.append(f"stopping: {m['afterStop']}") + return [f"{engine}: music: {b}" for b in bad] + + +def main() -> int: + failures = [] + with socketserver.ThreadingTCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + for engine in ("chrome", "firefox"): + if shutil.which("google-chrome" if engine == "chrome" else engine) is None: + print(f"{engine}: not installed, skipped") + continue + cast = browse(engine, "") + plain = browse(engine, "?nobridge") + music = browse(engine, "?music") + if cast is None or plain is None or music is None: + failures.append(f"{engine}: the page never reported") + continue + print(f"{engine}:", json.dumps({"photos-videos": cast, "music": music}, indent=1)) + failures += check(engine, cast, plain) + failures += check_music(engine, music) + for f in failures: + print("FAIL", f, file=sys.stderr) + if not failures: + print("OK") + return 1 if failures else 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/packages/meshbay-hub/tests/harness/copy_link_probe.py b/packages/meshbay-hub/tests/harness/copy_link_probe.py new file mode 100644 index 0000000..564d277 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/copy_link_probe.py @@ -0,0 +1,270 @@ +#!/usr/bin/env python3 +""" +"Copy link" in Files, Music and Photos, in a real browser. + +Mounts the shipped `FilesPanel`, `MusicApp` and `PhotosApp` on a made-up +index — no node, no transport — with the `linkFor` a group page gives them, +built by the real `copy-link.js` for a group `demo@someowner`. Opens each +menu the way a reader would (right-click; the dots on a phone; the Files +toolbar with one row ticked), picks "Copy link", and reads back what reached +the clipboard and what the page said. + + copy_link_probe.py + +Prints JSON: one entry per case. +""" + +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 = 8775 +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> +<div id="files"></div><div id="music"></div><div id="photos"></div> +<script type="module"> +import { html, render } from '/vendor/htm-preact.js'; +import { initLocale, setLocale } from '/i18n.js'; +import { FilesPanel } from '/files-app.js'; +import { MusicApp } from '/music-app.js'; +import { PhotosApp } from '/photos-app.js'; +import { groupItemLink, entryPath } from '/copy-link.js'; + +const LOGS = []; +addEventListener('error', (e) => LOGS.push('error: ' + (e.message || e))); +addEventListener('unhandledrejection', + (e) => LOGS.push('rejection: ' + (e.reason && e.reason.message || e.reason))); +const frame = () => new Promise((r) => requestAnimationFrame(() => requestAnimationFrame(r))); +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); + +// What the clipboard was handed, and nothing else: a headless page has no +// clipboard permission to test against. +const COPIES = []; +Object.defineProperty(navigator, 'clipboard', { configurable: true, + value: { writeText: async (text) => { COPIES.push(text); } } }); + +const GROUP = { name: 'demo', owner_username: 'someowner' }; +const linkFor = (target) => (target + ? groupItemLink(GROUP, typeof target === 'string' ? target : entryPath(target)) : null); +const noop = () => {}; +const ref = { current: null }; + +const labels = () => [...document.querySelectorAll('.ctx-menu .ctx-menu-label')] + .map((el) => el.textContent); +const pick = async (label) => { + const item = [...document.querySelectorAll('.ctx-menu .ctx-menu-item')] + .find((b) => b.querySelector('.ctx-menu-label').textContent === label); + if (!item) return false; + item.click(); + await wait(50); + return true; +}; +const note = () => (document.querySelector('.page-note') || {}).textContent || ''; +const closeMenus = async () => { + document.body.dispatchEvent(new MouseEvent('mousedown', { bubbles: true })); + await frame(); +}; +const rightClick = async (el) => { + await closeMenus(); + const r = el.getBoundingClientRect(); + el.dispatchEvent(new MouseEvent('contextmenu', { bubbles: true, cancelable: true, + clientX: r.left + 10, clientY: r.top + 5 })); + await frame(); +}; +const rowNamed = (name) => [...document.querySelectorAll('tr.file-row')] + .find((tr) => tr.querySelector('.file-name') + && tr.querySelector('.file-name').textContent.trim().startsWith(name)); + +(async () => { + const cases = []; + try { + setLocale('en'); + await initLocale(); + try { localStorage.setItem('meshbay_music_view_mode', 'flat'); } catch {} + + // -- Files -- + const FILES = [ + { id: 'f1', name: 'IMG 0001.JPG', path: 'Root/trip_2015', size: 10, type: 'image', + added_at: 1 }, + { id: 'f2', name: 'notes.txt', path: 'Root/trip_2015', size: 5, type: 'document', + added_at: 2 }, + ]; + render(html`<${FilesPanel} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${FILES} nodeDirs=${['Root', 'Root/trip_2015']} + nodeRoots=${[{ name: 'Root', writable: false }]} + setEntries=${noop} setNodeDirs=${noop} setNodeRoots=${noop} applyIndex=${noop} + isNodeAdmin=${false} operatorPaired=${false} userId="me" setError=${noop} + onPreview=${noop} linkFor=${linkFor} />`, document.getElementById('files')); + await frame(); + + await rightClick(rowNamed('Root')); + const folderLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'files folder', labels: folderLabels, copied: COPIES.at(-1), note: note() }); + + rowNamed('Root').click(); await frame(); + rowNamed('trip_2015').click(); await frame(); + await rightClick(rowNamed('IMG 0001.JPG')); + const fileLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'files file', labels: fileLabels, copied: COPIES.at(-1), note: note() }); + + await closeMenus(); + const linkBtn = () => document.querySelector('.tb-actions button[aria-label="Copy link"]'); + rowNamed('notes.txt').querySelector('input[type=checkbox]').click(); await frame(); + const oneTicked = linkBtn() ? !linkBtn().disabled : null; + if (linkBtn() && !linkBtn().disabled) { linkBtn().click(); await wait(50); } + const copiedFromToolbar = COPIES.at(-1); + for (const n of ['IMG 0001.JPG', 'notes.txt']) { + rowNamed(n).querySelector('input[type=checkbox]').click(); await frame(); + } + const twoTicked = linkBtn() ? !linkBtn().disabled : null; + cases.push({ case: 'files toolbar', one_enabled: oneTicked, two_enabled: twoTicked, + copied: copiedFromToolbar }); + render(null, document.getElementById('files')); + + // -- Music: a loose track, its row's dots (what a phone has) -- + const TRACKS = [ + { id: 'a1', name: 'track 01.flac', path: 'Music/Some Album', size: 3, type: 'audio' }, + { id: 'a2', name: 'track 02.flac', path: 'Music/Some Album', size: 3, type: 'audio' }, + ]; + render(html`<${MusicApp} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${TRACKS} musicDirectories=${['Music']} + musicbrainzConfig=${{ enabled: false }} onPlayQueue=${noop} userId="" + linkFor=${linkFor} />`, document.getElementById('music')); + await frame(); + await closeMenus(); + const dots = document.querySelector('.music-flat-track .ctx-dots'); + if (dots) { dots.click(); await frame(); } + const trackLabels = labels(); + await pick('Copy link'); + cases.push({ case: 'music track', dots: Boolean(dots), labels: trackLabels, + copied: COPIES.at(-1) }); + render(null, document.getElementById('music')); + + // -- Photos: right-click a tile; the lightbox's button -- + const PHOTOS = [ + { id: 'p1', name: 'beach.jpg', path: 'Pics/Summer', size: 4, type: 'image', added_at: 1 }, + ]; + render(html`<${PhotosApp} groupId="g" transportRef=${ref} gekRef=${ref} + status="connected" entries=${PHOTOS} photoDirectories=${['Pics']} + setError=${noop} linkFor=${linkFor} />`, document.getElementById('photos')); + await frame(); + const album = document.querySelector('.photo-album-card'); + if (album) { album.click(); await frame(); } + const tile = document.querySelector('.photo-tile'); + let tileLabels = []; + if (tile) { + await rightClick(tile); + tileLabels = labels(); + await pick('Copy link'); + } + const fromTile = COPIES.at(-1); + if (tile) { tile.click(); await frame(); } + const lb = document.querySelector('.photo-lightbox button[aria-label="Copy link"]'); + COPIES.length = 0; + if (lb) { lb.click(); await wait(50); } + cases.push({ case: 'photos', tile: Boolean(tile), labels: tileLabels, copied: fromTile, + lightbox_button: Boolean(lb), lightbox_copied: COPIES.at(-1) || null }); + + // Said, then gone (note.js): still up just after, not 2.5 s later. + const upAfterCopy = Boolean(document.querySelector('.page-note')); + await wait(2700); + cases.push({ case: 'note goes', up_after_copy: upAfterCopy, + up_later: Boolean(document.querySelector('.page-note')) }); + + parent.postMessage({ cases, logs: LOGS, origin: location.origin }, '*'); + } catch (err) { + parent.postMessage({ error: String(err && (err.stack || err)), logs: LOGS }, '*'); + } +})(); +</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") + 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(300): + 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/harness/group_link_probe.py b/packages/meshbay-hub/tests/harness/group_link_probe.py new file mode 100644 index 0000000..2d7c0d7 --- /dev/null +++ b/packages/meshbay-hub/tests/harness/group_link_probe.py @@ -0,0 +1,176 @@ +#!/usr/bin/env python3 +""" +A group link, `#/name@owner[/path]`, opened in the real application. + +`test_group_link.py` runs `group-link.js` on its own; this is where it meets +the router, the account's group list and the sign-in state. Loads the shipped +`app.js` in a real browser with `fetch` stubbed (no node answers, so a group +page goes as far as "offline"), once per case: + + handle — `#/demo@someowner`: the group page, the address left as it is + uuid — `#/group/<id>`: the same page, the address showing the handle + file — `#/demo@someowner/<path>`: the page, the path kept in the address + until the index can say what it is (no node here: never) + unknown — `#/demo@stranger1`: not among the account's groups + signed_out — `#/demo@someowner/<path>` with no session: the sign-in form, and + the address untouched under it + + group_link_probe.py + +Prints JSON: one object per case. +""" + +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 = 8774 +RECORDS = [] +socketserver.TCPServer.allow_reuse_address = True + +GROUP = "0f8fad5b-d9cb-469f-a165-70867728950e" +FILE = "backup/city_2015/backup/IMG_0001.JPG" +LINKS = { + "handle": "#/demo@someowner", + "uuid": f"#/group/{GROUP}", + "file": f"#/demo@someowner/{FILE}", + "unknown": "#/demo@stranger1", + "signed_out": f"#/demo@someowner/{FILE}", +} +CASES = list(LINKS) + +PAGE = r"""<!doctype html><html><head><meta charset=utf-8></head><body> +<div id="app"></div> +<script type="module"> +const CASE = new URLSearchParams(location.search).get('case'); +const LINKS = __LINKS__; +const realFetch = window.fetch.bind(window); +const post = (o) => realFetch('/log', { method: 'POST', body: JSON.stringify(o) }); +const calls = []; +const json = (body, status = 200) => ({ + ok: status < 400, status, statusText: '', headers: new Headers(), + json: async () => body, text: async () => JSON.stringify(body), +}); +window.fetch = async (url, init = {}) => { + const u = String(url); + calls.push(u); + if (u.includes('/v1/users/me/preferences')) return json({}); + if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' }); + if (u.includes('/v1/groups/mine')) return json({ groups: [ + { id: '__GROUP__', name: 'demo', owner_username: 'someowner', visibility: 'private', + created_at: '2026-01-01T00:00:00+00:00', description: '' }, + { id: 'other-group', name: 'demo', owner_username: 'otherowner', visibility: 'private', + created_at: '2026-01-01T00:00:00+00:00', description: '' }, + ] }); + if (u.includes('/nodes')) return json({ nodes: [] }); + return json({}); +}; +if (CASE === 'signed_out') { + localStorage.removeItem('mb_auth'); +} else { + localStorage.setItem('mb_auth', JSON.stringify({ + username: 'member-account', userId: 'u-1', token: 'tok', refreshToken: 'ref', + role: 'user' })); +} +sessionStorage.clear(); +history.replaceState(null, '', '/?case=' + CASE + LINKS[CASE]); + +const wait = (ms) => new Promise((r) => setTimeout(r, ms)); +(async () => { + const out = { case: CASE }; + try { + await import('/app.js'); + await wait(2000); + out.hash = decodeURI(location.hash); + out.history_length = history.length; + out.group_page = Boolean(document.querySelector('.group-header')); + out.group_title = (document.querySelector('.group-header h2') || {}).innerText || ''; + out.active_sidebar = [...document.querySelectorAll('.sidebar-group.active')] + .map((a) => a.getAttribute('href')); + out.message = (document.querySelector('main .page-message') || {}).innerText || ''; + out.spinner = Boolean(document.querySelector('main .page-message .spinner')); + out.login_form = Boolean(document.querySelector('input[type=password]')); + out.hub_calls = calls.map((c) => c.replace(/^https?:\/\/[^/]+/, '')); + } catch (e) { + out.error = String(e && e.stack || e); + } + post(out); +})(); +</script></body></html> +""".replace("__GROUP__", GROUP).replace("__LINKS__", json.dumps(LINKS)) + + +class H(http.server.SimpleHTTPRequestHandler): + def log_message(self, *a): + pass + + def do_POST(self): + length = int(self.headers.get("Content-Length") or 0) + body = self.rfile.read(length) + if self.path == "/log": + RECORDS.append(json.loads(body.decode())) + 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") + return + 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 + ctype = "text/javascript" if asset.suffix in (".js", ".mjs") else ( + "application/wasm" if asset.suffix == ".wasm" else "application/octet-stream") + self._send(asset.read_bytes(), ctype) + + +def _run(case: str) -> dict | None: + before = len(RECORDS) + 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}", f"http://127.0.0.1:{PORT}/?case={case}"], + stdout=subprocess.DEVNULL, stderr=subprocess.DEVNULL) + for _ in range(300): + if len(RECORDS) > before: + break + time.sleep(0.1) + proc.terminate() + try: + proc.wait(timeout=10) + except subprocess.TimeoutExpired: + proc.kill() + proc.wait() + return RECORDS[before] if len(RECORDS) > before else None + + +def main() -> int: + with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: + threading.Thread(target=srv.serve_forever, daemon=True).start() + results = [_run(case) for case in CASES] + if not all(results): + print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr) + return 1 + print(json.dumps(results, indent=1)) + return 0 + + +if __name__ == "__main__": + raise SystemExit(main()) diff --git a/packages/meshbay-hub/tests/harness/invite_link_probe.py b/packages/meshbay-hub/tests/harness/invite_link_probe.py index 97ee893..b0a833e 100644 --- a/packages/meshbay-hub/tests/harness/invite_link_probe.py +++ b/packages/meshbay-hub/tests/harness/invite_link_probe.py @@ -13,6 +13,9 @@ Loads the shipped `app.js` in a real browser with `fetch` stubbed, twice: signed_out — a link, no session signed_in — the same link, a session; then the Join button is clicked + signed_in_listed — the same, with the hub listing the group once joined, as + it does: the group page opens and the address shows its handle + (`#/name@owner`, group-link.js) invite_link_probe.py @@ -56,7 +59,15 @@ window.fetch = async (url, init = {}) => { calls.push({ url: u, body: init.body ? String(init.body) : '' }); if (u.includes('/v1/users/me/preferences')) return json({}); if (u.includes('/v1/users/me')) return json({ user_id: 'u-1', role: 'user' }); - if (u.includes('/v1/groups/mine')) return json({ groups: [] }); + // Joined, the hub lists the group — in the one case that says so. The others + // keep an empty list, so the address stays the `#/group/<id>` the Join + // button navigated to and is read before the router could rewrite it. + if (u.includes('/v1/groups/mine')) return json({ groups: + CASE === 'signed_in_listed' && calls.some((c) => c.url.includes('/redeem')) + ? [{ id: '__GROUP__', name: 'Some Group', owner_username: 'the-owner', + visibility: 'private', created_at: '2026-01-01T00:00:00+00:00', + description: '' }] + : [] }); if (u.includes('/v1/invite-links/preview')) return json({ group_id: '__GROUP__', group_name: 'Some Group', inviter: 'the-owner', expires_at: '2099-01-01T00:00:00+00:00', already_member: false }); @@ -65,7 +76,7 @@ window.fetch = async (url, init = {}) => { if (u.includes('/nodes')) return json({ nodes: [] }); return json({}); }; -if (CASE === 'signed_in') { +if (CASE.startsWith('signed_in')) { localStorage.setItem('mb_auth', JSON.stringify({ username: 'invitee-account', userId: 'u-1', token: 'tok', refreshToken: 'ref', role: 'user' })); @@ -98,6 +109,12 @@ const text = () => document.getElementById('app').innerText; out.join_button = Boolean(join); if (join) { join.click(); await wait(1500); } out.hash_after_click = location.hash; + if (CASE === 'signed_in_listed') { + await wait(1500); + out.hash_settled = decodeURI(location.hash); + out.group_page = Boolean(document.querySelector('.group-header')); + out.history_length = history.length; + } out.redeem_bodies = calls.filter((c) => c.url.includes('/redeem')).map((c) => c.body); } out.code_in_a_hub_request = calls.some( @@ -169,7 +186,7 @@ def _run(case: str) -> dict | None: def main() -> int: with socketserver.TCPServer(("127.0.0.1", PORT), H) as srv: threading.Thread(target=srv.serve_forever, daemon=True).start() - results = [_run("signed_out"), _run("signed_in")] + results = [_run("signed_out"), _run("signed_in"), _run("signed_in_listed")] if not all(results): print(json.dumps({"error": "no measurement", "got": results}), file=sys.stderr) return 1 |