misterdownloadmanager: The ultimate open-source, clean-room download manager written from scratch in pure Rust for Windows, Mac, and Linux
Rust bittorrent-clientdebriddownload-acceleratordownload-managerdownloadmanagereguifile-downloadergallery-dlidmidm-alternativeinternet-download-managerm3u8-downloadermagnetplaylist-downloaderreal-debridrusttorrent-clientvideo-downloaderyoutube-downloaderyt-dlp
Lab: the Linux test machine, scripted, with harnesses for PR checks (#164) (#200)
Ahmed Nefzaoui60c2564e6c78
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex bbc09b5d..e8def485 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -275,6 +275,15 @@ Each release's notes on GitHub come from its section here (`## [X.Y.Z]`, see### Changed+- **Developers: a Linux test machine, scripted** (part of [#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164)):+ `tools/lab/linux-vm/` sets up an Ubuntu 24.04 desktop in VirtualBox from a Windows host+ (`vm.ps1`: hardware, headless start, linked clones; `setup.sh`: packages, Rust, Node, the+ browsers, UI automation, an unlocked keyring), builds any branch or pull request there with a+ quick test profile (`build.sh`), and checks pull requests on it: windows shot and compared+ pixel by pixel (`shots.sh`, `shot-host.sh`, `pixdiff.py`), HLS and DASH hand-overs from the Snap+ Firefox and Google Chrome (`streams.mjs`, `streams-chrome.mjs`), the extension's proxy switch+ (`proxy-optin.mjs`), hand-overs and the Scheduler while minimized, torrents without a network,+ and MDM's start-up time (`measure.sh`). Every change is now checked on Linux as on Windows.- **Developers: the engine tests no longer fail on a busy computer**([#136](https://github.com/anefzaoui/misterdownloadmanager/issues/136)). Three end-to-end testsdepended on timing: a refused connection coming back, the learned connection limit, and a deaddiff --git a/ROADMAP.md b/ROADMAP.mdindex fc790305..7eeacd75 100644--- a/ROADMAP.md+++ b/ROADMAP.md@@ -13,6 +13,9 @@ Everything below ships together, in one release, as version 0.3.0.### Done+- ✅ A Linux test machine for every change, scripted: an Ubuntu 24.04 desktop that builds each+ branch and drives MDM, Firefox and Chrome there (part of+ [#164](https://github.com/anefzaoui/misterdownloadmanager/issues/164))- ✅ Firefox: reading the browser's proxy (#42) is an opt-in, a switch in the extension's popup, sothe extension's update asks for no new permission; Chrome's extension leaves it out for now- ✅ Streams whose address doesn't end in .m3u8 or .mpd, served as plain text, are found too: bydiff --git a/tools/lab/linux-vm/build.sh b/tools/lab/linux-vm/build.shnew file mode 100644index 00000000..f485fb59--- /dev/null+++ b/tools/lab/linux-vm/build.sh@@ -0,0 +1,38 @@+#!/usr/bin/env bash+# Build the checkout (~/mdm) in a terminal on the lab's desktop, so whoever watches the VM follows+# it; the output is also kept in ~/lab/build.log for the host to read. The programs are then copied+# to ~/lab/bin/<label>/ (default: the ref's name), so builds of several branches can be compared.+#+# bash build.sh [<branch, pr/<number> or commit>] [<label>] # e.g. main, fix/foo, pr/167+#+# MDM_PROFILE picks the cargo profile: `vmtest` (default; setup.sh defines it in ~/.cargo/config.toml:+# release without LTO, incremental, a few minutes per branch) for functional checks, `release`+# (fat LTO, what ships) when a check measures speed or size. Six jobs leave two cores to the desktop.+set -uo pipefail+. "$HOME/.cargo/env"+cd "$HOME/mdm" || exit 1+ref_name=${1:-HEAD}+if [ $# -gt 0 ]; then+ git fetch -q origin '+refs/heads/*:refs/remotes/origin/*' '+refs/pull/*/head:refs/remotes/origin/pr/*'+ ref=$(git rev-parse -q --verify "origin/$1^{commit}" || git rev-parse -q --verify "$1^{commit}") || {+ echo "== no branch, PR or commit named $1"; exit 1; }+ git checkout -q --detach "$ref"+fi+profile=${MDM_PROFILE:-vmtest}+label=${2:-$(echo "$ref_name" | tr '/' '-')}+mkdir -p "$HOME/lab"+log="$HOME/lab/build.log"+{+ echo "== $(git log --oneline -1)"+ echo "== cargo build --profile $profile -j 6 (app, browser host, command line, lab server) -> ~/lab/bin/$label"+} | tee "$log"+start=$(date +%s)+cargo build --profile "$profile" -j 6 -p mdm-app -p mdm-nmhost -p mdm-cli -p mdm-labserver 2>&1 | tee -a "$log"+status=${PIPESTATUS[0]}+if [ "$status" = 0 ]; then+ out=target/$profile; [ "$profile" = dev ] && out=target/debug+ mkdir -p "$HOME/lab/bin/$label"+ cp "$out"/misterdownloadmanager{,-nmhost,-cli} "$out"/labserver "$HOME/lab/bin/$label/"+fi+echo "== exit $status after $(( $(date +%s) - start )) s" | tee -a "$log"+exit "$status"diff --git a/tools/lab/linux-vm/chrome-popup.mjs b/tools/lab/linux-vm/chrome-popup.mjsnew file mode 100644index 00000000..ab5d0720--- /dev/null+++ b/tools/lab/linux-vm/chrome-popup.mjs@@ -0,0 +1,57 @@+// The extension's popup in Google Chrome (headless, the DevTools pipe): an expression evaluated in+// it, printed. For checks of what the popup shows there.+// node chrome-popup.mjs <unpacked extension folder> "<expression>"+import fs from "node:fs";+import path from "node:path";+import { spawn } from "node:child_process";++const ext = path.resolve(process.argv[2]);+const expression = process.argv[3];+const NUL = String.fromCharCode(0);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+const profile = path.join(process.env.HOME, "lab/chrome-popup");+fs.rmSync(profile, { recursive: true, force: true });+fs.mkdirSync(profile, { recursive: true });+const proc = spawn(+ "/usr/bin/google-chrome",+ ["--headless", "--remote-debugging-pipe", "--enable-unsafe-extension-debugging", "--password-store=basic", `--user-data-dir=${profile}`, "--no-first-run", "about:blank"],+ { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] },+);+let next = 1;+const waiting = new Map();+let buf = "";+proc.stdio[4].on("data", (d) => {+ buf += d.toString("utf8");+ let i;+ while ((i = buf.indexOf(NUL)) >= 0) {+ const m = JSON.parse(buf.slice(0, i));+ buf = buf.slice(i + 1);+ const w = m.id && waiting.get(m.id);+ if (!w) continue;+ waiting.delete(m.id);+ if (m.error) w.reject(new Error(m.error.message));+ else w.resolve(m.result);+ }+});+const send = (method, params = {}, sessionId) => {+ const id = next++;+ proc.stdio[3].write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + NUL);+ return new Promise((resolve, reject) => {+ waiting.set(id, { resolve, reject });+ setTimeout(() => waiting.has(id) && (waiting.delete(id), reject(new Error(`${method}: no answer in 60 s`))), 60000);+ });+};+try {+ const { product } = await send("Browser.getVersion");+ const { id } = await send("Extensions.loadUnpacked", { path: ext });+ const { targetId } = await send("Target.createTarget", { url: `chrome-extension://${id}/popup.html` });+ const { sessionId } = await send("Target.attachToTarget", { targetId, flatten: true });+ await sleep(3000);+ const r = await send("Runtime.evaluate", { expression, awaitPromise: true, returnByValue: true }, sessionId);+ console.log(`${product}, extension ${id}: ${JSON.stringify(r.result.value)}`);+} catch (e) {+ console.log(`ERROR ${e.message}`);+} finally {+ proc.kill();+}+process.exit(0);diff --git a/tools/lab/linux-vm/env.sh b/tools/lab/linux-vm/env.shnew file mode 100644index 00000000..d193426a--- /dev/null+++ b/tools/lab/linux-vm/env.sh@@ -0,0 +1,5 @@+# The desktop session's display, bus and runtime folder, for scripts started from outside it+# (VBoxManage guestcontrol): GUI programs open on the lab's screen, gsettings and D-Bus reach it.+export DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/$(id -u) DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus+export XAUTHORITY=/run/user/$(id -u)/gdm/Xauthority+[ -f ~/.cargo/env ] && . ~/.cargo/envdiff --git a/tools/lab/linux-vm/handoff-minimized.sh b/tools/lab/linux-vm/handoff-minimized.shnew file mode 100644index 00000000..67b082e8--- /dev/null+++ b/tools/lab/linux-vm/handoff-minimized.sh@@ -0,0 +1,51 @@+#!/bin/bash+# #162/#173 on X11: with MDM's window minimized (Minimize to the notification area off), a magnet+# from a second launch and a download through the browser's host; how long until each one's+# window opens. Torrents' network is off (no DHT, UPnP, local discovery or incoming connections):+# the magnet only opens its window, nothing reaches the internet.+# handoff-minimized.sh <label> (a build in ~/lab/bin/<label>)+. ~/lab/env.sh+bin=$HOME/lab/bin/$1+app=$bin/misterdownloadmanager+data=$HOME/.local/share/misterdownloadmanager+pkill -x misterdownloadm; sleep 2+python3 - "$data/downloads.json" <<'PY'+import json, sys+p = sys.argv[1]+d = json.load(open(p))+s = d.setdefault("settings", {})+s.update(minimize_to_tray=False, torrent_dht=False, torrent_upnp=False, torrent_lsd=False, torrent_incoming=False,+ language="en", language_asked=True, extension_never_ask=True)+json.dump(d, open(p, "w"))+PY+cd ~; setsid -f "$app" >/dev/null 2>&1 </dev/null+# This instance's own main window (by its process), not one left from an earlier run.+main=""+for _ in $(seq 60); do+ pid=$(pgrep -f "^$app$" | head -1)+ [ -n "$pid" ] && main=$(wmctrl -lp | awk -v p="$pid" '$3 == p && /Mister Download Manager 0\./ {print $1}' | head -1)+ [ -n "$main" ] && break; sleep 1+done+[ -z "$main" ] && { echo "MDM's main window didn't appear"; exit 1; }+sleep 5+state() { xprop -id "$main" WM_STATE 2>/dev/null | grep -o 'Normal\|Iconic\|Withdrawn'; }+minimize() { xdotool windowminimize "$(printf %d "$main")"; sleep 2; }+# Wait for a window whose title contains $1: the seconds it took, or "not in 30 s".+opened() {+ local t0; t0=$(date +%s.%N)+ for _ in $(seq 150); do+ if wmctrl -l | grep -q -F -- "$1"; then echo "$(echo "$(date +%s.%N) - $t0" | bc | cut -c1-4) s"; return; fi+ sleep 0.2+ done+ echo "not in 30 s"+}+echo "== $1 (pid $pid), main window $main, load $(cut -d" " -f1-3 /proc/loadavg)"+minimize; echo "main window: $(state)"+"$app" 'magnet:?xt=urn:btih:0123456789abcdef0123456789abcdef01234567&dn=lab-minimized' &+echo "magnet (second launch) -> Add torrent: $(opened 'Add torrent') main window then: $(state)"+wmctrl -c 'Add torrent'; sleep 2+minimize; echo "main window: $(state)"+python3 ~/lab/nmping.py "$bin/misterdownloadmanager-nmhost" '{"url":"http://127.0.0.1:8097/gen/1M/minimized.zip","referrer":"http://127.0.0.1:8097/page","size":1048576}' | tail -1 &+echo "download (browser host) -> Download File Info: $(opened 'Download File Info') main window then: $(state)"+wmctrl -c 'Download File Info'; sleep 1+wmctrl -l | cut -c1-90 | grep -v -E 'Desktop Icons|mdm@|MDM build'diff --git a/tools/lab/linux-vm/measure.sh b/tools/lab/linux-vm/measure.shnew file mode 100644index 00000000..cdfcadc2--- /dev/null+++ b/tools/lab/linux-vm/measure.sh@@ -0,0 +1,26 @@+#!/bin/bash+# Start-up timings of a build: measure.sh <program> <label> [runs]+# fresh: an empty profile (the language picker opens, every script's font loads);+# warm: the profile the fresh run left (language chosen: no picker... unless never chosen).+. ~/lab/env.sh+prog=$1; label=$2; runs=${3:-5}+d=~/.local/share/misterdownloadmanager+# The app and its crash monitor (a process name is cut to 15 characters).+stop() { pkill -x misterdownloadm; sleep 2; }+ms() { date -d "$1" +%s%3N; }+one() {+ stop+ [ "$1" = fresh ] && rm -rf "$d"+ rm -f $d/logs/* 2>/dev/null+ cd ~; setsid "$prog" >/dev/null 2>&1 </dev/null &+ for _ in $(seq 60); do grep -qs 'first frame drawn' $d/logs/*.log && break; sleep 0.5; done+ f=$(cat $d/logs/*.log)+ gl=$(echo "$f" | grep -m1 'drawing with OpenGL,' | cut -c1-27)+ op=$(echo "$f" | grep -m1 'window opened' | cut -c1-27)+ first=$(echo "$f" | grep -m1 'first frame drawn' | sed -E 's/.*drawn, ([0-9]+) ms.*/\1/')+ freeze=$(echo "$f" | grep -c 'stopped responding')+ echo "$label $1: first frame ${first} ms, GL ready -> first window $(( $(ms "$op") - $(ms "$gl") )) ms, freezes $freeze"+}+for i in $(seq $runs); do one fresh; done+for i in $(seq $runs); do one warm; done+stopdiff --git a/tools/lab/linux-vm/pixdiff.py b/tools/lab/linux-vm/pixdiff.pynew file mode 100644index 00000000..849db287--- /dev/null+++ b/tools/lab/linux-vm/pixdiff.py@@ -0,0 +1,39 @@+"""Compare two screenshot folders pixel by pixel (the same file names in each): for every pair,+whether it is identical, else how many pixels differ, where (their bounding box) and a diff image+(the after shot dimmed, differing pixels in red) in <out>.++ python pixdiff.py <before folder> <after folder> <out folder>+"""+import os+import sys++from PIL import Image, ImageChops+++def main(before, after, out):+ os.makedirs(out, exist_ok=True)+ names = sorted(set(os.listdir(before)) & set(os.listdir(after)))+ for name in names:+ if not name.endswith(".png"):+ continue+ a = Image.open(os.path.join(before, name)).convert("RGB")+ b = Image.open(os.path.join(after, name)).convert("RGB")+ if a.size != b.size:+ print(f"{name}: sizes differ, {a.size} before, {b.size} after")+ continue+ diff = ImageChops.difference(a, b)+ box = diff.getbbox()+ if not box:+ print(f"{name}: identical ({a.size[0]}x{a.size[1]})")+ continue+ mask = diff.convert("L").point(lambda v: 255 if v else 0)+ count = sum(1 for v in mask.getdata() if v)+ total = a.size[0] * a.size[1]+ shown = Image.blend(Image.new("RGB", b.size, "white"), b, 0.35)+ shown.paste((255, 0, 0), mask=mask)+ shown.save(os.path.join(out, name), optimize=True)+ print(f"{name}: {count} of {total} pixels differ ({100 * count / total:.2f} %), in {box}")+++if __name__ == "__main__":+ main(*sys.argv[1:4])diff --git a/tools/lab/linux-vm/proxy-optin.mjs b/tools/lab/linux-vm/proxy-optin.mjsnew file mode 100644index 00000000..c493669b--- /dev/null+++ b/tools/lab/linux-vm/proxy-optin.mjs@@ -0,0 +1,173 @@+// #42/#191 on Linux: the popup's proxy switch in the Snap Firefox (headless, over WebDriver BiDi).+// Off at first; turning it on brings Firefox's permission prompt, answered through the browser's own+// window (Allow, then Don't allow); the switch and the "proxy" permission are read back after each+// step, and after turning it off again.+// node proxy-optin.mjs <xpi>+import fs from "node:fs";+import path from "node:path";+import { spawn, execFileSync } from "node:child_process";++const xpi = path.resolve(process.argv[2]);+const ID = "[email protected]";+const UUID = "5d0c3b8e-7a51-4c1e-9f0a-38e2c4a1d7b6";+const NL = String.fromCharCode(10);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function until(what, ms, f) {+ const end = Date.now() + ms;+ for (;;) {+ const v = await f().catch(() => null);+ if (v) return v;+ if (Date.now() > end) throw new Error(`timed out: ${what}`);+ await sleep(250);+ }+}+class Bidi {+ constructor(ws) {+ this.ws = ws;+ this.next = 1;+ this.waiting = new Map();+ ws.addEventListener("message", (e) => {+ const m = JSON.parse(e.data);+ const w = m.id && this.waiting.get(m.id);+ if (!w) return;+ this.waiting.delete(m.id);+ if (m.type === "error") w.reject(new Error(`${w.method}: ${m.error} ${m.message}`));+ else w.resolve(m.result);+ });+ }+ send(method, params = {}) {+ const id = this.next++;+ this.ws.send(JSON.stringify({ id, method, params }));+ return new Promise((resolve, reject) => this.waiting.set(id, { resolve, reject, method }));+ }+}++const profile = path.join(process.env.HOME, "snap/firefox/common/mdm-proxy-optin");+// A Firefox left from an earlier run would keep the profile locked.+try {+ execFileSync("pkill", ["-f", "--", `-profile ${profile}`]);+ execFileSync("sleep", ["2"]);+} catch {}+fs.rmSync(profile, { recursive: true, force: true });+fs.mkdirSync(profile, { recursive: true });+const pref = (k, v) => `user_pref(${JSON.stringify(k)}, ${JSON.stringify(v)});`;+fs.writeFileSync(+ path.join(profile, "user.js"),+ [+ pref("browser.shell.checkDefaultBrowser", false),+ pref("datareporting.policy.dataSubmissionEnabled", false),+ pref("browser.aboutwelcome.enabled", false),+ pref("extensions.webextensions.uuids", JSON.stringify({ [ID]: UUID })),+ ].join(NL),+);+const port = 9300 + Math.floor(Math.random() * 500);+// With a window on the lab's desktop: the switch takes a real click (xdotool), which nothing+// else gives an extension's page (permissions.request wants a user input handler).+const ff = spawn("/snap/bin/firefox", ["-no-remote", "-profile", profile, "--remote-debugging-port", String(port), "--width=1100", "--height=760"], {+ env: { ...process.env, MOZ_REMOTE_ALLOW_SYSTEM_ACCESS: "1" },+ stdio: "ignore",+});+const say = (s) => console.log(s);+try {+ const ws = await until("Firefox's remote protocol", 60000, () =>+ new Promise((resolve) => {+ const s = new WebSocket(`ws://127.0.0.1:${port}/session`);+ s.addEventListener("open", () => resolve(s));+ s.addEventListener("error", () => resolve(null));+ }),+ );+ const bidi = new Bidi(ws);+ const { capabilities } = await bidi.send("session.new", { capabilities: {} });+ say(`Firefox ${capabilities.browserVersion} (Snap, a window on the desktop), add-on ${xpi}`);+ await bidi.send("webExtension.install", { extensionData: { type: "archivePath", path: xpi } });+ const chrome = async (expression) => {+ const { contexts: w } = await bidi.send("browsingContext.getTree", { "moz:scope": "chrome" });+ const r = await bidi.send("script.evaluate", { expression, target: { context: w[0].context }, awaitPromise: true, "moz:scope": "chrome" });+ if (r.type === "exception") throw new Error(`chrome: ${r.exceptionDetails.text}`);+ return r.result.value;+ };+ const url = `moz-extension://${UUID}/popup.html`;+ await chrome(`gBrowser.selectedTab = gBrowser.addTab(${JSON.stringify(url)}, { triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal() }) && "opened"`);+ const c = await until("the popup's tab", 10000, async () => ((await bidi.send("browsingContext.getTree", {})).contexts.find((x) => x.url === url) || {}).context);+ const ev = async (expression) => {+ const r = await bidi.send("script.evaluate", { expression: `(async () => JSON.stringify(await (${expression})))()`, target: { context: c }, awaitPromise: true, userActivation: true });+ if (r.type === "exception") throw new Error(`evaluate: ${r.exceptionDetails.text}`);+ return r.result.value === undefined ? undefined : JSON.parse(r.result.value);+ };+ const state = async () => {+ const s = await ev(`(async () => ({ shown: !document.getElementById("proxy-row").hidden, on: document.getElementById("proxy").checked,+ label: document.getElementById("proxy-row").textContent.trim(), permission: await browser.permissions.contains({ permissions: ["proxy"] }) }))()`);+ return `switch ${s.shown ? "shown" : "HIDDEN"}, ${s.on ? "on" : "off"} ("${s.label}"); the proxy permission: ${s.permission ? "granted" : "not granted"}`;+ };+ await until("the popup", 10000, () => ev("document.readyState === 'complete'"));+ await sleep(1500);+ say(`at first: ${await state()}`);+ // Turn it on (a click: a user's gesture), then answer Firefox's prompt with `button`+ // ("button": Allow, "secondaryButton": Don't allow); what the prompt said.+ // A real click on the switch: its place on the screen (the window's, the tab's, the switch's).+ const toggle = async () => {+ const b = await ev(`(() => { const r = document.getElementById("proxy").getBoundingClientRect(); return { x: r.left + r.width / 2, y: r.top + r.height / 2 }; })()`);+ const at = JSON.parse(await chrome(`(() => {+ const tab = gBrowser.tabs.find((x) => x.linkedBrowser.currentURI.spec.startsWith(${JSON.stringify(url)}));+ if (tab) gBrowser.selectedTab = tab;+ const r = gBrowser.selectedBrowser.getBoundingClientRect();+ return JSON.stringify({ x: window.mozInnerScreenX + r.left, y: window.mozInnerScreenY + r.top }); })()`));+ const x = Math.round(at.x + b.x), y = Math.round(at.y + b.y);+ await sleep(800);+ // The first click into a window only focuses it: one on the page's empty top left first.+ execFileSync("xdotool", ["mousemove", String(Math.round(at.x + 4)), String(Math.round(at.y + 4)), "click", "1"]);+ await sleep(600);+ execFileSync("xdotool", ["mousemove", String(x), String(y)]);+ await sleep(400);+ execFileSync("xdotool", ["click", "1"]);+ return `clicked at ${x},${y}`;+ };+ const answer = (which) =>+ chrome(`(async () => {+ let n = null;+ for (let i = 0; i < 80 && !n; i++) {+ n = [...document.querySelectorAll("popupnotification")].find((x) => !x.hidden && /permission/i.test(x.id));+ if (!n) await new Promise((r) => setTimeout(r, 100));+ }+ if (!n) return "no prompt";+ const text = (n.getAttribute("label") || "") + " " + [...n.querySelectorAll("li, description")].map((x) => x.textContent).join(" / ");+ n.${which}.click();+ return n.id + ": " + text.replace(/\\s+/g, " ").trim().slice(0, 200);+ })()`);+ if (process.env.PROBE) {+ const asked = ev(`browser.permissions.request({ permissions: ["proxy"] }).then((r) => "resolved " + r, (e) => "rejected " + e)`);+ await sleep(3000);+ say(`notifications: ${await chrome(`JSON.stringify((PopupNotifications._currentNotifications || []).map((n) => n.id)) + " / panel: " + [...document.querySelectorAll("popupnotification")].map((x) => x.id + (x.hidden ? "(hidden)" : "")).join(", ")`)}`);+ say(`request: ${await Promise.race([asked, sleep(5000).then(() => "pending after 8 s")])}`);+ }+ // Each step clicks again when its click was lost (the first one into the page sometimes is).+ const on = async (which) => {+ for (let i = 1; i <= 3; i++) {+ await toggle();+ const prompt = await answer(which);+ if (prompt !== "no prompt") return `${prompt} (click ${i})`;+ }+ return "no prompt after 3 clicks";+ };+ const off = async () => {+ for (let i = 1; i <= 3; i++) {+ await toggle();+ await sleep(1500);+ if (!(await ev(`document.getElementById("proxy").checked`))) return `click ${i}`;+ }+ return "still on after 3 clicks";+ };+ say(`on, the prompt answered Allow: ${await on("button")}`);+ await sleep(1500);+ say(`after Allow: ${await state()}`);+ say(`off: ${await off()}`);+ say(`after turning it off: ${await state()}`);+ say(`on again, the prompt answered Don't allow: ${await on("secondaryButton")}`);+ await sleep(1500);+ say(`after Don't allow: ${await state()}`);+} catch (e) {+ say(`ERROR ${e.message}`);+} finally {+ ff.kill();+}+process.exit(0);diff --git a/tools/lab/linux-vm/queue-minimized.sh b/tools/lab/linux-vm/queue-minimized.shnew file mode 100644index 00000000..41b38bfc--- /dev/null+++ b/tools/lab/linux-vm/queue-minimized.sh@@ -0,0 +1,60 @@+#!/bin/bash+# #176 on X11: a minimized MDM keeps working. Minimize to the notification area off, the main+# queue set to one file at a time and to start 75 s from now; three lab files (throttled, a few+# seconds each) added to it, then the window minimized. Prints when the queue started, each+# file's completion (order, time) and each "Download complete" window, and the main window's state.+# queue-minimized.sh <label> (a build in ~/lab/bin/<label>; the lab server on :8097)+. ~/lab/env.sh+app=$HOME/lab/bin/$1/misterdownloadmanager+data=$HOME/.local/share/misterdownloadmanager+dir=$HOME/Downloads/Compressed+tag=q$(date +%H%M%S)+pkill -x misterdownloadm; sleep 2+start=$(date -d '+75 seconds' '+%H %M %S')+python3 - "$data/downloads.json" $start <<'PY'+import json, sys+p, h, m, s = sys.argv[1], *map(int, sys.argv[2:5])+d = json.load(open(p))+st = d.setdefault("settings", {})+st.update(minimize_to_tray=False, language="en", language_asked=True, extension_never_ask=True,+ always_dark=False, dark_mode_support=False)+for q in d.get("queues", []):+ if not q.get("sync"):+ q["files_at_once"] = 1+ q["schedule"].update(start_at=[h, m, s], days=[True] * 7, once=None, start_on_startup=False)+json.dump(d, open(p, "w"))+PY+echo "== $1: the main queue starts at $(echo $start | tr ' ' ':'), one file at a time"+cd ~; setsid -f "$app" >/dev/null 2>&1 </dev/null+main=""+for _ in $(seq 60); do+ pid=$(pgrep -f "^$app$" | head -1)+ [ -n "$pid" ] && main=$(wmctrl -lp | awk -v p="$pid" '$3 == p && /Mister Download Manager 0\./ {print $1}' | head -1)+ [ -n "$main" ] && break; sleep 1+done+sleep 4+for n in 1 2 3; do+ "$app" /d "http://127.0.0.1:8097/gen/2M/$tag-$n.zip?rate=400K" /a /n+ sleep 1+done+sleep 3+xdotool windowminimize "$(printf %d "$main")"; sleep 2+state() { xprop -id "$main" WM_STATE 2>/dev/null | grep -o 'Normal\|Iconic'; }+echo "$(date +%T) files added, main window: $(state)"+seen=""; done_files=""+end=$(( $(date +%s) + 180 ))+while [ "$(date +%s)" -lt $end ]; do+ for n in 1 2 3; do+ f="$dir/$tag-$n.zip"+ if [ -f "$f" ] && [ "$(stat -c %s "$f")" = 2097152 ] && ! echo "$done_files" | grep -q " $n "; then+ done_files="$done_files $n "; echo "$(date +%T) file $n complete; main window: $(state)"+ fi+ done+ for w in $(wmctrl -lp | awk -v p="$pid" '$3 == p && /Download complete/ {print $1}'); do+ echo "$seen" | grep -q "$w" && continue+ seen="$seen $w"; echo "$(date +%T) a Download complete window opened ($w); main window: $(state)"+ done+ [ "$(echo $done_files | wc -w)" = 3 ] && [ "$(echo $seen | wc -w)" -ge 3 ] && break+ sleep 1+done+echo "$(date +%T) finished: files$done_files; Download complete windows: $(echo $seen | wc -w); main window: $(state)"diff --git a/tools/lab/linux-vm/restart-lab.sh b/tools/lab/linux-vm/restart-lab.shnew file mode 100644index 00000000..6cf10cb6--- /dev/null+++ b/tools/lab/linux-vm/restart-lab.sh@@ -0,0 +1,8 @@+#!/bin/bash+# The lab server and MDM from one build (~/lab/bin/<label>), restarted.+. ~/lab/env.sh+pkill -x labserver; pkill -x misterdownloadm; sleep 2+setsid -f ~/lab/bin/$1/labserver --bind 127.0.0.1:8097 --log-file ~/lab/labserver.jsonl >/tmp/labserver.out 2>&1 </dev/null+cd ~; setsid -f ~/lab/bin/$1/misterdownloadmanager >/dev/null 2>&1 </dev/null+sleep 15+curl -s -o /dev/null -w "lab %{http_code} " "http://127.0.0.1:8097/hls2/playlist?id=lab"; wmctrl -l | grep -E "Mister Download Manager 0" | cut -c1-80diff --git a/tools/lab/linux-vm/run-streams.sh b/tools/lab/linux-vm/run-streams.shnew file mode 100644index 00000000..11b1df35--- /dev/null+++ b/tools/lab/linux-vm/run-streams.sh@@ -0,0 +1,6 @@+#!/bin/bash+# streams harness with a quiet browser side: run-streams.sh <firefox|chrome> <extension> [kinds]+. ~/lab/env.sh+pkill -f web-ext; pkill -f "snap/firefox/.*/firefox"; pkill -f "/opt/google/chrome"; sleep 2+cd ~/lab+if [ "$1" = chrome ]; then timeout 1200 node streams-chrome.mjs "$2" http://127.0.0.1:8097 "$3" 2>&1 | tail -20; else timeout 1500 node streams.mjs "$2" http://127.0.0.1:8097 "$3" 2>&1 | tail -20; fidiff --git a/tools/lab/linux-vm/setup.sh b/tools/lab/linux-vm/setup.shnew file mode 100644index 00000000..41a4f354--- /dev/null+++ b/tools/lab/linux-vm/setup.sh@@ -0,0 +1,152 @@+#!/usr/bin/env bash+# The Linux test machine: an Ubuntu 24.04 desktop (GNOME on Xorg) that builds and runs MDM, with+# the browsers for the extension and AT-SPI automation for the windows. Run it inside the machine+# as its desktop user (it asks sudo for the system parts); running it again only adds what's+# missing and updates the checkout.+#+# bash setup.sh [--no-build] [--branch <name>]+#+# From a Windows host, vm.ps1 next to this file copies it in and runs it.+set -euo pipefail++build=1+branch=main+while [ $# -gt 0 ]; do+ case "$1" in+ --no-build) build=0 ;;+ --branch) branch="$2"; shift ;;+ *) echo "unknown option $1" >&2; exit 2 ;;+ esac+ shift+done++repo_url=https://github.com/anefzaoui/misterdownloadmanager.git+checkout="$HOME/mdm"+# sudo_ takes the password from MDM_SUDO_PASSWORD when set (through stdin, so never pipe into it).+sudo_() { if [ -n "${MDM_SUDO_PASSWORD:-}" ]; then echo "$MDM_SUDO_PASSWORD" | sudo -S -p '' "$@"; else sudo "$@"; fi; }+export DEBIAN_FRONTEND=noninteractive++# --- The desktop: GNOME on Xorg (VirtualBox's display stays on the splash under Wayland), signed+# in automatically, never locked or blanked, so screenshots and automation always see it.+tmp=$(mktemp)+cat >"$tmp" <<EOF+[daemon]+WaylandEnable=false+AutomaticLoginEnable=true+AutomaticLogin=$USER++[security]++[xdmcp]++[chooser]++[debug]+EOF+sudo_ install -m 644 "$tmp" /etc/gdm3/custom.conf+rm -f "$tmp"+mkdir -p "$HOME/.config"+echo yes > "$HOME/.config/gnome-initial-setup-done"+if [ -S "/run/user/$(id -u)/bus" ]; then+ export DBUS_SESSION_BUS_ADDRESS="unix:path=/run/user/$(id -u)/bus"+ gsettings set org.gnome.desktop.session idle-delay 0+ gsettings set org.gnome.desktop.screensaver lock-enabled false+ gsettings set org.gnome.desktop.screensaver idle-activation-enabled false+ # AT-SPI for every toolkit: agent-desktop and Orca read the windows through it.+ gsettings set org.gnome.desktop.interface toolkit-accessibility true+fi+# A login keyring with an empty password (auto-login unlocks nothing): gnome-keyring keeps it+# unencrypted and unlocked, so a browser asking the Secret Service (Chrome's "Safe Storage")+# never stops a test with "Choose a password for your new keyring". Test browsers also run with+# --password-store=basic. MDM itself doesn't use the Secret Service.+keyrings="$HOME/.local/share/keyrings"+mkdir -p "$keyrings" && chmod 700 "$keyrings"+if [ ! -f "$keyrings/login.keyring" ]; then+ printf '[keyring]\ndisplay-name=Login\nctime=0\nmtime=0\nlock-on-idle=false\nlock-after=false\n' > "$keyrings/login.keyring"+ chmod 600 "$keyrings/login.keyring"+ echo login > "$keyrings/default"+ systemctl --user restart gnome-keyring-daemon.service 2>/dev/null || true+fi++# --- Packages: the build's libraries (the same as ci.yml and release.yml), the packaging tools,+# the helpers MDM drives (ffmpeg, 7-Zip, gallery-dl), the AppImage runtime (FUSE 2), and the+# automation and screen-reader tools.+sudo_ apt-get update -q+sudo_ apt-get install -y -q \+ build-essential pkg-config git curl ca-certificates python3 python3-pip python3-pil \+ libgtk-3-dev libxkbcommon-dev libwayland-dev libgl1-mesa-dev \+ libxcb-render0-dev libxcb-shape0-dev libxcb-xfixes0-dev \+ rpm zsync libfuse2t64 \+ ffmpeg p7zip-full gallery-dl \+ at-spi2-core python3-pyatspi orca xdotool wmctrl x11-utils mesa-utils imagemagick \+ gnome-shell-extension-appindicator++# yt-dlp: the distribution's copy falls behind the sites, so the project's own build.+if ! command -v yt-dlp >/dev/null || [ "$(readlink -f "$(command -v yt-dlp)")" != /usr/local/bin/yt-dlp ]; then+ sudo_ curl -fsSL -o /usr/local/bin/yt-dlp https://github.com/yt-dlp/yt-dlp/releases/latest/download/yt-dlp+ sudo_ chmod 755 /usr/local/bin/yt-dlp+fi++# --- Browsers: Firefox as Ubuntu ships it (Snap), Chromium (Snap) and Google Chrome (.deb), each+# with its own native messaging folder.+# The Snap store's downloads sometimes stall ("download too slow"): a few tries each.+snap_install() {+ snap list "$1" >/dev/null 2>&1 && return 0+ for _ in 1 2 3; do sudo_ snap install "$1" && return 0; sleep 10; done+ echo "warning: snap $1 not installed; run setup again later" >&2+}+snap_install firefox+snap_install chromium+if ! command -v google-chrome >/dev/null; then+ tmp=$(mktemp -d)+ curl -fsSL -o "$tmp/chrome.deb" https://dl.google.com/linux/direct/google-chrome-stable_current_amd64.deb+ sudo_ apt-get install -y -q "$tmp/chrome.deb"+ rm -rf "$tmp"+fi++# --- Node LTS and agent-desktop (UI automation through the accessibility tree).+if ! command -v node >/dev/null; then+ curl -fsSL -o /tmp/nodesource.sh https://deb.nodesource.com/setup_lts.x+ sudo_ bash /tmp/nodesource.sh+ rm -f /tmp/nodesource.sh+ sudo_ apt-get install -y -q nodejs+fi+command -v agent-desktop >/dev/null || sudo_ npm install -g agent-desktop++# --- Rust (stable; rust-toolchain.toml picks the components).+if [ ! -x "$HOME/.cargo/bin/rustup" ]; then+ curl -fsSL https://sh.rustup.rs | sh -s -- -y --profile minimal --default-toolchain stable+fi+# shellcheck disable=SC1091+. "$HOME/.cargo/env"+rustup update stable+# The lab's own profile for functional checks (build.sh): release without the shipping build's+# fat LTO, incremental, so switching branches recompiles only what changed. This machine only.+if ! grep -q 'profile.vmtest' "$HOME/.cargo/config.toml" 2>/dev/null; then+ cat >> "$HOME/.cargo/config.toml" <<'EOF'++[profile.vmtest]+inherits = "release"+lto = false+codegen-units = 256+incremental = true+debug = false+opt-level = 2++[profile.vmtest.package."*"]+opt-level = 3+EOF+fi++# --- The checkout and the build (its target folder stays in the machine).+if [ ! -d "$checkout/.git" ]; then+ git clone "$repo_url" "$checkout"+fi+git -C "$checkout" fetch -q origin+git -C "$checkout" checkout -q "$branch"+git -C "$checkout" pull -q --ff-only || true+if [ "$build" = 1 ]; then+ bash "$(dirname "$0")/build.sh" "$branch"+fi++echo "lab ready: $(lsb_release -ds), $(rustc --version), node $(node --version), $(agent-desktop --version 2>/dev/null || echo 'agent-desktop ?')"diff --git a/tools/lab/linux-vm/shot-host.sh b/tools/lab/linux-vm/shot-host.shnew file mode 100644index 00000000..0e0c2e1e--- /dev/null+++ b/tools/lab/linux-vm/shot-host.sh@@ -0,0 +1,21 @@+#!/bin/bash+# Host side (Git Bash on Windows): one MDM window in the lab VM, cropped from VirtualBox's own+# screenshot (capturing an OpenGL window from inside the guest gives an empty image).+# shot-host.sh <vm> <label> <main|fileinfo|show name> <lang> <light|dark> <out.png>+# MDM_STATE (a saved downloads.json in the guest) and MDM_SEEN (extension-seen lines) pass through+# to shots.sh. MDM_VM_USER / MDM_VM_PASSWORD as for vm.ps1.+V="${VBOXMANAGE:-/c/Program Files/Oracle/VirtualBox/VBoxManage.exe}"+user=${MDM_VM_USER:-mdm}; pass=${MDM_VM_PASSWORD:-mdm123456789}+vm=$1; out=$6+geo=$(MSYS_NO_PATHCONV=1 "$V" guestcontrol "$vm" run --exe /bin/bash --username "$user" --password "$pass" --timeout 150000 --wait-stdout -- \+ -c "MDM_STATE=${MDM_STATE:-} MDM_SEEN='${MDM_SEEN:-}' bash /home/$user/lab/shots.sh $2 $3 $4 $5" 2>/dev/null | tail -1)+full="${out%.png}.full.png"+"$V" controlvm "$vm" screenshotpng "$(cygpath -w "$full")"+python - "$full" "$out" $geo <<'PY'+import sys+from PIL import Image+full, out, x, y, w, h = sys.argv[1], sys.argv[2], *map(int, sys.argv[3:7])+Image.open(full).crop((x, y, x + w, y + h)).save(out, optimize=True)+print(out, x, y, w, h)+PY+rm -f -- "$full"diff --git a/tools/lab/linux-vm/shots.sh b/tools/lab/linux-vm/shots.shnew file mode 100644index 00000000..056a922b--- /dev/null+++ b/tools/lab/linux-vm/shots.sh@@ -0,0 +1,53 @@+#!/bin/bash+# One MDM window ready for a screenshot: MDM restarted with the language and mode set in its+# settings, the window opened with `/show <name>` and raised; prints its frame on the screen as+# "X Y W H" for the host to crop VirtualBox's screenshot to (vm.ps1 shot; capturing an OpenGL+# window from inside the guest gives an empty image).+# shots.sh <label> <main|fileinfo|show name> <lang> <light|dark> e.g. shots.sh base extension de dark+. ~/lab/env.sh+label=$1; show=$2; lang=$3; mode=$4+app=$HOME/lab/bin/$label/misterdownloadmanager+data=$HOME/.local/share/misterdownloadmanager+pkill -x misterdownloadm; sleep 2+# MDM_STATE: a saved list and settings put back first, so builds compared see the same list.+[ -n "${MDM_STATE:-}" ] && cp "$MDM_STATE" "$data/downloads.json"+# MDM_SEEN: the browsers whose extension reached MDM, "Name<TAB>version" lines with "\n"+# between (printf's %b turns them into real tabs and newlines).+[ -n "${MDM_SEEN:-}" ] && printf '%b\n' "$MDM_SEEN" > "$data/extension-seen"+python3 - "$data/downloads.json" "$lang" "$mode" <<'PY'+import json, sys+p, lang, mode = sys.argv[1:4]+d = json.load(open(p))+s = d.setdefault("settings", {})+s.update(language=lang, language_asked=True, always_dark=(mode == "dark"), dark_mode_support=(mode == "dark"))+json.dump(d, open(p, "w"))+PY+cd ~; setsid -f "$app" >/dev/null 2>&1 </dev/null+pid=""+for _ in $(seq 60); do+ pid=$(pgrep -f "^$app$" | head -1)+ [ -n "$pid" ] && wmctrl -lp | awk -v p="$pid" '$3 == p' | grep -q . && break+ sleep 1+done+main=$(wmctrl -lp | awk -v p="$pid" '$3 == p {print $1}' | head -1)+sleep 4+# `main`: the main window itself; `fileinfo`: Download File Info for a lab file (`/d`); any other+# name: `/show <name>`.+case "$show" in+ main) ;;+ fileinfo) timeout 20 "$app" /d "http://127.0.0.1:8097/gen/1M/shot.zip" ;;+ *) timeout 20 "$app" /show "$show" ;;+esac+win=$main+for _ in $(seq 40); do+ [ "$show" = main ] && break+ win=$(wmctrl -lp | awk -v p="$pid" -v m="$main" '$3 == p && $1 != m {print $1}' | tail -1)+ [ -n "$win" ] && break+ sleep 0.5+done+sleep 2+timeout 5 wmctrl -i -a "$win"; sleep 1+# The client area, widened by the window manager's frame (title bar and borders).+read -r l r top b < <(timeout 5 xprop -id "$win" _NET_FRAME_EXTENTS | grep -o '[0-9]\+' | tr '\n' ' ')+timeout 5 xwininfo -id "$win" | awk -v l="${l:-0}" -v r="${r:-0}" -v t="${top:-0}" -v b="${b:-0}" '/Absolute upper-left X/ {x=$4} /Absolute upper-left Y/ {y=$4} /Width:/ {w=$2} /Height:/ {h=$2}+ END {print x - l, y - t, w + l + r, h + t + b}'diff --git a/tools/lab/linux-vm/streams-chrome.mjs b/tools/lab/linux-vm/streams-chrome.mjsnew file mode 100644index 00000000..27d61b11--- /dev/null+++ b/tools/lab/linux-vm/streams-chrome.mjs@@ -0,0 +1,197 @@+// #155/#167 on Linux with Google Chrome (.deb; Ubuntu's Chromium is a Snap, which can't reach MDM):+// headless over the DevTools pipe (as tools/extension/e2e.mjs drives it), the unpacked extension+// loaded, the lab's HLS and DASH player pages; the button over the player and the popup's media+// list (Chrome's own right-click menu can't be driven). Same checks as streams.mjs.+// node streams-chrome.mjs <unpacked extension folder> [lab] [kinds] (kinds: as streams.mjs)+import fs from "node:fs";+import path from "node:path";+import { spawn, execFileSync } from "node:child_process";++const ext = path.resolve(process.argv[2]);+const LAB = process.argv[3] || "http://127.0.0.1:8097";+const KINDS = (process.argv[4] || "hls:/hls/master.m3u8,dash:/dash/manifest.mpd").split(",").map((k) => k.split(":"));+const NL = String.fromCharCode(10);+const NUL = String.fromCharCode(0);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function until(what, ms, f) {+ const end = Date.now() + ms;+ for (;;) {+ const v = await f().catch(() => null);+ if (v) return v;+ if (Date.now() > end) throw new Error(`timed out: ${what}`);+ await sleep(250);+ }+}+class Pipe {+ constructor(proc) {+ this.out = proc.stdio[3];+ this.next = 1;+ this.waiting = new Map();+ let buf = "";+ proc.stdio[4].on("data", (d) => {+ buf += d.toString("utf8");+ let i;+ while ((i = buf.indexOf(NUL)) >= 0) {+ const m = JSON.parse(buf.slice(0, i));+ buf = buf.slice(i + 1);+ const w = m.id && this.waiting.get(m.id);+ if (!w) continue;+ this.waiting.delete(m.id);+ if (m.error) w.reject(new Error(`${w.method}: ${m.error.message}`));+ else w.resolve(m.result);+ }+ });+ }+ send(method, params = {}, sessionId) {+ const id = this.next++;+ this.out.write(JSON.stringify({ id, method, params, ...(sessionId ? { sessionId } : {}) }) + NUL);+ return new Promise((resolve, reject) => {+ this.waiting.set(id, { resolve, reject, method });+ setTimeout(() => this.waiting.has(id) && (this.waiting.delete(id), reject(new Error(`${method}: no answer in 60 s`))), 60000);+ });+ }+}+const run = (cmd, args) => {+ try {+ return execFileSync(cmd, args, { encoding: "utf8" });+ } catch (e) {+ return e.stdout || "";+ }+};+const windows = () => run("wmctrl", ["-l"]);+const closeVideo = () => run("wmctrl", ["-c", "Download video from a page"]);+const ytdlpPids = () => run("pgrep", ["-f", "^python3 /usr/local/bin/yt-dlp"]).split(NL).filter(Boolean);+const argOf = (pid) => {+ try {+ return fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").split(NUL).filter(Boolean).pop();+ } catch {+ return null;+ }+};++const profile = path.join(process.env.HOME, "lab/chrome-streams");+fs.rmSync(profile, { recursive: true, force: true });+fs.mkdirSync(path.join(profile, "Default"), { recursive: true });+// With --user-data-dir, Chrome on Linux reads host manifests from <user-data-dir>/NativeMessagingHosts+// (not ~/.config/google-chrome/): the one MDM registered, copied there.+const hosts = path.join(profile, "NativeMessagingHosts");+fs.mkdirSync(hosts, { recursive: true });+const registered = path.join(process.env.HOME, ".config/google-chrome/NativeMessagingHosts/com.misterdownloadmanager.host.json");+fs.copyFileSync(registered, path.join(hosts, "com.misterdownloadmanager.host.json"));+const proc = spawn(+ "/usr/bin/google-chrome",+ ["--headless", "--remote-debugging-pipe", "--enable-unsafe-extension-debugging", "--password-store=basic", `--user-data-dir=${profile}`, "--no-first-run", "--no-default-browser-check", "--window-size=1280,900", "about:blank"],+ { stdio: ["ignore", "ignore", "ignore", "pipe", "pipe"] },+);+const out = [];+const say = (s) => {+ console.log(s);+ out.push(s);+};+try {+ const cdp = new Pipe(proc);+ const { product } = await cdp.send("Browser.getVersion");+ const { id } = await cdp.send("Extensions.loadUnpacked", { path: ext });+ say(`${product} (headless), extension ${id} from ${ext}`);+ await until("the extension's service worker", 15000, async () =>+ (await cdp.send("Target.getTargets")).targetInfos.find((t) => t.type === "service_worker" && t.url.includes(id)),+ );+ say("service worker running");+ const { targetId } = await cdp.send("Target.createTarget", { url: "about:blank" });+ const { sessionId } = await cdp.send("Target.attachToTarget", { targetId, flatten: true });+ await cdp.send("Page.enable", {}, sessionId);+ const evaluate = async (expression, s = sessionId) => {+ const r = await cdp.send("Runtime.evaluate", { expression, userGesture: true, awaitPromise: true, returnByValue: true }, s);+ if (r.exceptionDetails) throw new Error(`evaluate: ${r.exceptionDetails.text}`);+ return r.result.value;+ };+ const navigate = async (url) => {+ await cdp.send("Page.navigate", { url }, sessionId);+ await until(`the page ${url}`, 15000, () => evaluate("[location.href, document.readyState]").then(([at, st]) => st === "complete" && at === new URL(url).href));+ };+ const mouse = async (x, y, act = "move") => {+ const at = { x, y, button: "left", buttons: 0, modifiers: 0 };+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseMoved", ...at }, sessionId);+ if (act === "click") {+ await cdp.send("Input.dispatchMouseEvent", { type: "mousePressed", ...at, buttons: 1, clickCount: 1 }, sessionId);+ await cdp.send("Input.dispatchMouseEvent", { type: "mouseReleased", ...at, buttons: 0, clickCount: 1 }, sessionId);+ }+ };+ const rect = (sel) =>+ evaluate(`(() => { const e = document.querySelector(${JSON.stringify(sel)});+ if (!e || (e.localName === "mdm-video-button" && e.style.display !== "block")) return null;+ const r = e.getBoundingClientRect(); return { l: r.left, t: r.top, r: r.right, b: r.bottom }; })()`);+ const labLog = async () => await (await fetch(`${LAB}/_log`)).json();+ const check = async (what, page, manifest, cookie, trigger) => {+ closeVideo();+ await until("earlier yt-dlp lookups to end", 90000, async () => ytdlpPids().length === 0).catch(() => {});+ await sleep(1000);+ await fetch(`${LAB}/_log`, { method: "DELETE" });+ const before = new Set(ytdlpPids());+ const t0 = Date.now();+ const r = await trigger();+ const secs = () => ((Date.now() - t0) / 1000).toFixed(1);+ let windowAt = null;+ let given = null;+ let pid = null;+ const end = Date.now() + 60000;+ while (Date.now() < end && !(windowAt && given)) {+ if (!windowAt && windows().includes("Download video from a page")) windowAt = secs();+ if (!given) {+ pid = ytdlpPids().find((x) => !before.has(x));+ if (pid) given = argOf(pid);+ }+ await sleep(200);+ }+ if (pid) await until("yt-dlp's lookup", 90000, async () => !fs.existsSync(`/proc/${pid}`)).catch(() => {});+ const done = secs();+ const asked = (await labLog()).filter((e) => e.referer === page || e.path === "/page" || e.path === manifest);+ const seen = asked.map((e) => `${e.path}${e.query ? "?" + e.query : ""} ${e.status}${(e.cookie || "").includes(cookie) ? " +cookie" : ""}${e.referer === page ? " +referrer" : ""}`);+ const ok = windowAt && given && new URL(given).pathname === manifest && asked.some((e) => e.path === manifest) && !asked.some((e) => e.path === "/page");+ say(+ `${ok ? "OK " : "FAIL"} ${what}${r ? ` (${r})` : ""}: MDM's window ${windowAt ? `at ${windowAt} s` : "NOT within 60 s"}; ` ++ `yt-dlp given ${given || "nothing"}, done at ${done} s; the lab saw ${seen.join(", ") || "nothing"}`,+ );+ };+ for (const [kind, manifest] of KINDS) {+ const cookie = `sid155=chrome-${kind}`;+ await navigate(`${LAB}/cookie?set=${encodeURIComponent(cookie)}`);+ const page = `${LAB}/page?${kind}=1`;+ await navigate(page);+ const state = await until("the stream player", 20000, () => evaluate("document.body.dataset.stream || ''"));+ say(`${kind}: the page's player: ${state}`);+ const v = await rect("#player");+ await check(`${kind} button`, page, manifest, cookie, async () => {+ let b = null;+ for (let i = 0; i < 40 && !b; i++) {+ await mouse((v.l + v.r) / 2 + (i % 2), (v.t + v.b) / 2);+ b = await rect("mdm-video-button");+ if (!b) await sleep(200);+ }+ if (!b) return "no button over the player";+ await mouse(b.l + 14, (b.t + b.b) / 2, "click");+ return "";+ });+ await check(`${kind} media list`, page, manifest, cookie, async () => {+ const url = `chrome-extension://${id}/popup.html?page=${encodeURIComponent(page)}`;+ const { targetId: tid } = await cdp.send("Target.createTarget", { url });+ const { sessionId: s } = await cdp.send("Target.attachToTarget", { targetId: tid, flatten: true });+ const name = manifest.split("/").pop();+ const rows = await until("the media list", 15000, () =>+ evaluate(`[...document.querySelectorAll("#media-list li")].map((li) => li.querySelector(".name").textContent + (li.querySelector("button") ? " [Download]" : ""))`, s).then((r) => r && r.length && r),+ );+ const clicked = await evaluate(+ `(() => { const li = [...document.querySelectorAll("#media-list li")].find((x) => x.querySelector(".name").textContent === ${JSON.stringify(name)}); if (!li || !li.querySelector("button")) return false; li.querySelector("button").click(); return true; })()`,+ s,+ );+ setTimeout(() => cdp.send("Target.closeTarget", { targetId: tid }).catch(() => {}), 20000);+ return `list: ${rows.join("; ")}${clicked ? "" : "; no Download for " + name}`;+ });+ }+} catch (e) {+ say(`ERROR ${e.message}`);+} finally {+ proc.kill();+ fs.writeFileSync(path.join(process.env.HOME, "lab/streams-chrome.txt"), out.join(NL) + NL);+}+process.exit(0);diff --git a/tools/lab/linux-vm/streams.mjs b/tools/lab/linux-vm/streams.mjsnew file mode 100644index 00000000..c6879e2a--- /dev/null+++ b/tools/lab/linux-vm/streams.mjs@@ -0,0 +1,256 @@+// #155/#167 on Linux: the Snap Firefox (headless, over WebDriver BiDi, as tools/extension/e2e.mjs+// drives it) with an add-on, on the lab server's HLS and DASH player pages. Each hand-over path+// (the button over the player, the right-click menu, the popup's media list) is triggered, then:+// when the host started, when MDM's Download video window opened, the address yt-dlp was given,+// and what yt-dlp asked the lab for once it finished. MDM must be running and not minimized.+// node streams.mjs <xpi> [lab] [kinds] lab: http://127.0.0.1:8097+// kinds: page flag and manifest path, default "hls:/hls/master.m3u8,dash:/dash/manifest.mpd";+// #171's streams without endings: "hls2:/hls2/playlist,dash2:/dash2/manifest"+import fs from "node:fs";+import path from "node:path";+import { spawn, execFileSync } from "node:child_process";++const xpi = path.resolve(process.argv[2]);+const LAB = process.argv[3] || "http://127.0.0.1:8097";+const KINDS = (process.argv[4] || "hls:/hls/master.m3u8,dash:/dash/manifest.mpd").split(",").map((k) => k.split(":"));+const ID = "[email protected]";+const UUID = "5d0c3b8e-7a51-4c1e-9f0a-38e2c4a1d7b6";+const NL = String.fromCharCode(10);+const NUL = String.fromCharCode(0);+const sleep = (ms) => new Promise((r) => setTimeout(r, ms));+async function until(what, ms, f) {+ const end = Date.now() + ms;+ for (;;) {+ const v = await f().catch(() => null);+ if (v) return v;+ if (Date.now() > end) throw new Error(`timed out: ${what}`);+ await sleep(250);+ }+}+class Bidi {+ constructor(ws) {+ this.ws = ws;+ this.next = 1;+ this.waiting = new Map();+ ws.addEventListener("message", (e) => {+ const m = JSON.parse(e.data);+ const w = m.id && this.waiting.get(m.id);+ if (!w) return;+ this.waiting.delete(m.id);+ if (m.type === "error") w.reject(new Error(`${w.method}: ${m.error} ${m.message}`));+ else w.resolve(m.result);+ });+ }+ send(method, params = {}) {+ const id = this.next++;+ this.ws.send(JSON.stringify({ id, method, params }));+ return new Promise((resolve, reject) => this.waiting.set(id, { resolve, reject, method }));+ }+}+const run = (cmd, args) => {+ try {+ return execFileSync(cmd, args, { encoding: "utf8" });+ } catch (e) {+ return e.stdout || "";+ }+};+const windows = () => run("wmctrl", ["-l"]);+const closeVideo = () => run("wmctrl", ["-c", "Download video from a page"]);+const ytdlpPids = () => run("pgrep", ["-f", "^python3 /usr/local/bin/yt-dlp"]).split(NL).filter(Boolean);+const argOf = (pid) => {+ try {+ return fs.readFileSync(`/proc/${pid}/cmdline`, "utf8").split(NUL).filter(Boolean).pop();+ } catch {+ return null;+ }+};+const hostLog = path.join(process.env.HOME, "lab/hostwrap.log");+const hostLaunches = () => {+ try {+ return fs.readFileSync(hostLog, "utf8").split(NL).filter((l) => l.startsWith("== ") && l.includes("args")).length;+ } catch {+ return 0;+ }+};++// A profile the Snap can read (not /tmp: a Snap has its own).+const profile = path.join(process.env.HOME, "snap/firefox/common/mdm-streams");+fs.rmSync(profile, { recursive: true, force: true });+fs.mkdirSync(profile, { recursive: true });+const pref = (k, v) => `user_pref(${JSON.stringify(k)}, ${JSON.stringify(v)});`;+fs.writeFileSync(+ path.join(profile, "user.js"),+ [+ pref("browser.shell.checkDefaultBrowser", false),+ pref("datareporting.policy.dataSubmissionEnabled", false),+ pref("browser.aboutwelcome.enabled", false),+ pref("extensions.originControls.grantByDefault", true),+ pref("extensions.webextensions.uuids", JSON.stringify({ [ID]: UUID })),+ ].join(NL),+);+const port = 9300 + Math.floor(Math.random() * 500);+const ff = spawn("/snap/bin/firefox", ["-headless", "-no-remote", "-profile", profile, "--remote-debugging-port", String(port), "--width=1280", "--height=900"], {+ env: { ...process.env, MOZ_HEADLESS: "1", MOZ_REMOTE_ALLOW_SYSTEM_ACCESS: "1" },+ stdio: "ignore",+});+const out = [];+const say = (s) => {+ console.log(s);+ out.push(s);+};+try {+ const ws = await until("Firefox's remote protocol", 60000, () =>+ new Promise((resolve) => {+ const s = new WebSocket(`ws://127.0.0.1:${port}/session`);+ s.addEventListener("open", () => resolve(s));+ s.addEventListener("error", () => resolve(null));+ }),+ );+ const bidi = new Bidi(ws);+ const { capabilities } = await bidi.send("session.new", { capabilities: {} });+ say(`Firefox ${capabilities.browserVersion} (Snap, headless), add-on ${path.basename(xpi)}`);+ await bidi.send("webExtension.install", { extensionData: { type: "archivePath", path: xpi } });+ const { contexts } = await bidi.send("browsingContext.getTree", {});+ const context = contexts[0].context;+ const evaluate = async (expression, c = context) => {+ const r = await bidi.send("script.evaluate", {+ expression: `(async () => JSON.stringify(await (${expression})))()`,+ target: { context: c },+ awaitPromise: true,+ userActivation: true,+ });+ if (r.type === "exception") throw new Error(`evaluate: ${r.exceptionDetails.text}`);+ return r.result.value === undefined ? undefined : JSON.parse(r.result.value);+ };+ const navigate = (url) => bidi.send("browsingContext.navigate", { context, url, wait: "complete" });+ const mouse = (x, y, act = "move", button = 0) => {+ const a = [{ type: "pointerMove", x: Math.round(x), y: Math.round(y) }];+ if (act === "click") a.push({ type: "pointerDown", button }, { type: "pointerUp", button });+ return bidi.send("input.performActions", { context, actions: [{ type: "pointer", id: "mouse", actions: a }] });+ };+ const rect = (sel) =>+ evaluate(`(() => { const e = document.querySelector(${JSON.stringify(sel)});+ if (!e || (e.localName === "mdm-video-button" && e.style.display !== "block")) return null;+ const r = e.getBoundingClientRect(); return { l: r.left, t: r.top, r: r.right, b: r.bottom }; })()`);+ const chrome = async (expression) => {+ const { contexts: w } = await bidi.send("browsingContext.getTree", { "moz:scope": "chrome" });+ const r = await bidi.send("script.evaluate", { expression, target: { context: w[0].context }, awaitPromise: true, "moz:scope": "chrome" });+ if (r.type === "exception") throw new Error(`chrome: ${r.exceptionDetails.text}`);+ return r.result.value;+ };+ const labLog = async () => await (await fetch(`${LAB}/_log`)).json();++ // One path: earlier lookups ended, the log cleared, then the trigger; what followed.+ const check = async (what, page, manifest, cookie, trigger) => {+ closeVideo();+ await until("earlier yt-dlp lookups to end", 90000, async () => ytdlpPids().length === 0).catch(() => {});+ await sleep(1000);+ await fetch(`${LAB}/_log`, { method: "DELETE" });+ const before = new Set(ytdlpPids());+ const launches = hostLaunches();+ const t0 = Date.now();+ const r = await trigger();+ const secs = () => ((Date.now() - t0) / 1000).toFixed(1);+ let hostAt = null;+ let windowAt = null;+ let given = null;+ let pid = null;+ const end = Date.now() + 60000;+ while (Date.now() < end && !(windowAt && given)) {+ if (!hostAt && hostLaunches() > launches) hostAt = secs();+ if (!windowAt && windows().includes("Download video from a page")) windowAt = secs();+ if (!given) {+ pid = ytdlpPids().find((x) => !before.has(x));+ if (pid) given = argOf(pid);+ }+ await sleep(200);+ }+ if (pid) await until("yt-dlp's lookup", 90000, async () => !fs.existsSync(`/proc/${pid}`)).catch(() => {});+ const done = secs();+ const asked = (await labLog()).filter((e) => e.referer === page || e.path === "/page" || e.path === manifest);+ const seen = asked.map((e) => `${e.path}${e.query ? "?" + e.query : ""} ${e.status}${(e.cookie || "").includes(cookie) ? " +cookie" : ""}${e.referer === page ? " +referrer" : ""}`);+ const ok = windowAt && given && new URL(given).pathname === manifest && asked.some((e) => e.path === manifest) && !asked.some((e) => e.path === "/page");+ say(+ `${ok ? "OK " : "FAIL"} ${what}${r ? ` (${r})` : ""}: host started ${hostAt ? `at ${hostAt} s` : "?"}, ` ++ `MDM's window ${windowAt ? `at ${windowAt} s` : "NOT within 60 s"}; yt-dlp given ${given || "nothing"}, done at ${done} s; ` ++ `the lab saw ${seen.join(", ") || "nothing"}`,+ );+ };++ for (const [kind, manifest] of KINDS) {+ const cookie = `sid155=linux-${kind}`;+ await navigate(`${LAB}/cookie?set=${encodeURIComponent(cookie)}`);+ const page = `${LAB}/page?${kind}=1`;+ await fetch(`${LAB}/_log`, { method: "DELETE" });+ await navigate(page);+ const state = await until("the stream player", 20000, () => evaluate("document.body.dataset.stream || ''"));+ await sleep(3000);+ // The master itself (the first address of that path), not its variants (same path, more query).+ const played = (await labLog()).filter((e) => e.path === manifest);+ const master = played.length ? played[0].path + (played[0].query ? "?" + played[0].query : "") : manifest;+ const times = played.filter((e) => e.path + (e.query ? "?" + e.query : "") === master).length;+ say(`${kind}: the page's player: ${state}; while it played, before anything was asked: ${master} ${times}×, ${played.length - times} variant request(s)`);+ const v = await rect("#player");+ await check(`${kind} button`, page, manifest, cookie, async () => {+ let b = null;+ for (let i = 0; i < 40 && !b; i++) {+ await mouse((v.l + v.r) / 2 + (i % 2), (v.t + v.b) / 2);+ b = await rect("mdm-video-button");+ if (!b) await sleep(200);+ }+ if (!b) return "no button over the player";+ await mouse(b.l + 14, (b.t + b.b) / 2, "click");+ return "";+ });+ await check(`${kind} right-click menu`, page, manifest, cookie, async () => {+ await mouse((v.l + v.r) / 2, (v.t + v.b) / 2, "click", 2);+ return chrome(`(async () => {+ const menu = document.getElementById("contentAreaContextMenu");+ const shown = () => [...menu.querySelectorAll("menuitem")].filter((m) => !m.hidden);+ const L = "Download with Mister Download Manager";+ for (let i = 0; i < 50 && !shown().some((m) => m.label === L); i++) await new Promise((r) => setTimeout(r, 100));+ const item = shown().find((m) => m.label === L);+ if (!item) { const all = shown().map((m) => m.label).join(" | "); menu.hidePopup(); return "not there: " + all; }+ const at = gContextMenu ? { onVideo: gContextMenu.onVideo, mediaURL: gContextMenu.mediaURL } : null;+ menu.activateItem(item);+ return "chosen " + JSON.stringify(at);+ })()`);+ });+ await check(`${kind} media list`, page, manifest, cookie, async () => {+ const url = `moz-extension://${UUID}/popup.html?page=${encodeURIComponent(page)}`;+ await chrome(`gBrowser.addTab(${JSON.stringify(url)}, { triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal() }) && "opened"`);+ const c = await until("the popup's tab", 10000, async () => ((await bidi.send("browsingContext.getTree", {})).contexts.find((x) => x.url === url) || {}).context);+ const name = manifest.split("/").pop();+ const rows = await until("the media list", 15000, () =>+ evaluate(`[...document.querySelectorAll("#media-list li")].map((li) => li.querySelector(".name").textContent + (li.querySelector("button") ? " [Download]" : ""))`, c).then((r) => r && r.length && r),+ );+ const clicked = await evaluate(+ `(() => { const li = [...document.querySelectorAll("#media-list li")].find((x) => x.querySelector(".name").textContent === ${JSON.stringify(name)}); if (!li || !li.querySelector("button")) return false; li.querySelector("button").click(); return true; })()`,+ c,+ );+ setTimeout(() => bidi.send("browsingContext.close", { context: c }).catch(() => {}), 20000);+ return `list: ${rows.join("; ")}${clicked ? "" : "; no Download for " + name}`;+ });+ }+ // Every kind on one page: the popup's media list shows exactly those streams.+ if (KINDS.length > 1) {+ const page = `${LAB}/page?${KINDS.map(([k]) => `${k}=1`).join("&")}`;+ await navigate(page);+ await until("the stream players", 20000, () => evaluate("document.body.dataset.stream || ''"));+ await sleep(3000);+ const url = `moz-extension://${UUID}/popup.html?page=${encodeURIComponent(page)}`;+ await chrome(`gBrowser.addTab(${JSON.stringify(url)}, { triggeringPrincipal: Services.scriptSecurityManager.getSystemPrincipal() }) && "opened"`);+ const c = await until("the popup's tab", 10000, async () => ((await bidi.send("browsingContext.getTree", {})).contexts.find((x) => x.url === url) || {}).context);+ const rowsNow = () => evaluate(`[...document.querySelectorAll("#media-list li")].map((li) => [li.querySelector(".tag").textContent, li.querySelector(".name").textContent, li.querySelector(".meta").textContent].join(" "))`, c);+ await until("the media list", 20000, () => rowsNow().then((r) => r && r.length >= KINDS.length && r)).catch(() => {});+ await sleep(2000);+ const rows = await rowsNow();+ say(`all on one page (${page.replace(LAB, "")}): the media list: ${rows.join(" | ") || "empty"}`);+ }+} catch (e) {+ say(`ERROR ${e.message}`);+} finally {+ ff.kill();+ fs.writeFileSync(path.join(process.env.HOME, "lab/streams.txt"), out.join(NL) + NL);+}+process.exit(0);diff --git a/tools/lab/linux-vm/torrent-menu.sh b/tools/lab/linux-vm/torrent-menu.shnew file mode 100644index 00000000..c16ad580--- /dev/null+++ b/tools/lab/linux-vm/torrent-menu.sh@@ -0,0 +1,52 @@+#!/bin/bash+# A torrent in MDM's list without any network: a .torrent made here for a local file (no trackers),+# the torrent network off (no DHT, UPnP, local discovery, incoming connections), added through a+# second launch; Add torrent shows, then is confirmed. For the torrent windows' and menus' checks.+# torrent-menu.sh <label> add start MDM, open Add torrent for the lab torrent (prints its frame)+# torrent-menu.sh <label> confirm press Add torrent's default button+. ~/lab/env.sh+app=$HOME/lab/bin/$1/misterdownloadmanager+data=$HOME/.local/share/misterdownloadmanager+dir=$HOME/lab/t177+frame() {+ local w=$1+ read -r l r top b < <(xprop -id "$w" _NET_FRAME_EXTENTS | grep -o '[0-9]\+' | tr '\n' ' ')+ xwininfo -id "$w" | awk -v l="${l:-0}" -v r="${r:-0}" -v t="${top:-0}" -v b="${b:-0}" '/Absolute upper-left X/ {x=$4} /Absolute upper-left Y/ {y=$4} /Width:/ {w=$2} /Height:/ {h=$2}+ END {print x - l, y - t, w + l + r, h + t + b}'+}+case "$2" in+ add)+ mkdir -p "$dir"+ [ -f "$dir/lab-order.bin" ] || head -c 1048576 /dev/urandom > "$dir/lab-order.bin"+ python3 - "$dir/lab-order.bin" "$dir/lab-order.torrent" <<'PY'+import hashlib, sys+src, out = sys.argv[1:3]+data = open(src, "rb").read()+plen = 65536+pieces = b"".join(hashlib.sha1(data[i:i + plen]).digest() for i in range(0, len(data), plen))+def be(x):+ if isinstance(x, int): return b"i%de" % x+ if isinstance(x, str): x = x.encode()+ if isinstance(x, bytes): return b"%d:%s" % (len(x), x)+ if isinstance(x, dict): return b"d" + b"".join(be(k) + be(x[k]) for k in sorted(x)) + b"e"+info = {"name": "lab-order.bin", "length": len(data), "piece length": plen, "pieces": pieces}+open(out, "wb").write(be({"info": info, "created by": "mdm lab"}))+PY+ pkill -x misterdownloadm; sleep 2+ python3 - "$data/downloads.json" <<'PY'+import json, sys+p = sys.argv[1]+d = json.load(open(p))+d["settings"].update(torrent_dht=False, torrent_upnp=False, torrent_lsd=False, torrent_incoming=False,+ language="en", language_asked=True, always_dark=False, dark_mode_support=False)+json.dump(d, open(p, "w"))+PY+ cd ~; setsid -f "$app" >/dev/null 2>&1 </dev/null; sleep 12+ "$app" "$dir/lab-order.torrent"+ for _ in $(seq 40); do w=$(wmctrl -l | grep -F 'Add torrent' | awk '{print $1}' | head -1); [ -n "$w" ] && break; sleep 0.5; done+ sleep 2; wmctrl -i -a "$w"; sleep 1; frame "$w" ;;+ confirm)+ w=$(wmctrl -l | grep -F 'Add torrent' | awk '{print $1}' | head -1)+ wmctrl -i -a "$w"; sleep 0.5; xdotool key Return; sleep 3+ wmctrl -l | grep -c -F 'Add torrent' ;;+esacdiff --git a/tools/lab/linux-vm/use-system-helpers.sh b/tools/lab/linux-vm/use-system-helpers.shnew file mode 100644index 00000000..eaac6f99--- /dev/null+++ b/tools/lab/linux-vm/use-system-helpers.sh@@ -0,0 +1,14 @@+#!/bin/bash+# MDM uses the system's yt-dlp, ffmpeg and gallery-dl as the person's own copies (Helpers' programs.json).+d=~/.local/share/misterdownloadmanager/tools; mkdir -p $d+python3 - "$d/programs.json" <<'PY'+import json, subprocess, shutil, sys+def v(cmd, args):+ exe = shutil.which(cmd)+ if not exe: return None+ out = subprocess.run([exe] + args, capture_output=True, text=True).stdout.strip().splitlines()[0]+ return {"version": out.split()[2] if cmd == "ffmpeg" else out, "exe": exe}+p = {k: x for k, x in {"yt-dlp": v("yt-dlp", ["--version"]), "ffmpeg": v("ffmpeg", ["-version"]), "gallery-dl": v("gallery-dl", ["--version"])}.items() if x}+open(sys.argv[1], "w").write(json.dumps(p))+print(p)+PYdiff --git a/tools/lab/linux-vm/vm.ps1 b/tools/lab/linux-vm/vm.ps1new file mode 100644index 00000000..63085e63--- /dev/null+++ b/tools/lab/linux-vm/vm.ps1@@ -0,0 +1,141 @@+<#+The Linux test machine from the Windows host: a VirtualBox VM (Ubuntu 24.04 desktop, GNOME on+Xorg) that runs headless. Everything goes through VBoxManage, so the host's own keyboard, mouse+and clipboard are never touched; keep the VM's clipboard sharing and drag-and-drop off.++ tools/lab/linux-vm/vm.ps1 configure # shut down cleanly, apply the lab's hardware+ tools/lab/linux-vm/vm.ps1 start # boot headless, wait for the desktop+ tools/lab/linux-vm/vm.ps1 setup [-Branch <name>] # copy the guest scripts to ~/lab and run setup.sh+ # (long: packages, Rust, the first build)+ tools/lab/linux-vm/vm.ps1 run "<bash command>" # run in the desktop user's session+ tools/lab/linux-vm/vm.ps1 shot <file.png> # screenshot of the VM's screen+ tools/lab/linux-vm/vm.ps1 get <guest path> <host folder>+ tools/lab/linux-vm/vm.ps1 put <host file> <guest path>+ tools/lab/linux-vm/vm.ps1 clone <new name> [-Snapshot <name>] [-Cpus 6] [-MemoryMb 10240]+ # a linked clone of a snapshot of $MDM_VM, its own+ # hostname; then `start` it with MDM_VM=<name>++In the guest (~/lab, from `setup`):+ build.sh <ref> [label] a branch, PR (pr/<n>) or commit, built with the lab's vmtest profile+ into ~/lab/bin/<label>/, in a terminal on the lab's desktop+ restart-lab.sh <label> the lab server and MDM from one build, restarted+ shots.sh <label> <window> <lang> <light|dark> one window ready for a screenshot (its frame+ printed); shot-host.sh, on the host, crops VirtualBox's screenshot+ to it; pixdiff.py compares two folders of shots pixel by pixel+ measure.sh <program> <label> MDM's start-up timings+ streams.mjs, streams-chrome.mjs, run-streams.sh HLS and DASH players handed to MDM from the+ Snap Firefox and Google Chrome by the extension's three paths,+ checked against the lab server's log+ proxy-optin.mjs, chrome-popup.mjs the extension's popup: the proxy switch and its permission+ prompt in Firefox; any check of the popup in Chrome+ handoff-minimized.sh, queue-minimized.sh hand-overs and the Scheduler while MDM is minimized+ torrent-menu.sh a torrent in the list with no network, for the torrent windows+ use-system-helpers.sh MDM uses the system's yt-dlp, ffmpeg and gallery-dl++Snapshots for clones are taken powered off (`clone` shuts the VM down first when the snapshot+doesn't exist yet): a live snapshot saves the whole memory, and under Hyper-V (VirtualBox's NEM+mode, "VT-x is not available") it stalled with an empty .sav file and had to be killed.++The VM's name, user and password come from MDM_VM, MDM_VM_USER and MDM_VM_PASSWORD (defaults:+mdm-ubuntu, mdm, and the lab's throwaway password). Commands run with the desktop session's+DISPLAY and D-Bus, so GUI programs open on the VM's screen.+#>+param(+ [Parameter(Position = 0, Mandatory)] [ValidateSet('configure', 'start', 'setup', 'run', 'shot', 'get', 'put', 'clone')] [string] $Action,+ [Parameter(Position = 1)] [string] $Arg1,+ [Parameter(Position = 2)] [string] $Arg2,+ [string] $Branch = 'main',+ [string] $Snapshot = 'base',+ [int] $Cpus = 6,+ [int] $MemoryMb = 10240+)+$ErrorActionPreference = 'Stop'+$vbox = Join-Path $env:ProgramFiles 'Oracle\VirtualBox\VBoxManage.exe'+$vm = if ($env:MDM_VM) { $env:MDM_VM } else { 'mdm-ubuntu' }+$user = if ($env:MDM_VM_USER) { $env:MDM_VM_USER } else { 'mdm' }+$pass = if ($env:MDM_VM_PASSWORD) { $env:MDM_VM_PASSWORD } else { 'mdm123456789' }+$auth = @('--username', $user, '--password', $pass)++function Invoke-Guest([string] $Command) {+ # The desktop session's display and bus, so GUI programs and gsettings reach it.+ $session = 'export DISPLAY=:0 XDG_RUNTIME_DIR=/run/user/$(id -u) DBUS_SESSION_BUS_ADDRESS=unix:path=/run/user/$(id -u)/bus; ' ++ 'export XAUTHORITY=$(ls /run/user/$(id -u)/gdm/Xauthority 2>/dev/null || echo $HOME/.Xauthority); ' ++ "export MDM_SUDO_PASSWORD='$pass'; [ -f ~/.cargo/env ] && . ~/.cargo/env; "+ & $vbox guestcontrol $vm run --exe /bin/bash @auth --wait-stdout --wait-stderr -- -c ($session + $Command)+ if ($LASTEXITCODE) { throw "guest command failed ($LASTEXITCODE)" }+}++switch ($Action) {+ 'configure' {+ # Settings only change on a powered-off machine: an ACPI shutdown first, as a person would.+ $running = { (& $vbox showvminfo $vm --machinereadable | Select-String '^VMState=').ToString() -match 'running' }+ if (& $running) {+ & $vbox controlvm $vm acpipowerbutton+ for ($i = 0; $i -lt 90 -and (& $running); $i++) { Start-Sleep 2 }+ if (& $running) { throw "$vm did not shut down" }+ }+ # A USB tablet, so a viewer's pointer moves in and out without being captured. 8 CPUs,+ # 12 GB and 3D (VMSVGA): GNOME and MDM's OpenGL drawn by the host's GPU rather than+ # llvmpipe (VirtualBox may run on Hyper-V here, which is slower). Clipboard and+ # drag-and-drop stay off: nothing crosses between the lab and the host.+ & $vbox modifyvm $vm --usb-ohci on --mouse usbtablet --cpus 8 --memory 12288 `+ --graphicscontroller vmsvga --accelerate-3d on --vram 256 `+ --clipboard-mode disabled --drag-and-drop disabled+ if ($LASTEXITCODE) { throw "modifyvm failed ($LASTEXITCODE)" }+ }+ 'start' {+ $state = (& $vbox showvminfo $vm --machinereadable | Select-String '^VMState=').ToString()+ if ($state -notmatch 'running') { & $vbox startvm $vm --type headless | Out-Null }+ # Ready when the Guest Additions run (guestcontrol needs them) and the user is signed in.+ for ($i = 0; $i -lt 90; $i++) {+ $level = & $vbox showvminfo $vm --machinereadable | Select-String '^GuestAdditionsRunLevel=[23]'+ $users = & $vbox guestproperty get $vm /VirtualBox/GuestInfo/OS/LoggedInUsersList 2>$null+ if ($level -and "$users" -match "\b$user\b") { break }+ Start-Sleep 2+ }+ Start-Sleep 10+ Invoke-Guest 'loginctl list-sessions --no-legend | grep seat0'+ }+ 'setup' {+ Invoke-Guest 'mkdir -p ~/lab'+ # The guest side: setup, the build, the harnesses (everything here but this script).+ $files = Get-ChildItem $PSScriptRoot -File | Where-Object { $_.Extension -in '.sh', '.mjs' -and $_.Name -ne 'shot-host.sh' } | ForEach-Object FullName+ & $vbox guestcontrol $vm copyto @auth --target-directory /home/$user/lab/ @files+ Invoke-Guest "bash ~/lab/setup.sh --branch '$Branch'"+ }+ 'clone' {+ # A linked clone shares the snapshot's disk and writes only its own changes: small, and+ # it has the toolchain, the checkout and a warm target folder already.+ $name = $Arg1+ if (-not $name) { throw 'clone: a name for the new VM' }+ $snaps = & $vbox snapshot $vm list --machinereadable 2>$null+ if (-not ($snaps | Select-String "=`"$Snapshot`"")) {+ $running = { (& $vbox showvminfo $vm --machinereadable | Select-String '^VMState=').ToString() -match 'running' }+ if (& $running) {+ & $vbox controlvm $vm acpipowerbutton+ for ($i = 0; $i -lt 90 -and (& $running); $i++) { Start-Sleep 2 }+ if (& $running) { throw "$vm did not shut down" }+ }+ & $vbox snapshot $vm take $Snapshot --description 'Lab base for linked clones (tools/lab/linux-vm)'+ }+ & $vbox clonevm $vm --snapshot $Snapshot --options link --name $name --register+ if ($LASTEXITCODE) { throw "clonevm failed ($LASTEXITCODE)" }+ # The lab's hardware rules, with its own size; clipboard and drag-and-drop stay off.+ & $vbox modifyvm $name --cpus $Cpus --memory $MemoryMb --usb-ohci on --mouse usbtablet `+ --graphicscontroller vmsvga --accelerate-3d on --vram 256 `+ --clipboard-mode disabled --drag-and-drop disabled+ & $vbox startvm $name --type headless | Out-Null+ for ($i = 0; $i -lt 90; $i++) {+ $level = & $vbox showvminfo $name --machinereadable | Select-String '^GuestAdditionsRunLevel=[23]'+ if ($level) { break }+ Start-Sleep 2+ }+ Start-Sleep 10+ & $vbox guestcontrol $name run --exe /bin/bash @auth --wait-stdout --wait-stderr -- -c `+ "echo '$pass' | sudo -S -p '' hostnamectl set-hostname $name && echo '$pass' | sudo -S -p '' sed -i 's/$vm/$name/g' /etc/hosts && hostname"+ }+ 'run' { Invoke-Guest $Arg1 }+ 'shot' { & $vbox controlvm $vm screenshotpng ([IO.Path]::GetFullPath($Arg1)) }+ 'get' { & $vbox guestcontrol $vm copyfrom @auth --target-directory $Arg2 $Arg1 }+ 'put' { & $vbox guestcontrol $vm copyto @auth --target-directory $Arg2 $Arg1 }+}