Skip to content

XP event5x XPListening, games, ratings, comments and chat earn five times the XP

leftLeaderboard

juicewrld-desktopsrc-tauriplugin-testtest.js

1.4.2Released Nov 21, 2026

test.js

838 lines32.4 KBJavaScript
// The plugin test page (debug builds): every step of the site's plugin API against the plugins in the scanned folders,// by hand or by script (window.jwTest has the same steps as functions returning their numbers)."use strict";const P = window.juicewrldDesktop && window.juicewrldDesktop.plugins;const $ = (id) => document.getElementById(id);const RATE = 48000;const t0 = performance.now();function log(...parts) {  const line = parts.map((x) => (typeof x === "string" ? x : JSON.stringify(x))).join(" ");  const el = $("log");  el.textContent += `${((performance.now() - t0) / 1000).toFixed(2).padStart(8)}  ${line}\n`;  el.scrollTop = el.scrollHeight;  console.log(line);}function show(text) {  $("results").textContent = typeof text === "string" ? text : JSON.stringify(text, null, 2);}const state = {  plugins: [],  picked: null,  inst: null,  ctx: null,  pnode: null,  graph: null,  file: null,  saved: null,  savedParams: null,  busyTimer: 0,  statsTimer: 0,  params: [],  playOptions: {},  // Whether the person at the PC ticked "Hear it" (a real click: scripts can't). Until then nothing this page plays  // reaches the speakers: every graph ends in a monitor at zero gain, and the numbers come from the tap's samples.  hearing: false,  monitor: null,  // Every monitor of every graph still playing, so unticking "Hear it" silences them all at once.  monitors: new Set(),};// ---- status and the list ----async function refresh() {  if (!P) {    $("status").textContent = "No plugin API here (window.juicewrldDesktop.plugins is missing).";    return null;  }  const s = await P.status();  const scan = s.scan ? `, ${s.scan.modules} modules, last scan ${s.scan.read} read (${s.scan.loaded} loaded) in ${(s.scan.millis / 1000).toFixed(1)} s` : "";  const extra = `${s.unread ? `, ${s.unread} need activation or didn't load` : ""}${s.hidden ? `, ${s.hidden} hidden` : ""}`;  $("status").textContent = !s.supported    ? "This copy of the app can't run plugins."    : !s.enabled      ? "Plugins are off: turn them on in the app's menu (the dots in the title bar), or ask."      : s.scanning        ? `Looking for plugins${s.progress ? `: ${s.progress.module} (${Math.min(s.progress.done + 1, s.progress.total)} of ${s.progress.total})` : "…"}`        : !s.scanned          ? "Not scanned yet: Ask to scan, or Scan for plugins in the app's menu."          : `${s.plugins} plugins${scan}${extra}`;  $("enable").disabled = s.enabled || !s.supported;  $("rescan").disabled = !s.enabled || s.scanning;  return s;}async function loadList() {  state.plugins = await P.list();  renderList();  return state.plugins.length;}/** Asks the user (in the app's title bar) to scan; resolves once their scan is done. */async function requestScan() {  const done = await P.requestScan();  log(`requestScan: ${done}`);  await refresh();  if (done) await loadList();  return done;}function renderList() {  const q = $("search").value.trim().toLowerCase();  const kind = $("kind").value;  const ol = $("plugins");  ol.textContent = "";  for (const p of state.plugins) {    if (kind !== "all" && p.kind !== kind) continue;    if (q && !`${p.name} ${p.vendor}`.toLowerCase().includes(q)) continue;    const li = document.createElement("li");    li.setAttribute("aria-selected", String(state.picked && state.picked.id === p.id));    const name = document.createElement("span");    name.textContent = p.name;    li.append(name);    if (p.kind !== "effect") li.append(Object.assign(document.createElement("span"), { className: "badge", textContent: p.kind }));    if (p.surround) li.append(Object.assign(document.createElement("span"), { className: "badge", textContent: "surround" }));    li.append(Object.assign(document.createElement("span"), { className: "vendor", textContent: p.vendor }));    li.onclick = () => pick(p);    ol.append(li);  }}function pick(p) {  state.picked = p;  $("name").textContent = p.name;  $("meta").textContent = `${p.vendor} · ${p.version} · ${p.kind} · ${p.categories.join(", ")} · ${p.module} · ${p.id}`;  $("open").disabled = false;  renderList();}function findPlugin(nameOrId) {  const q = String(nameOrId).toLowerCase();  return (    state.plugins.find((p) => p.id.toLowerCase() === q) ||    state.plugins.find((p) => p.name.toLowerCase() === q) ||    state.plugins.find((p) => p.name.toLowerCase().includes(q))  );}// ---- the instance ----async function openPicked() {  await closeInstance();  const p = state.picked;  const inst = await P.open({ id: p.id, sampleRate: RATE, blockSize: Number($("block").value), label: $("label").value });  state.inst = inst;  inst.on("lost", (l) => {    log(`lost ${inst.name}: ${l.reason}${l.code ? ` (${l.code})` : ""}${l.culprit ? ", the plugin that crashed" : ""}`);    $("instance").innerHTML = "";    $("instance").append(Object.assign(document.createElement("span"), { className: "bad", textContent: `Lost: ${l.reason}` }));    stopAudio();    enable(false);  });  inst.on("latency", (e) => log(`latency now ${e.latency}`));  inst.on("param", (e) => {    const input = document.querySelector(`[data-param="${e.id}"]`);    if (input && e.phase === "change") input.value = String(e.value);  });  inst.on("editor", (e) => log(`editor ${e.open ? "open" : "closed"}`));  $("instance").textContent =    `Instance ${inst.id}: ${inst.layout} (${inst.inputs} in, ${inst.outputs} out, ${inst.inBuses}/${inst.outBuses} buses), ` +    `latency ${inst.latency} samples (${((inst.latency / RATE) * 1000).toFixed(2)} ms), ${inst.parameterCount} parameters` +    `${inst.bypassParameter ? ", its own bypass" : ""}${inst.hasEditor ? ", an editor" : ""}`;  log(`opened ${inst.name}: ${$("instance").textContent}`);  enable(true);  await loadParams();  return describe(inst);}function describe(inst) {  return {    instance: inst.id,    name: inst.name,    layout: inst.layout,    inputs: inst.inputs,    outputs: inst.outputs,    latency: inst.latency,    parameters: inst.parameterCount,    bypassParameter: inst.bypassParameter,    hasEditor: inst.hasEditor,  };}function enable(on) {  for (const id of ["close", "play", "show", "hide", "save", "reset", "render", "measure"]) $(id).disabled = !on;  $("restore").disabled = !on || !state.saved;  $("stop").disabled = !state.ctx;}async function closeInstance() {  await stopAudio();  if (state.inst) await state.inst.close();  state.inst = null;  state.saved = null;  enable(false);}async function loadParams() {  const ol = $("params");  ol.textContent = "";  state.params = await state.inst.parameters();  for (const p of state.params.filter((p) => !p.hidden).slice(0, 80)) {    const li = document.createElement("li");    const label = Object.assign(document.createElement("span"), { textContent: `${p.title}${p.units ? ` (${p.units})` : ""}` });    const input = Object.assign(document.createElement("input"), { type: "range", min: "0", max: "1", step: p.steps > 0 ? String(1 / p.steps) : "0.001", value: String(p.value) });    input.dataset.param = String(p.id);    const shown = Object.assign(document.createElement("span"), { textContent: p.display });    input.oninput = () => state.inst.setParameter(p.id, Number(input.value)).catch((e) => log(String(e)));    li.append(label, input, shown);    ol.append(li);  }  return state.params.length;}// ---- sound ----function pinkNoise(frames) {  const out = new Float32Array(frames);  let b0 = 0, b1 = 0, b2 = 0, b3 = 0, b4 = 0, b5 = 0, b6 = 0;  let seed = 12345;  const rnd = () => ((seed = (seed * 1664525 + 1013904223) >>> 0) / 4294967296) * 2 - 1;  for (let i = 0; i < frames; i++) {    const w = rnd();    b0 = 0.99886 * b0 + w * 0.0555179;    b1 = 0.99332 * b1 + w * 0.0750759;    b2 = 0.969 * b2 + w * 0.153852;    b3 = 0.8665 * b3 + w * 0.3104856;    b4 = 0.55 * b4 + w * 0.5329522;    b5 = -0.7616 * b5 - w * 0.016898;    out[i] = (b0 + b1 + b2 + b3 + b4 + b5 + b6 + w * 0.5362) * 0.06;    b6 = w * 0.115926;  }  return out;}/** The test signal as samples, for offline work: what the source plays, `seconds` long. */function signal(kind, seconds) {  const n = Math.round(seconds * RATE);  if (kind === "file" && state.file) {    const src = state.file.getChannelData(0);    const out = new Float32Array(n);    for (let i = 0; i < n; i++) out[i] = src[i % src.length];    return out;  }  if (kind === "noise") {    const base = pinkNoise(RATE * 4);    const out = new Float32Array(n);    for (let i = 0; i < n; i++) out[i] = base[i % base.length];    return out;  }  if (kind === "clicks") {    const out = new Float32Array(n);    for (let i = 0; i < n; i += 12000) out[i] = 0.9;    return out;  }  const out = new Float32Array(n);  if (kind === "sweep") {    let phase = 0;    for (let i = 0; i < n; i++) {      const t = (i % (RATE * 8)) / (RATE * 8);      phase += (2 * Math.PI * 40 * Math.pow(400, t)) / RATE;      out[i] = 0.2 * Math.sin(phase);    }    return out;  }  for (let i = 0; i < n; i++) out[i] = 0.2 * Math.sin((2 * Math.PI * 220 * i) / RATE);  return out;}function sourceNode(ctx, kind) {  if (kind === "tone") {    const o = ctx.createOscillator();    o.frequency.value = 220;    const g = ctx.createGain();    g.gain.value = 0.2;    o.connect(g);    return { start: () => o.start(), stop: () => o.stop(), out: g };  }  const seconds = kind === "file" && state.file ? state.file.duration : kind === "sweep" ? 8 : 4;  const buffer = kind === "file" && state.file ? state.file : ctx.createBuffer(1, Math.round(seconds * RATE), RATE);  if (!(kind === "file" && state.file)) buffer.copyToChannel(signal(kind, seconds), 0);  const s = ctx.createBufferSource();  s.buffer = buffer;  s.loop = true;  return { start: () => s.start(), stop: () => s.stop(), out: s };}/** The end of every graph this page makes: silent unless the person at the PC ticked "Hear it". */function monitorFor(ctx) {  const m = ctx.createGain();  m.gain.value = state.hearing ? 0.5 : 0;  m.connect(ctx.destination);  state.monitors.add(m);  // Forgotten with its context.  ctx.addEventListener("statechange", () => ctx.state === "closed" && state.monitors.delete(m));  return m;}function setHearing(e) {  // Only a real click turns it on; a script ticking the box (or a scripted run) leaves the page silent.  state.hearing = !!(e && e.isTrusted && $("hear").checked);  $("hear").checked = state.hearing;  for (const m of state.monitors) m.gain.value = state.hearing ? 0.5 : 0;  log(state.hearing ? "hearing it (monitor at -6 dB)" : "silent (monitor at zero)");}async function play(options = {}) {  await stopAudio();  if (!state.inst) throw new Error("open a plugin first");  const kind = options.source || $("source").value;  const hint = options.hint || $("hint").value;  state.playOptions = { hint, latency: options.latency };  const ctx = new AudioContext({ latencyHint: hint, sampleRate: RATE });  state.ctx = ctx;  state.monitor = monitorFor(ctx);  await ctx.audioWorklet.addModule("tap-worklet.js");  const pnode = await state.inst.createNode(ctx, options.latency ? { latency: options.latency } : {});  state.pnode = pnode;  const src = sourceNode(ctx, kind);  const input = ctx.createGain();  src.out.connect(input);  input.connect(pnode.node);  // The dry signal delayed by the node's whole latency, so dry and wet line up when switching.  const delay = ctx.createDelay(4);  delay.delayTime.value = pnode.latency / RATE;  input.connect(delay);  const wet = ctx.createGain();  const dry = ctx.createGain();  pnode.node.connect(wet);  delay.connect(dry);  wet.connect(state.monitor);  dry.connect(state.monitor);  const aIn = ctx.createAnalyser();  const aOut = ctx.createAnalyser();  aIn.fftSize = aOut.fftSize = 4096;  input.connect(aIn);  pnode.node.connect(aOut);  const tap = new AudioWorkletNode(ctx, "jw-tap", { numberOfInputs: 2, numberOfOutputs: 1 });  input.connect(tap, 0, 0);  pnode.node.connect(tap, 0, 1);  const sink = ctx.createGain();  sink.gain.value = 0;  tap.connect(sink).connect(ctx.destination);  state.graph = { src, input, wet, dry, aIn, aOut, tap, kind };  setDry();  src.start();  await ctx.resume();  pnode.on("underrun", (e) => log(`underrun (${e.underruns} so far)`));  pnode.on("lost", () => log("the stream says the plugin host went"));  state.statsTimer = setInterval(updateNumbers, 250);  $("stop").disabled = false;  log(`playing ${kind} through ${state.inst.name} (latencyHint ${hint}: baseLatency ${(ctx.baseLatency * 1000).toFixed(1)} ms, ring ${pnode.ringLatency} frames, total ${pnode.latency} frames = ${(pnode.latencySeconds * 1000).toFixed(1)} ms)`);  return { hint, baseLatencyMs: ctx.baseLatency * 1000, outputLatencyMs: (ctx.outputLatency || 0) * 1000, ringLatency: pnode.ringLatency, pluginLatency: state.inst.latency, latency: pnode.latency, latencyMs: pnode.latencySeconds * 1000 };}function setDry() {  if (!state.graph) return;  const dry = $("dry").checked;  state.graph.wet.gain.value = dry ? 0 : 1;  state.graph.dry.gain.value = dry ? 1 : 0;}async function stopAudio() {  clearInterval(state.statsTimer);  if (state.pnode) await state.pnode.close();  state.pnode = null;  if (state.ctx) await state.ctx.close().catch(() => {});  state.ctx = null;  state.graph = null;  state.monitor = null;  $("stop").disabled = true;}function db(analyser) {  const buf = new Float32Array(analyser.fftSize);  analyser.getFloatTimeDomainData(buf);  let sum = 0;  for (const x of buf) sum += x * x;  const rms = Math.sqrt(sum / buf.length);  return rms > 0 ? 20 * Math.log10(rms) : -Infinity;}function levels() {  if (!state.graph) return null;  return { in: db(state.graph.aIn), out: db(state.graph.aOut) };}function updateNumbers() {  const l = levels();  if (!l) return;  for (const [k, m, v] of [["in", "mIn", "vIn"], ["out", "mOut", "vOut"]]) {    $(m).value = Math.max(-60, l[k]);    $(v).textContent = Number.isFinite(l[k]) ? `${l[k].toFixed(1)} dB` : "silence";  }  const s = state.pnode && state.pnode.stats();  if (!s) return;  const rows = [    ["latency", `${state.pnode.latency} fr (${(state.pnode.latencySeconds * 1000).toFixed(1)} ms)`],    ["ring", `${state.pnode.ringLatency} fr`],    ["plugin", `${s.pluginLatency} fr`],    ["underruns", String(s.underruns)],    ["host late", String(s.late)],    ["slowest block", `${(s.slowestBlockUs / 1000).toFixed(2)} ms`],    ["last block", `${(s.lastBlockUs / 1000).toFixed(2)} ms`],    ["played", `${((s.quanta * 128) / RATE).toFixed(1)} s`],  ];  const dl = $("numbers");  dl.textContent = "";  for (const [k, v] of rows) dl.append(Object.assign(document.createElement("dt"), { textContent: k }), Object.assign(document.createElement("dd"), { textContent: v }));}function stats() {  const s = state.pnode && state.pnode.stats();  return s ? { ...s, latency: state.pnode.latency, ringLatency: state.pnode.ringLatency, seconds: (s.quanta * 128) / RATE, levels: levels() } : null;}/** Records dry and wet together and finds the clicks' delay between them. */function record(frames) {  return new Promise((resolve) => {    state.graph.tap.port.onmessage = (e) => e.data.type === "recorded" && resolve(e.data);    state.graph.tap.port.postMessage({ type: "record", frames });  });}async function measureLatency() {  // Clicks through the same ring latency as what's playing (or the default), measured from the tap's own samples.  if (!state.graph || state.graph.kind !== "clicks") await play({ ...state.playOptions, source: "clicks" });  await new Promise((r) => setTimeout(r, Math.max(500, (state.pnode.latency / RATE) * 1000 + 300)));  const { dry, wet } = await record(RATE * 2);  const lags = [];  for (let i = 1; i < dry.length - 30000; i++) {    if (Math.abs(dry[i]) > 0.5 && Math.abs(dry[i - 1]) < 0.1) {      let best = 0;      let at = -1;      for (let j = i; j < Math.min(wet.length, i + 24000); j++) {        const v = Math.abs(wet[j]);        if (v > best * 1.0001) {          best = v;          at = j;        }      }      if (at >= 0 && best > 1e-4) lags.push(at - i);    }  }  lags.sort((a, b) => a - b);  const measured = lags.length ? lags[Math.floor(lags.length / 2)] : null;  const r = { measured, expected: state.pnode.latency, ring: state.pnode.ringLatency, plugin: state.inst.latency, clicks: lags.length, all: lags };  log(`measured latency ${measured} frames (expected ${r.expected}: ring ${r.ring} + plugin ${r.plugin})`);  return r;}/** * Long runs: the tap checks every sample from now on, the wet signal against the dry one `latency` frames earlier times * `gain` (a plugin that only delays and scales, as JW Test Gain at 0 dB does). report() says how it went. */function verify(gain = 1) {  if (!state.graph) throw new Error("nothing is playing");  state.graph.tap.port.postMessage({ type: "verify", latency: state.pnode.latency, gain });  return { latency: state.pnode.latency, gain };}function verifyReport() {  return new Promise((resolve) => {    state.graph.tap.port.onmessage = (e) => e.data.type === "report" && resolve(e.data);    state.graph.tap.port.postMessage({ type: "report" });  });}// ---- a busy main thread ----function busy(on, ms = Number($("busyMs").value), every = Number($("busyEvery").value)) {  clearInterval(state.busyTimer);  state.busyTimer = 0;  $("busy").checked = !!on;  if (on) {    state.busyTimer = setInterval(() => {      const end = performance.now() + ms;      while (performance.now() < end) {}    }, every);    log(`main thread busy ${ms} ms of every ${every} ms`);  }  return { on: !!on, ms, every };}// ---- editor and state ----async function showEditor(label = $("label").value) {  const open = await state.inst.showEditor(label);  log(`editor ${open ? "shown" : "not shown"}`);  return open;}async function hideEditor() {  return state.inst.hideEditor();}function hash(bytes) {  let h = 0x811c9dc5;  for (const b of bytes) h = Math.imul(h ^ b, 0x01000193) >>> 0;  return h.toString(16).padStart(8, "0");}async function saveState() {  state.saved = await state.inst.getState();  state.savedParams = (await state.inst.parameters()).map((p) => [p.id, p.value]);  $("restore").disabled = false;  const r = { bytes: state.saved.length, hash: hash(state.saved) };  $("stateInfo").textContent = `Saved ${r.bytes} bytes (${r.hash})`;  log(`saved state: ${r.bytes} bytes, ${r.hash}`);  return r;}/** Restores the saved state; compares every parameter with its value when saved. */async function restoreState() {  await state.inst.setState(state.saved);  const now = await state.inst.parameters();  const before = new Map(state.savedParams);  const differ = now.filter((p) => before.has(p.id) && Math.abs(before.get(p.id) - p.value) > 1e-6).map((p) => ({ id: p.id, title: p.title, saved: before.get(p.id), now: p.value }));  const again = await state.inst.getState();  await loadParams();  const r = { parameters: now.length, differ, sameBytes: hash(again) === hash(state.saved), bytes: again.length };  $("stateInfo").textContent = `Restored: ${differ.length} of ${now.length} parameters differ from when saved; state bytes ${r.sameBytes ? "identical" : "differ"}`;  log(`restored state: ${differ.length} parameters differ, bytes ${r.sameBytes ? "identical" : "differ"}`);  return r;}/** Moves parameters away from where they are (a quarter turn each), so a restore has something to undo. */async function scramble(count = 8) {  const ps = (await state.inst.parameters()).filter((p) => !p.readOnly && !p.hidden && !p.bypass && p.automatable).slice(0, count);  for (const p of ps) await state.inst.setParameter(p.id, (p.value + 0.25) % 1);  return ps.map((p) => p.title);}// ---- offline ----const now = () => performance.now();/** 20 s of the source through a fresh offline instance three ways: shared ring, IPC, and an OfflineAudioContext. */async function renderOffline(seconds = 20) {  const kind = $("source").value === "tone" ? "noise" : $("source").value;  const input = signal(kind, seconds);  const state0 = await state.inst.getState();  const out = { plugin: state.inst.name, seconds, source: kind };  const fresh = async () => {    const o = await P.open({ id: state.picked.id, sampleRate: RATE, blockSize: 1024, offline: true, label: "Export" });    await o.setState(state0);    return o;  };  // The page's own render(): shared memory, request and response, no deadline.  let o = await fresh();  let t = now();  const [ringL] = await o.render([input, input]);  out.ring = { ms: Math.round(now() - t), realtime: +((seconds * 1000) / (now() - t)).toFixed(1), rms: rmsDb(ringL) };  await o.close();  // The same through the app's IPC (raw-binary invoke: JSON numbers where the CSP blocks the IPC protocol).  o = await fresh();  t = now();  const [ipcL] = await o.render([input, input], { via: "ipc" });  out.ipc = { ms: Math.round(now() - t), realtime: +((seconds * 1000) / (now() - t)).toFixed(1) };  out.ringVsIpcMaxDiff = maxDiff(ringL, ipcL);  await o.close();  // Inside an OfflineAudioContext graph, as the studio's export renders.  o = await fresh();  const octx = new OfflineAudioContext(2, input.length, RATE);  const buf = octx.createBuffer(1, input.length, RATE);  buf.copyToChannel(input, 0);  const src = octx.createBufferSource();  src.buffer = buf;  const pn = await o.createNode(octx);  src.connect(pn.node).connect(octx.destination);  src.start();  t = now();  const rendered = await octx.startRendering();  out.graph = { ms: Math.round(now() - t), realtime: +((seconds * 1000) / (now() - t)).toFixed(1), underruns: (pn.stats() || {}).underruns || 0 };  out.graphVsRingMaxDiff = maxDiff(ringL, rendered.getChannelData(0));  await o.close();  log(`offline render of ${seconds} s through ${out.plugin}: ring ${out.ring.ms} ms (${out.ring.realtime}x), ipc ${out.ipc.ms} ms (${out.ipc.realtime}x), graph ${out.graph.ms} ms (${out.graph.realtime}x)`);  show(out);  return out;}function rmsDb(x) {  let s = 0;  for (const v of x) s += v * v;  const r = Math.sqrt(s / x.length);  return r > 0 ? +(20 * Math.log10(r)).toFixed(2) : null;}function maxDiff(a, b) {  let m = 0;  for (let i = 0; i < Math.min(a.length, b.length); i++) m = Math.max(m, Math.abs(a[i] - b[i]));  return m;}// ---- measuring the IPC ----const invoke = (cmd, args, options) => window.__TAURI_INTERNALS__.invoke(cmd, args, options);function pct(sorted, p) {  return sorted[Math.min(sorted.length - 1, Math.floor(p * sorted.length))];}/** Round trips of raw bytes through invoke (the page's main thread), by size. */async function benchInvoke(sizes = [1024, 16384, 262144, 1048576], rounds = 40) {  const out = [];  for (const size of sizes) {    const body = new Uint8Array(size);    for (let i = 0; i < size; i++) body[i] = i & 255;    const times = [];    const n = size >= 1048576 ? Math.ceil(rounds / 8) : rounds;    for (let i = 0; i < n; i++) {      const t = now();      const r = await invoke("plugins_bench_echo", body);      times.push(now() - t);      if (i === 0) {        const got = r instanceof ArrayBuffer ? r.byteLength : r.length;        if (got !== size) throw new Error(`echo came back ${got} bytes for ${size}`);      }    }    times.sort((a, b) => a - b);    out.push({ bytes: size, median: +pct(times, 0.5).toFixed(2), p95: +pct(times, 0.95).toFixed(2), mbPerS: +((size * 2) / 1048576 / (pct(times, 0.5) / 1000)).toFixed(1) });  }  return out;}/** A 1 KB block (128 stereo frames) every 2.67 ms for `seconds`, round trip through invoke: the gaps a stream would see. */async function benchInvokeStream(seconds = 3) {  const body = new Uint8Array(1024);  const times = [];  const end = now() + seconds * 1000;  let last = now();  let worstGap = 0;  while (now() < end) {    const t = now();    await invoke("plugins_bench_echo", body);    times.push(now() - t);    worstGap = Math.max(worstGap, now() - last);    last = now();    await new Promise((r) => setTimeout(r, 2));  }  times.sort((a, b) => a - b);  return { blocks: times.length, median: +pct(times, 0.5).toFixed(2), p99: +pct(times, 0.99).toFixed(2), max: +times[times.length - 1].toFixed(2), worstGapMs: +worstGap.toFixed(1) };}/** Rust pushing 1 KB every 3 ms through a Tauri channel: how evenly it arrives. */function benchChannel(seconds = 3, bytes = 1024, every = 3) {  return new Promise((resolve, reject) => {    const count = Math.round((seconds * 1000) / every);    const arrivals = [];    let next = 0;    const early = new Map();    let done = false;    const id = window.__TAURI_INTERNALS__.transformCallback((m) => {      early.set(m.index, m);      while (early.has(next)) {        const e = early.get(next);        early.delete(next);        next++;        // The channel's end marker (Rust dropped it) isn't a message.        if (!e.end) arrivals.push(now());      }      if (arrivals.length >= count && !done) {        done = true;        const gaps = arrivals.slice(1).map((t, i) => t - arrivals[i]).sort((a, b) => a - b);        resolve({ messages: count, bytes, everyMs: every, gapMedian: +pct(gaps, 0.5).toFixed(2), gapP99: +pct(gaps, 0.99).toFixed(2), gapMax: +gaps[gaps.length - 1].toFixed(1) });      }    });    invoke("plugins_bench_channel", { to: `__CHANNEL__:${id}`, bytes, count, every }).catch(reject);    setTimeout(() => done || reject(new Error(`channel: ${arrivals.length} of ${count} arrived`)), seconds * 1000 + 20000);  });}async function bench() {  const r = { ipc: location.search.includes("ipc=fetch") ? "custom protocol (fetch to ipc.localhost)" : "postMessage (as on the site: its CSP blocks ipc.localhost)" };  log(`measuring the IPC: ${r.ipc}`);  r.invoke = await benchInvoke();  r.invokeStreamIdle = await benchInvokeStream();  r.channelIdle = await benchChannel();  busy(true, 180, 200);  try {    r.invokeStreamBusy = await benchInvokeStream();    r.channelBusy = await benchChannel();  } finally {    busy(false);  }  show(r);  log("IPC measured");  return r;}/** The render bursts of an AudioContext at each latency hint: baseLatency, and how many quanta come at once. */async function bursts() {  const out = [];  for (const hint of ["interactive", "balanced", "playback"]) {    const ctx = new AudioContext({ latencyHint: hint, sampleRate: RATE });    await ctx.audioWorklet.addModule("tap-worklet.js");    const tap = new AudioWorkletNode(ctx, "jw-tap", { numberOfInputs: 2, numberOfOutputs: 1 });    const g = ctx.createGain();    g.gain.value = 0;    tap.connect(g).connect(ctx.destination);    await ctx.resume();    await new Promise((r) => setTimeout(r, 400));    const times = await new Promise((resolve) => {      tap.port.onmessage = (e) => e.data.type === "timing" && resolve(e.data.times);      tap.port.postMessage({ type: "timing", quanta: 1500 });    });    // Quanta rendered within a millisecond of each other count as one burst.    const runs = [];    let run = 1;    for (let i = 1; i < times.length; i++) {      if (times[i] - times[i - 1] <= 1) run++;      else {        runs.push(run);        run = 1;      }    }    runs.sort((a, b) => a - b);    out.push({ hint, baseLatencyMs: +(ctx.baseLatency * 1000).toFixed(2), outputLatencyMs: +((ctx.outputLatency || 0) * 1000).toFixed(2), burstMedian: runs[Math.floor(runs.length / 2)], burstMax: runs[runs.length - 1] });    await ctx.close();  }  return out;}// ---- a plugin that crashes ----async function crashTest(kind = "crash") {  const crash = state.plugins.find((p) => p.name === "JW Test Crash");  if (!crash) throw new Error("the test plugin isn't in a scanned folder");  const keep = state.inst;  const lost = new Promise((resolve) => {    const off = P.on("lost", (e) => {      off();      resolve(e);    });  });  const o = await P.open({ id: crash.id, sampleRate: RATE, label: "Insert 9" });  const ctx = new AudioContext({ latencyHint: "interactive", sampleRate: RATE });  const pn = await o.createNode(ctx);  // The page's usual test level (-14 dBFS), never a full-scale tone, and through the shared monitor: silent unless  // "Hear it" is ticked, and silenced again when it's unticked.  const osc = ctx.createOscillator();  const level = ctx.createGain();  level.gain.value = 0.2;  osc.connect(level).connect(pn.node).connect(monitorFor(ctx));  osc.start();  await ctx.resume();  await new Promise((r) => setTimeout(r, 400));  const t = now();  await o.setParameter(kind === "hang" ? 1 : 0, 1);  const e = await Promise.race([lost, new Promise((_, rej) => setTimeout(() => rej(new Error("no loss reported")), 15000))]);  const noticedMs = Math.round(now() - t);  await ctx.close();  // The app restarts the host; a new instance works again.  await new Promise((r) => setTimeout(r, 800));  const again = await P.open({ id: state.picked ? state.picked.id : crash.id, sampleRate: RATE, label: "after" });  const [l] = await again.render([new Float32Array(4800).fill(0.25), new Float32Array(4800).fill(0.25)]);  await again.close();  const r = { kind, reason: e.reason, code: e.code, noticedMs, instances: e.instances, keptInstanceLost: !!(keep && keep.lost), afterRestartRendered: l.length, afterRestartPeak: Math.max(...l.map(Math.abs)) };  log(`${kind}: the app reported ${e.reason}${e.code ? ` (${e.code})` : ""} after ${noticedMs} ms; ${e.instances.length} instances lost; a new instance rendered ${l.length} frames`);  show(r);  if (keep && keep.lost) {    state.inst = null;    enable(false);  }  return r;}// ---- wiring ----$("search").oninput = renderList;$("kind").onchange = renderList;$("enable").onclick = () => P.requestEnable().then((on) => (log(`requestEnable: ${on}`), refresh(), on && loadList()));$("rescan").onclick = () => requestScan().catch((e) => log(`scan: ${e.message}`));$("open").onclick = () => openPicked().catch((e) => log(`open failed: ${e.message}`));$("close").onclick = () => closeInstance();$("play").onclick = () => play().catch((e) => log(`play failed: ${e.message}`));$("stop").onclick = () => stopAudio();$("dry").onchange = setDry;$("hear").onchange = setHearing;$("bypass").onchange = () => state.inst && state.inst.setBypass($("bypass").checked).catch((e) => log(e.message));$("measure").onclick = () => measureLatency().then(show, (e) => log(e.message));$("busy").onchange = () => busy($("busy").checked);$("show").onclick = () => showEditor().catch((e) => log(`editor: ${e.message}`));$("hide").onclick = () => hideEditor().catch((e) => log(e.message));$("save").onclick = () => saveState().catch((e) => log(e.message));$("restore").onclick = () => restoreState().then(show, (e) => log(e.message));$("reset").onclick = () => state.inst.reset().then((l) => log(`reset; latency ${l}`));$("render").onclick = () => renderOffline().catch((e) => log(`render failed: ${e.message}`));$("bench").onclick = () => bench().catch((e) => log(`bench failed: ${e.message}`));$("crash").onclick = () => crashTest().catch((e) => log(`crash test: ${e.message}`));const drop = $("drop");drop.ondragover = (e) => {  e.preventDefault();  drop.toggleAttribute("data-over", true);};drop.ondragleave = () => drop.removeAttribute("data-over");drop.ondrop = async (e) => {  e.preventDefault();  drop.removeAttribute("data-over");  const f = e.dataTransfer.files[0];  if (!f) return;  const ctx = new OfflineAudioContext(1, 1, RATE);  state.file = await ctx.decodeAudioData(await f.arrayBuffer());  $("source").value = "file";  drop.textContent = `${f.name}: ${state.file.duration.toFixed(1)} s, ${state.file.numberOfChannels} channels`;  log(`loaded ${f.name}`);};if (P) {  P.on("status", (s) => {    log(`status: ${s.enabled ? "on" : "off"}${s.scanning ? ", scanning" : ""}, ${s.plugins} plugins`);    refresh();    if (s.enabled && !s.scanning) loadList().catch(() => {});  });  P.on("lost", (e) => log(`the app lost ${e.instances.length} instances (${e.reason})`));  refresh().then((s) => s && s.enabled && loadList().then((n) => log(`${n} plugins listed`)));}window.jwTest = {  refresh,  list: loadList,  requestScan,  status: () => P.status(),  find: (q) => findPlugin(q),  async open(q, options = {}) {    const p = findPlugin(q);    if (!p) throw new Error(`no plugin like ${q}`);    pick(p);    if (options.block) $("block").value = String(options.block);    if (options.label) $("label").value = options.label;    return openPicked();  },  close: closeInstance,  play,  stop: stopAudio,  stats,  levels,  measureLatency,  verify,  verifyReport,  busy,  showEditor,  hideEditor,  saveState,  restoreState,  scramble,  params: () => state.inst.parameters(),  setParam: (id, v) => state.inst.setParameter(id, v),  renderOffline,  bench,  bursts,  crashTest,  setDry: (on) => (($("dry").checked = !!on), setDry()),  instance: () => state.inst && describe(state.inst),  log: () => $("log").textContent,};