Files
adaptive-music/scripts/live_foundry_playback.mjs
Jason 398749210a
Validate and generate manual release / package (push) Waiting to run
Release v0.7.2 - Redesigned interface and persistent account settings
2026-12-04 11:08:09 -05:00

459 lines
25 KiB
JavaScript

// Exercises the installed module through the authorized development world.
import {randomUUID} from 'node:crypto';
import {setTimeout as delay} from 'node:timers/promises';
import {loadMAToken} from '../gateway/private-config.mjs';
const moduleId = 'adaptive-music';
const check = (value, code) => { if (!value) throw new Error(code); };
async function until(read, accept, code, timeout = 25000) {
const end = Date.now() + timeout;
do {
const result = await read();
if (accept(result)) return result;
await delay(300);
} while (Date.now() < end);
throw new Error(code);
}
function observeMA(page, ma) {
const commands = [];
let sendspinAuthenticated = false;
const json = event => {
if (typeof event.payload !== 'string') return null;
try { return JSON.parse(event.payload); } catch { return null; }
};
page.on('websocket', socket => {
if (socket.url() === `wss://${ma.host}/sendspin`) {
socket.on('framereceived', event => {
if (json(event)?.type === 'auth_ok') sendspinAuthenticated = true;
});
}
if (socket.url() !== `wss://${ma.host}/ws`) return;
const pending = new Map();
socket.on('framesent', event => {
const frame = json(event);
if (!frame?.message_id || typeof frame.command !== 'string') return;
const entry = {command: frame.command, args: frame.command.startsWith('player_queues/') ? frame.args : null};
commands.push(entry);
pending.set(frame.message_id, entry);
});
socket.on('framereceived', event => {
const frame = json(event);
const entry = pending.get(frame?.message_id);
if (!entry || frame.partial) return;
pending.delete(frame.message_id);
entry.reply = true;
entry.error = frame.error_code ?? null;
if (entry.command === 'auth') entry.authenticated = frame.result?.authenticated === true;
if (entry.command === 'players/get' && frame.result) entry.player = {id:frame.result.player_id,name:frame.result.name};
if (entry.command === 'player_queues/get' && frame.result) {
const {state, current_index, elapsed_time} = frame.result;
entry.queue = {state, index: current_index, position: elapsed_time};
}
});
});
return {commands, sendspinAuthenticated: () => sendspinAuthenticated};
}
function safeStats(page) {
return page.evaluate(async moduleId => {
const stats = await game.modules.get(moduleId).api.peerStats();
const streams = [...document.querySelectorAll('audio')].map(element => element.srcObject).filter(Boolean);
const rms = (window.__adaptiveMusicTestAudio?.listenerAnalysers ?? []).filter(sensor => streams.includes(sensor.stream))
.reduce((max, {analyser}) => {
const samples = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(samples);
return Math.max(max, Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length));
}, 0);
return stats.filter(row => row.type === 'inbound-rtp').reduce((result, row) => ({
rms,
bytes: result.bytes + (row.bytesReceived ?? 0),
energy: result.energy + (row.totalAudioEnergy ?? 0),
samples: result.samples + (row.totalSamplesReceived ?? 0),
}), {rms, bytes: 0, energy: 0, samples: 0});
}, moduleId);
}
async function gmAudioDiagnostics(page, setup) {
await page.evaluate(() => {
Object.defineProperty(navigator.clipboard, 'writeText', {
configurable: true,
value: async text => { window.__adaptiveMusicTestDiagnostics = JSON.parse(text); },
});
});
await setup.getByRole('button', {name: 'Copy connection diagnostics', exact: true}).click({timeout: 3000});
return page.evaluate(() => {
const d = window.__adaptiveMusicTestDiagnostics;
if (!d) return null;
return {
stage: d.stage, state: d.state, audioContext: d.audioContext, decoded: d.decodedFrames,
scheduled: d.scheduledFrames, droppedLate: d.droppedLate, droppedAhead: d.droppedAhead,
signalRMS: d.signalRMS, muted: d.muted, listenerConnections: d.listenerConnections,
volume: Number([...document.querySelectorAll('#adaptive-music-setup input[type="range"]')][0]?.value),
};
});
}
async function openMenu(page, name) {
await page.evaluate(async key => {
const type = game.settings.menus.get(key)?.type;
if (!type) throw Error('missing-installed-module-menu');
const app=new type();
await app.render({force: true});
window.__adaptiveTestWindow=app;
}, `${moduleId}.${name}`);
}
const writes = new Set(['stop', 'clear', 'play_media', 'play_index', 'repeat'].map(action => 'player_queues/' + action));
export async function checkFoundryLayout(page,ma){
await openMenu(page,'setup');
const setup=page.locator('#adaptive-music-setup');
const tabs=setup.getByRole('tab');
check(await tabs.count()===3,'three-foundry-tabs-required');
const resizable=await page.evaluate(()=>window.__adaptiveTestWindow.options.window.resizable);
check(resizable===true,'foundry-window-not-resizable');
const originalWidth=Math.round((await setup.boundingBox()).width);
const layout=[];
for(const width of [originalWidth,380]){
await page.evaluate(width=>window.__adaptiveTestWindow.setPosition({width,height:490}),width);
for(const label of ['Connection','Scene Music','Playback']){
await setup.getByRole('tab',{name:label,exact:true}).click();
const panel=setup.getByRole('tabpanel');
await panel.waitFor({state:'visible'});
const measurements=await panel.evaluate(el=>{
const content=el.closest('.window-content');
const horizontalFit=el.scrollWidth<=el.clientWidth+1&&content.scrollWidth<=content.clientWidth+1;
const nestedScroll=[...content.querySelectorAll('div,section,details,fieldset')].some(node=>['auto','scroll'].includes(getComputedStyle(node).overflowY));
return {horizontalFit,nestedScroll};
});
check(measurements.horizontalFit&&!measurements.nestedScroll,'foundry-layout-overflow');
layout.push({width,tab:label,...measurements});
}
}
await setup.getByRole('tab',{name:'Connection',exact:true}).press('ArrowRight');
check(await setup.getByRole('tabpanel',{name:'Scene Music'}).isVisible(),'tab-keyboard-navigation-failed');
await setup.getByRole('tab',{name:'Connection',exact:true}).click();
const advanced=setup.getByText('Advanced',{exact:true});
check(!await setup.getByLabel('ICE server URL').isVisible(),'advanced-visible-by-default');
await advanced.click();
check(await setup.getByLabel('ICE server URL').isVisible(),'advanced-controls-unreachable');
await advanced.click();
await setup.getByLabel('Music Assistant server address').fill('https://ma.example.test/path');
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByRole('alert').filter({hasText:'Enter the MA server origin'}).waitFor();
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
await setup.getByRole('button',{name:'Check browser connection',exact:true}).click();
await setup.getByText('Browser checks complete.',{exact:true}).waitFor();
const routeDiagnostics=await setup.locator('[aria-live="polite"] p').evaluateAll(lines=>lines.map(line=>({
path:line.textContent.startsWith('/ws')?'/ws':'/sendspin',opened:line.textContent.includes('upgrade succeeded'),
})));
check(routeDiagnostics.length===2,'missing-graphical-route-diagnostics');
return {resizable,layout,keyboardTabs:true,advancedCollapsed:true,invalidAddressRejected:true,missingTokenRejected:true,routeDiagnostics};
}
export async function checkFoundryPlayback({pages, ma, world, report}) {
const [gm, ...players] = pages;
const run = randomUUID().slice(0, 8);
const receiverName = `Adaptive Music integration ${run}`;
const fixtureName = `Adaptive Music verification ${run}`;
const setup = gm.locator('#adaptive-music-setup');
const wire = observeMA(gm, ma);
const stage = name => {
report.stage = name;
console.error(`Installed-world playback stage: ${name}`);
};
let baseline, sceneId, combatId, receiver;
const fixture = data => gm.evaluate(async ({world, moduleId, ...data}) => {
if (!game.ready || game.world.id !== world || !game.user.isGM || !game.socket?.connected) throw Error('wrong-development-world');
if (data.action === 'scene') {
const scene = await CONFIG.Scene.documentClass.create({name: data.fixtureName, width: 1200, height: 1000, navigation: false, tokenVision: false});
return scene.id;
}
if (data.action === 'combat') {
const combat = await CONFIG.Combat.documentClass.create({scene: data.sceneId, active: true});
await combat.createEmbeddedDocuments('Combatant', [{name: data.fixtureName, initiative: 12}]);
return combat.id;
}
if (data.action === 'start-combat') {
const combat = game.combats.get(data.combatId);
await combat.startCombat();
return Boolean(combat.started && combat.active);
}
if (data.action === 'delete-combat') return game.combats.get(data.combatId)?.delete().then(() => true);
if (data.action === 'activate-scene') return game.scenes.get(data.sceneId)?.activate().then(() => true);
if (data.action === 'baseline') {
const enabled = game.settings.get(moduleId, 'enabled');
const scene = game.scenes.active?.id ?? null;
if (enabled) {
game.modules.get(moduleId).api.stopDevelopment();
await game.settings.set(moduleId, 'enabled', false);
}
return {enabled, scene};
}
if (data.action === 'cleanup') {
const api = game.modules.get(moduleId).api;
api.stopDevelopment();
await api.closeGMHost();
if (data.combatId) await game.combats.get(data.combatId)?.delete();
if (data.baseline.scene && game.scenes.active?.id !== data.baseline.scene) await game.scenes.get(data.baseline.scene)?.activate();
if (data.sceneId) await game.scenes.get(data.sceneId)?.delete();
if (game.settings.get(moduleId, 'enabled') !== data.baseline.enabled) await game.settings.set(moduleId, 'enabled', data.baseline.enabled);
return (!data.sceneId || !game.scenes.has(data.sceneId)) && (!data.combatId || !game.combats.has(data.combatId)) &&
game.settings.get(moduleId, 'enabled') === data.baseline.enabled;
}
throw Error('unknown-fixture-operation');
}, {world: world.id, moduleId, ...data});
const command = (from, name, predicate = () => true) => until(
() => wire.commands.slice(from).find(entry => entry.command === `player_queues/${name}` && entry.reply && predicate(entry.args)),
Boolean, `ma-${name.replaceAll('_', '-')}-not-observed`, 70000).then(entry => {
if (entry.error !== null) report.upstreamError = {command: entry.command, code: entry.error};
check(entry.error === null, 'ma-queue-command-failed');
return entry;
});
const audio = async () => {
const before = await Promise.all(players.map(safeStats));
try {
return await Promise.all(players.map(async (page, index) => {
const after = await until(() => safeStats(page), value => value.bytes > before[index].bytes &&
(value.energy - before[index].energy > 1e-6 || value.rms > 0.001),
'listener-audio-energy-did-not-increase', 30000);
return {bytesIncreased: true, energyIncrease: after.energy - before[index].energy, playbackRMS: after.rms,
samplesIncreased: after.samples > before[index].samples};
}));
} catch (error) {
report.listenerStatsAtFailure = await Promise.all(players.map(page => safeStats(page).catch(() => null)));
throw error;
}
};
try {
stage('world-readiness');
await gm.waitForFunction(({moduleId, count}) => game.modules.get(moduleId)?.api &&
[...game.users].filter(user => user.active && !user.isGM).length >= count &&
[...game.users].filter(user => user.active && user.isGM).length === 1, {moduleId, count: players.length});
report.publicKeys = await Promise.all(pages.map(page => page.waitForFunction(moduleId => Boolean(game.user.getFlag(moduleId, 'audioPublicKey')?.key), moduleId, {timeout: 8000}).then(() => true, () => false)));
await Promise.all(pages.map(page => page.evaluate(() => {
const tally = {invitationsForMe: 0, invitationEvents: 0, offers: 0, answers: 0, sentInvitations: 0, sentSignals: 0};
window.__adaptiveMusicTestSignaling = tally;
game.socket.on('module.adaptive-music', frame => {
if (frame?.type === 'audio-invite-v1') {
tally.invitationEvents++;
if (frame.to === game.user.id) tally.invitationsForMe++;
}
if (frame?.v === 1 && frame.from === 'listener') tally.offers++;
if (frame?.v === 1 && frame.from === 'gm') tally.answers++;
});
game.socket.onAnyOutgoing?.((event, frame) => {
if (event !== 'module.adaptive-music') return;
if (frame?.type === 'audio-invite-v1') tally.sentInvitations++;
if (frame?.v === 1 && typeof frame.cipher === 'string') tally.sentSignals++;
});
})));
stage('user-document-permissions');
const gmId = await gm.evaluate(() => game.user.id);
const probeFlag = `integrationProbe${run}`;
report.playerCannotWriteGMFlag = await players[0].evaluate(async ({gmId, moduleId, probeFlag}) => {
try { await game.users.get(gmId).setFlag(moduleId, probeFlag, true); return false; }
catch { return true; }
}, {gmId, moduleId, probeFlag});
if (!report.playerCannotWriteGMFlag) await gm.evaluate(({moduleId, probeFlag}) => game.user.unsetFlag(moduleId, probeFlag), {moduleId, probeFlag});
stage('create-test-scene');
baseline = await fixture({action: 'baseline'});
sceneId = await fixture({action: 'scene', fixtureName});
await fixture({action: 'activate-scene', sceneId});
await openMenu(gm, 'setup');
await gm.evaluate(()=>{
window.__adaptiveTestNotifications=[];
const observer=new MutationObserver(()=>{
for(const node of document.querySelectorAll('#notifications .notification')){
const text=node.textContent.trim();
if(text.startsWith('Adaptive Music: ')&&!window.__adaptiveTestNotifications.includes(text))window.__adaptiveTestNotifications.push(text);
}
});
observer.observe(document.body,{childList:true,subtree:true});
});
stage('ma-authentication');
const tabbed=await setup.getByRole('tab',{name:'Connection',exact:true}).count()>0;
await setup.getByLabel('Music Assistant server address').fill(ma.origin);
if(tabbed){
const before=wire.commands.length;
report.advancedInitiallyCollapsed=!await setup.getByLabel('ICE server URL').isVisible();
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByRole('alert').filter({hasText:'Enter a Music Assistant access token'}).waitFor();
report.formRejectedMissingTokenWithoutNetwork=wire.commands.length===before;
check(report.formRejectedMissingTokenWithoutNetwork&&report.advancedInitiallyCollapsed,'connection-form-validation-failed');
await setup.getByText('Advanced',{exact:true}).click();
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
await setup.getByText('Advanced',{exact:true}).click();
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
await setup.getByRole('button',{name:'Connect',exact:true}).click();
await setup.getByText(/^Campaign audio connected\./).waitFor({timeout:50000});
receiver=wire.commands.findLast(entry=>entry.player?.name===receiverName)?.player.id;
check(receiver,'receiver-identity-not-verified');
report.oneClickConnection=true;
await setup.getByRole('button',{name:'Choose scene music'}).click();
}else{
await setup.getByLabel('Private GM access token').fill(await loadMAToken('.local'));
await setup.getByText('Receiver options',{exact:true}).click();
await setup.getByLabel('Dedicated receiver name').fill(receiverName);
await setup.getByRole('button',{name:'Authenticate',exact:true}).click();
const selector=setup.getByLabel('Dedicated campaign receiver');
await selector.locator('option').filter({hasText:receiverName}).waitFor({state:'attached',timeout:25000});
receiver=await selector.inputValue();
await setup.getByRole('button',{name:'Connect audio',exact:true}).click();
}
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
check(receiver && report.maAPIAuthenticated, 'receiver-identity-not-verified');
stage('dedicated-sendspin-connection');
if(!tabbed)await setup.getByText(/^Campaign audio connected\./).waitFor({timeout: 50000});
report.sendspinAuthenticated = wire.sendspinAuthenticated();
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
check(report.sendspinAuthenticated && report.accountPairingPassed, 'sendspin-pairing-not-observed');
stage('scene-assignments');
const assignments = setup.locator('fieldset[data-adaptive-music="assignments"]').filter({has: gm.locator('legend', {hasText: /^Scene music$/})});
const ambient = assignments.getByLabel('Ambient playlist');
const references = await ambient.locator('option').evaluateAll(options => options.map(option => option.value).filter(value => value.startsWith('["ma",')));
report.catalogChoices = references.length;
check(references.length >= 2, 'insufficient-ma-catalog-choices');
await ambient.selectOption(references[0]);
await assignments.getByLabel('Combat playlist').selectOption(references[1]);
if(tabbed)await assignments.getByLabel('Default boss music').selectOption(references[1]);
await assignments.getByRole('button', {name: 'Save assignments', exact: true}).click();
await assignments.getByText('Assignments saved.', {exact: true}).waitFor();
report.sceneAssignmentVerified=await gm.evaluate(({sceneId,ambient})=>{
const scene=game.scenes.get(sceneId);
return scene?.active===true&&JSON.stringify(['ma',scene.getFlag('adaptive-music','music')?.ambient?.id])===ambient;
},{sceneId,ambient:references[0]});
check(report.sceneAssignmentVerified,'assignment-not-saved-to-active-scene');
stage('activate-listener-audio');
await Promise.all(players.map(async page => {
await openMenu(page, 'listen');
await page.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
}));
stage('ambient');
const start = wire.commands.length;
if(tabbed){
await setup.getByRole('button',{name:'Go to Playback'}).click();
await setup.getByRole('button',{name:'Enable automation'}).click();
await setup.getByText('Automation active',{exact:true}).waitFor({timeout:10000});
}else{
await setup.getByLabel('Enable music automation').check();
await setup.getByRole('button',{name:'Apply automation setting',exact:true}).click();
}
const ambientPlay = await command(start, 'play_media', args => args.option === 'replace');
report.ambient = await audio();
await delay(6500);
stage('actual-combat');
combatId = await fixture({action: 'combat', sceneId, fixtureName});
const interrupt = wire.commands.length;
check(await fixture({action: 'start-combat', combatId}), 'foundry-combat-did-not-start');
const combatPlay = await command(interrupt, 'play_media', args => args.option === 'replace');
check(JSON.stringify(combatPlay.args.media) !== JSON.stringify(ambientPlay.args.media), 'combat-playlist-was-not-distinct');
await delay(4500);
report.combat = await audio();
stage('ambient-restoration');
const restore = wire.commands.length;
check(await fixture({action: 'delete-combat', combatId}), 'foundry-combat-delete-not-observed');
const restored = await command(restore, 'play_media', args => args.option === 'add');
const seek = await command(restore, 'play_index');
report.ambientOrderRestored = JSON.stringify(restored.args.media) === JSON.stringify(ambientPlay.args.media);
const snapshot = wire.commands.slice(interrupt, wire.commands.indexOf(combatPlay)).findLast(entry => entry.queue?.state === 'playing')?.queue;
report.ambientRestoreOffset = {index: seek.args.index, seconds: seek.args.seek_position};
report.ambientIndexAndOffsetRestored = Boolean(snapshot && seek.args.seek_position > 0 &&
snapshot.index === seek.args.index && Math.abs(snapshot.position - seek.args.seek_position) <= 2);
await delay(4500);
report.restoredAmbient = await audio();
report.onlyDedicatedQueueWritten = wire.commands.filter(entry => writes.has(entry.command)).every(entry => entry.args?.queue_id === receiver);
check(report.ambientOrderRestored && report.ambientIndexAndOffsetRestored && report.onlyDedicatedQueueWritten, 'queue-restore-or-ownership-mismatch');
stage('listener-stop-and-resume');
const listener = players[0].locator('#adaptive-music-listener');
await listener.getByRole('button', {name: 'Stop Audio', exact: true}).click();
await until(() => safeStats(players[0]), stats => stats.bytes === 0, 'listener-stop-did-not-close-peer');
await listener.getByRole('button', {name: 'Enable Audio', exact: true}).click();
report.afterListenerResume = await audio();
stage('listener-reload');
const reloaded = players[1];
await reloaded.reload({waitUntil: 'domcontentloaded', timeout: 30000});
await reloaded.waitForFunction(id => game.ready && game.world.id === id && !game.user.isGM && game.socket?.connected,
world.id, {polling: 250, timeout: 45000});
await openMenu(reloaded, 'listen');
await reloaded.locator('#adaptive-music-listener').getByRole('button', {name: 'Enable Audio', exact: true}).click();
report.afterListenerReload = await audio();
if(tabbed){
stage('playback-tab-controls');
await setup.getByText('2 connected listeners',{exact:true}).waitFor();
await setup.locator('.adaptive-now h3').filter({hasText:/^(?!Nothing playing).+/}).waitFor();
const slider=setup.getByLabel('Campaign volume');
await slider.press('ArrowLeft');
await setup.getByRole('button',{name:'Pause',exact:true}).click();
await setup.getByRole('button',{name:'Resume',exact:true}).click();
report.afterPlaybackResume=await audio();
await setup.getByRole('button',{name:'Stop playback',exact:true}).click();
await setup.getByText('Stopped',{exact:true}).waitFor();
report.playbackTabControls=true;
}
stage('passed');
} finally {
report.maAPIAuthenticated = wire.commands.some(entry => entry.authenticated);
report.sendspinAuthenticated = wire.sendspinAuthenticated();
report.accountPairingPassed = wire.commands.some(entry => entry.command === 'sendspin/pair_web_player' && entry.reply && entry.error === null);
report.queueWrites = wire.commands.filter(entry => writes.has(entry.command)).map(({command, reply, error}) => ({command, reply: reply === true, error}));
if(report.stage!=='passed')report.playbackFailureDetails={
notifications:await gm.evaluate(()=>window.__adaptiveTestNotifications??[]).catch(()=>[]),
recentMACommands:wire.commands.slice(-20).map(({command,reply,error})=>({command,reply:reply===true,error})),
};
if (receiver) {
if(await setup.getByRole('tab',{name:'Connection',exact:true}).count())await setup.getByRole('tab',{name:'Connection',exact:true}).click().catch(()=>{});
report.gmAudioDiagnostics = await gmAudioDiagnostics(gm, setup).catch(() => null);
}
report.browserAudio = await Promise.all(pages.map(page => page.evaluate(async () => {
const diagnostic = [...document.querySelectorAll('#adaptive-music-setup [role="status"]')].map(node => node.textContent).find(text => text.includes('Decoded frames:'));
const {contexts = [], analysers = []} = window.__adaptiveMusicTestAudio ?? {};
return {
decodedFrames: diagnostic ? Number(diagnostic.match(/Decoded frames: (\d+)/)?.[1] ?? 0) : null,
signaling: window.__adaptiveMusicTestSignaling,
contexts: contexts.map(({context, destination}) => ({state: context.state, time: context.currentTime, track: destination.stream.getAudioTracks()[0]?.readyState})),
analyserRMS: analysers.map(analyser => {
const samples = new Float32Array(analyser.fftSize);
analyser.getFloatTimeDomainData(samples);
return Math.sqrt(samples.reduce((sum, sample) => sum + sample ** 2, 0) / samples.length);
}),
browsers: await Promise.all((window.__adaptiveMusicTestPeers ?? []).map(async peer => {
const stats = peer.connectionState === 'connected' ? [...(await peer.getStats()).values()] : [];
return {connection: peer.connectionState, ice: peer.iceConnectionState, signaling: peer.signalingState,
outgoingEnergy: stats.find(row => row.type === 'media-source' && row.kind === 'audio')?.totalAudioEnergy};
})),
};
}).catch(() => null)));
if (!report.upstreamError) {
const lastError = wire.commands.findLast(entry => entry.reply && entry.error !== null);
if (lastError) report.upstreamError = {command: lastError.command, code: lastError.error};
}
if (baseline) {
try {
if (report.stage === 'passed') await gm.evaluate(moduleId => game.modules.get(moduleId).api.setOverrides([{id: 'integration-cleanup', playlist: null}]), moduleId);
} finally {
report.temporaryWorldChangesRestored = await fixture({action: 'cleanup', sceneId, combatId, baseline}).catch(() => false);
}
}
}
}