2026-12-05 09:40:14 -05:00
// Exercises module playback in the authorized Foundry development world.
2026-12-04 11:08:09 -05:00
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 ) {
2026-12-05 09:40:14 -05:00
const { state , current_index , elapsed_time , ended , repeat_mode } = frame . result ;
entry . queue = { state , index : current_index , position : elapsed_time , ended , repeat : repeat_mode };
2026-12-04 11:08:09 -05:00
}
});
});
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 ,
2026-12-05 09:40:14 -05:00
underruns : d . underruns , sourceGaps : d . sourceGaps , sourceOverlaps : d . sourceOverlaps , bufferOverruns : d . bufferOverruns ,
2026-12-04 11:08:09 -05:00
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 } ` );
}
2026-12-05 09:40:14 -05:00
const writes = new Set ([ 'stop' , 'clear' , 'play_media' , 'play_index' , 'repeat' , 'pause' , 'resume' , 'seek' , 'next' , 'shuffle' ]. map ( action => 'player_queues/' + action ));
2026-12-04 11:08:09 -05:00
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 };
}
2026-12-05 09:40:14 -05:00
export async function checkNativeSceneSheet ( gm , report ){
const details = await gm . evaluate ( async ()=>{
const scene = game . scenes . active ?? game . scenes . contents [ 0 ];
const app = scene ? . sheet ;
if ( ! app ) return null ;
await app . render ({ force : true });
return { type : app . constructor . name , documentName : app . document ? . documentName , id : app . id , tag : app . element ? . tagName };
});
check ( details ? . id , 'native-scene-sheet-unavailable' );
report . nativeSheet = { type : details . type , documentName : details . documentName , tag : details . tag };
const shell = gm . locator ( `[id=" ${ details . id } "]` );
await shell . waitFor ({ state : 'attached' });
const panel = shell . locator ( '[data-adaptive-music="assignments"]' );
await panel . waitFor ({ state : 'attached' });
report . nativeSheet . tab = await panel . evaluate ( node => node . closest ( '.tab' ) ? . dataset . tab ?? null );
report . nativeSheet . navigationTabs = await shell . locator ( 'nav [data-tab]' ). evaluateAll ( nodes => nodes . map ( node => node . dataset . tab ));
if ( report . nativeSheet . tab &&! await panel . isVisible ()){
await gm . evaluate (({ id , tab })=> foundry . applications . instances . get ( id ) ? . changeTab ( tab , 'sheet' ),{ id : details . id , tab : report . nativeSheet . tab });
}
await panel . waitFor ({ state : 'visible' });
report . nativeSheet . visible = true ;
}
export async function checkFoundryPlayback ({ pages , ma , world , report , long = false }) {
2026-12-04 11:08:09 -05:00
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 );
2026-12-05 09:40:14 -05:00
const continuity = ( reset = false )=> Promise . all ( pages . map ( page => page . evaluate ( async reset =>{
const { contexts , listenerAnalysers } = window . __adaptiveMusicTestAudio ;
const active = [... contexts . filter ( item => item . context . state === 'running' ),
... listenerAnalysers . filter ( item =>[... document . querySelectorAll ( 'audio' )]. some ( audio => audio . srcObject === item . stream ))];
if ( reset ){
await Promise . all ( active . map ( async item =>{
const deadline = Date . now () + 10000 ;
while ( ! item . meterPort && Date . now () < deadline ) await new Promise ( resolve => setTimeout ( resolve , 100 ));
if ( ! item . meterPort ) return ;
item . phaseStarted = null ;
item . meterPort . postMessage ( 'start-phase' );
while ( ! item . phaseStarted && Date . now () < deadline ) await new Promise ( resolve => setTimeout ( resolve , 100 ));
}));
}
const meters = active . map ( item => reset ? item . phaseStarted : item . continuity ). filter ( Boolean );
const rtp = ( await game . modules . get ( 'adaptive-music' ). api . peerStats ()). filter ( item => item . type === 'inbound-rtp' );
return { meters , rtp , timeline : window . __adaptiveMusicTestTimeline , visible :! document . hidden };
}, reset )));
const soak = async duration =>{
const initial = await continuity ( true ), start = performance . now (), checkpoints = [];
check ( initial . every ( client => client . meters . length === 1 ), 'missing-continuity-meter' );
do {
await delay ( Math . min ( 5000 , Math . max ( 1 , duration - ( performance . now () - start ))));
const progress = await continuity ();
checkpoints . push ( progress );
if ( checkpoints . length % 12 === 0 ) console . error ( `Continuity measurement: ${ Math . round (( performance . now () - start ) / 1000 ) } seconds in phase` );
if ( progress . some ( client => client . meters . length !== 1 || client . meters [ 0 ]. trailingZeroRun / client . meters [ 0 ]. sampleRate > 4 )) break ;
} while ( performance . now () - start < duration );
const seconds = ( performance . now () - start ) / 1000 , final = checkpoints . at ( - 1 );
const clients = final . map (( client , index )=>{
const first = initial [ index ]. meters [ 0 ], last = client . meters [ 0 ];
const silenceSeconds = Math . max ( 0 ,... checkpoints . flatMap ( point => point [ index ]. meters
. map ( meter => Math . max ( meter . trailingZeroRun , meter . maxZeroRun ) / meter . sampleRate )));
return {
renderedSeconds : last ? ( last . frames - first . frames ) / last . sampleRate : 0 ,
longestDigitalSilenceSeconds : silenceSeconds ,
shortDropouts : last ? last . shortDropouts - first . shortDropouts : null ,
metersRetained : checkpoints . every ( point => point [ index ]. meters . length === 1 ),
rtpAudio :! index || (( client . rtp [ 0 ] ? . totalSamplesReceived ?? 0 ) > ( initial [ index ]. rtp [ 0 ] ? . totalSamplesReceived ?? 0 )),
};
});
return { seconds , initial , final , clients , passed : seconds >= duration / 1000 && clients . every ( client =>
client . metersRetained && client . rtpAudio && client . renderedSeconds >= seconds * 0.95 && client . longestDigitalSilenceSeconds <= 4 )};
};
2026-12-04 11:08:09 -05:00
const stage = name => {
report . stage = name ;
2026-12-05 09:40:14 -05:00
console . error ( `Development-world playback stage: ${ name } ` );
2026-12-04 11:08:09 -05:00
};
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 );
}
2026-12-05 09:40:14 -05:00
return { enabled , scene , connection : game . settings . get ( moduleId , 'savedConnection' )};
2026-12-04 11:08:09 -05:00
}
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 );
2026-12-05 09:40:14 -05:00
await game . settings . set ( moduleId , 'savedConnection' , data . baseline . connection );
2026-12-04 11:08:09 -05:00
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 } ` ;
2026-12-05 09:40:14 -05:00
report . playerFlagDenials = await Promise . all ( players . map ( player => player . evaluate ( async ({ gmId , moduleId , probeFlag }) => {
2026-12-04 11:08:09 -05:00
try { await game . users . get ( gmId ). setFlag ( moduleId , probeFlag , true ); return false ; }
catch { return true ; }
2026-12-05 09:40:14 -05:00
}, { gmId , moduleId , probeFlag })));
report . playerCannotWriteGMFlag = report . playerFlagDenials . every ( Boolean );
2026-12-04 11:08:09 -05:00
if ( ! report . playerCannotWriteGMFlag ) await gm . evaluate (({ moduleId , probeFlag }) => game . user . unsetFlag ( moduleId , probeFlag ), { moduleId , probeFlag });
2026-12-05 09:40:14 -05:00
check ( report . playerCannotWriteGMFlag , 'player-wrote-gm-user-flag' );
2026-12-04 11:08:09 -05:00
stage ( 'create-test-scene' );
baseline = await fixture ({ action : 'baseline' });
sceneId = await fixture ({ action : 'scene' , fixtureName });
await fixture ({ action : 'activate-scene' , sceneId });
2026-12-05 09:40:14 -05:00
await gm . waitForFunction ( id => game . scenes . active ? . id === id , sceneId ,{ polling : 100 });
2026-12-04 11:08:09 -05:00
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 ();
2026-12-05 09:40:14 -05:00
await setup . getByText ( /^Campaign audio connected\./ ). waitFor ({ timeout : 85000 });
2026-12-04 11:08:09 -05:00
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' );
2026-12-05 09:40:14 -05:00
if ( tabbed ) await setup . getByLabel ( 'Scene' ,{ exact : true }). selectOption ( sceneId );
2026-12-04 11:08:09 -05:00
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 ]);
2026-12-05 09:40:14 -05:00
check ( await ambient . inputValue () === references [ 0 ], 'ambient-selection-lost-before-save' );
2026-12-04 11:08:09 -05:00
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 );
2026-12-05 09:40:14 -05:00
if ( long ){
stage ( 'enable-dedicated-queue-repeat' );
const repeat = wire . commands . length ;
const repeatSelect = setup . getByLabel ( 'Repeat' ,{ exact : true });
report . repeatControl = { visible : await repeatSelect . isVisible (), enabled : await repeatSelect . isEnabled (). catch (()=> false ),
queueRepeat : wire . commands . findLast ( entry => entry . queue ) ? . queue . repeat };
await repeatSelect . selectOption ( 'all' );
await command ( repeat , 'repeat' , args => args . repeat_mode === 'all' && args . queue_id === receiver );
stage ( 'continuous-ambient' );
report . continuity = { ambient : await soak ( 30000 )};
check ( report . continuity . ambient . passed , 'ambient-continuity-failed' );
}
2026-12-04 11:08:09 -05:00
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 ();
2026-12-05 09:40:14 -05:00
if ( long ){
stage ( 'continuous-combat' );
report . continuity . combat = await soak ( 30000 );
check ( report . continuity . combat . passed , 'combat-continuity-failed' );
}
2026-12-04 11:08:09 -05:00
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 ();
2026-12-05 09:40:14 -05:00
if ( long ){
stage ( 'continuous-restored-ambient' );
report . continuity . restoredAmbient = await soak ( 1740000 );
report . continuity . totalMeasuredSeconds = Object . values ( report . continuity ). reduce (( total , phase )=> total + phase . seconds , 0 );
check ( report . continuity . restoredAmbient . passed , 'restored-ambient-continuity-failed' );
}
2026-12-04 11:08:09 -05:00
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 );
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 {
2026-12-05 09:40:14 -05:00
timeline : window . __adaptiveMusicTestTimeline ,
2026-12-04 11:08:09 -05:00
decodedFrames : diagnostic ? Number ( diagnostic . match ( /Decoded frames: (\d+)/ ) ? .[ 1 ] ?? 0 ) : null ,
signaling : window . __adaptiveMusicTestSignaling ,
2026-12-05 09:40:14 -05:00
contexts : contexts . map (({ context , destination , continuity }) => ({ state : context . state , time : context . currentTime , continuity , track : destination . stream . getAudioTracks ()[ 0 ] ? . readyState })),
2026-12-04 11:08:09 -05:00
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 );
}
}
2026-12-05 09:40:14 -05:00
const queueWrites = wire . commands . filter ( entry => writes . has ( entry . command ));
report . onlyDedicatedQueueWritten = Boolean ( receiver ) && queueWrites . length > 0 && queueWrites . every ( entry => entry . args ? . queue_id === receiver );
report . queueWrites = queueWrites . map (({ command , reply , error })=>({ command , reply : reply === true , error }));
}
check ( report . temporaryWorldChangesRestored , 'test-world-cleanup-not-verified' );
check ( report . onlyDedicatedQueueWritten , 'non-dedicated-write' );
}
// Candidate GUI acceptance. Public Foundry document APIs create and activate the
// dedicated fixtures. Assignment, transport, and credential actions use the GUI.
export async function checkFoundryV080Review ({ pages , ma , world , report }) {
const [ gm ,... players ] = pages ;
const namespace = 'adaptive-music' ;
const receiverName = 'Adaptive Music integration ' + randomUUID (). slice ( 0 , 8 );
const names = [ 'Adaptive Music v0.8 — Ambience' , 'Adaptive Music v0.8 — Combat and boss' ];
const setup = gm . locator ( '#adaptive-music-setup' );
const controls = gm . locator ( '#adaptive-music-controls' );
const playlistIndexes = ( process . env . AM_REVIEW_PLAYLIST_INDEXES ?? '0,1,2' ). split ( ',' ). map ( Number );
check ( playlistIndexes . length === 3 && new Set ( playlistIndexes ). size === 3 && playlistIndexes . every ( index => Number . isSafeInteger ( index ) && index >= 0 ),
'three-distinct-review-playlist-indexes-required' );
const token = await loadMAToken ( '.local' );
const wire = observeMA ( gm , ma );
const stage = name =>{ report . stage = name ; console . error ( 'v0.8.0 GUI review stage:' , name );};
let saved , scenes = [], combatId ;
const documentAction = ( action , args = {})=> gm . evaluate ( async ({ action , args , world , namespace })=>{
if ( ! game . ready || game . world . id !== world ||! game . user . isGM ) throw Error ( 'wrong-development-world' );
const module = game . modules . get ( namespace );
if ( action === 'baseline' ){
const state = { scene : game . scenes . active ? . id , enabled : game . settings . get ( namespace , 'enabled' ),
connection : game . settings . get ( namespace , 'savedConnection' ), nativePlaylists : game . playlists . map ( playlist => playlist . id ). sort ()};
if ( state . enabled ){ module . api . stopDevelopment (); await game . settings . set ( namespace , 'enabled' , false );}
return state ;
}
if ( action === 'add-scene' ){
const scene = await CONFIG . Scene . documentClass . create ({ name : args . name , width : 1200 , height : 1000 , navigation : true , tokenVision : false });
return scene . id ;
}
if ( action === 'activate' ) return !! ( await game . scenes . get ( args . scene ) ? . activate ());
if ( action === 'open-scene' ){
const sheet = game . scenes . get ( args . scene ). sheet ;
await sheet . render ({ force : true , position : { left : 120 , top : 100 }});
return sheet . id ;
}
if ( action === 'close-scene' ) return game . scenes . get ( args . scene ). sheet . close ();
if ( action === 'add-combat' ){
const combat = await CONFIG . Combat . documentClass . create ({ scene : args . scene , active : true });
await combat . createEmbeddedDocuments ( 'Combatant' ,[{ name : 'Development boss' , initiative : 12 }]);
return combat . id ;
}
if ( action === 'start-combat' ) return game . combats . get ( args . combat ). startCombat ();
if ( action === 'delete-combat' ) return game . combats . get ( args . combat ) ? . delete ();
if ( action === 'cleanup' ){
module . api . stopDevelopment ();
await module . api . closeGMHost ();
if ( args . combat ) await game . combats . get ( args . combat ) ? . delete ();
if ( args . baseline . scene && game . scenes . active ? . id !== args . baseline . scene ) await game . scenes . get ( args . baseline . scene ) ? . activate ();
if ( game . settings . get ( namespace , 'enabled' ) !== args . baseline . enabled ) await game . settings . set ( namespace , 'enabled' , args . baseline . enabled );
if ( JSON . stringify ( game . settings . get ( namespace , 'savedConnection' )) !== JSON . stringify ( args . baseline . connection )){
await game . settings . set ( namespace , 'savedConnection' , args . baseline . connection );
}
for ( const [ index , id ] of args . scenes . entries ()){
const scene = game . scenes . get ( id );
if ( ! args . keepScenes || game . scenes . some ( other => other . id !== id && other . name === args . names [ index ])) await scene ? . delete ();
else await scene ? . update ({ name : args . names [ index ], navigation : true });
}
return { demonstrationScenes : args . names . filter ( name => game . scenes . some ( scene => scene . name === name )). length ,
activeSceneRestored : ( game . scenes . active ? . id ?? null ) === ( args . baseline . scene ?? null ),
automationRestored : game . settings . get ( namespace , 'enabled' ) === args . baseline . enabled ,
accountEnvelopeRestored : JSON . stringify ( game . settings . get ( namespace , 'savedConnection' )) === JSON . stringify ( args . baseline . connection ),
nativePlaylistInventoryUnchanged : JSON . stringify ( game . playlists . map ( playlist => playlist . id ). sort ()) === JSON . stringify ( args . baseline . nativePlaylists ),
temporaryCombatRemoved :! args . combat ||! game . combats . has ( args . combat )};
}
throw Error ( 'invalid-fixture-action' );
},{ action , args , world : world . id , namespace });
const selectTab = label => setup . getByRole ( 'tab' ,{ name : label , exact : true }). click ();
const connected = ()=> setup . getByText ( /^Connected · \d+ catalog choices$/ ). waitFor ({ timeout : 65000 });
const openSetup = async ()=>{
if ( await setup . isVisible ()) return ;
await openMenu ( gm , 'setup' );
};
const openPlaylists = async ()=>{
const catalog = gm . locator ( '.adaptive-catalog' );
if ( ! await catalog . isVisible ()){
report . sidebarState = await gm . evaluate (()=>{
const directory = ui . playlists ;
ui . sidebar ? . expand ();
directory ? . activate ();
return { directoryAvailable : Boolean ( directory ), expanded : ui . sidebar ? . expanded ,
renderState : directory ? . rendered , elementConnected : directory ? . element ? . isConnected };
});
}
await catalog . waitFor ({ state : 'visible' });
if ( ! await catalog . getByRole ( 'button' ,{ name : 'Music controls' }). isVisible ()) await catalog . locator ( 'summary' ). click ();
return catalog ;
};
const openControls = async ()=>{
if ( await controls . isVisible ()){
await gm . evaluate (()=> foundry . applications . instances . get ( 'adaptive-music-controls' ) ? . bringToFront ());
return ;
}
const list = await openPlaylists ();
await list . getByRole ( 'button' ,{ name : 'Music controls' }). click ();
};
const reload = async ()=>{
await gm . reload ({ waitUntil : 'domcontentloaded' });
await gm . waitForFunction ( id => game . ready && game . world . id === id && game . user . isGM && game . socket ? . connected , world . id ,{ polling : 250 , timeout : 60000 });
};
const command = ( index , action , predicate = ()=> true )=> until (()=> wire . commands . slice ( index ). find ( entry =>
entry . command === 'player_queues/' + action && entry . reply && entry . error === null && predicate ( entry . args )),
Boolean , 'ma-' + action . replaceAll ( '_' , '-' ) + '-not-verified' , 65000 );
const heard = async ()=> Promise . all ( players . map ( async player =>{
const initial = await safeStats ( player );
const end = await until (()=> safeStats ( player ), value => value . bytes > initial . bytes &&
( value . rms > 0.001 || value . energy > initial . energy + 1e-6 ), 'review-listener-audio-missing' , 30000 );
return { rms : end . rms , energyDelta : end . energy - initial . energy };
}));
let receiver ;
try {
stage ( 'setup-menu' );
await gm . bringToFront ();
saved = await documentAction ( 'baseline' );
await openSetup ();
await gm . evaluate (()=>{
window . __adaptiveReviewWarnings = [];
new MutationObserver (()=>{
for ( const notice of document . querySelectorAll ( '#notifications .notification' )){
const message = notice . textContent . trim ();
if ( message . startsWith ( 'Adaptive Music: ' ) &&! window . __adaptiveReviewWarnings . includes ( message )) window . __adaptiveReviewWarnings . push ( message );
}
}). observe ( document . body ,{ childList : true , subtree : true });
});
stage ( 'graphical-connection' );
await setup . getByLabel ( 'Music Assistant server address' ). fill ( ma . origin );
await setup . getByLabel ( 'Private GM access token' ). fill ( token );
await setup . getByLabel ( 'Remember credentials and reconnect on this trusted device' ). check ();
await setup . getByText ( 'Advanced' ,{ exact : true }). click ();
await setup . getByLabel ( 'Dedicated receiver name' ). fill ( receiverName );
await setup . getByRole ( 'button' ,{ name : 'Connect' , exact : true }). click ();
await connected ();
receiver = wire . commands . findLast ( entry => entry . player ? . name === receiverName ) ? . player . id ;
check ( receiver , 'dedicated-review-receiver-not-confirmed' );
report . guiConnection = true ;
await gm . evaluate (()=> foundry . applications . instances . get ( 'adaptive-music-setup' ). close ());
stage ( 'native-scene-assignments-and-playlist-sidebar' );
for ( const name of names ) scenes . push ( await documentAction ( 'add-scene' ,{ name : name + ' ' + receiverName . split ( ' ' ). at ( - 1 )}));
stage ( 'playlist-sidebar' );
const catalog = await openPlaylists ();
await catalog . locator ( 'li' ). first (). waitFor ();
const priorities = [ 'Ambient playlist' , 'Combat playlist' , 'Default boss music' ];
let keys ;
let usedPointerDrag = false ;
for ( const [ index , scene ] of scenes . entries ()){
stage ( 'scene-config-' + ( index + 1 ));
const sheetId = await documentAction ( 'open-scene' ,{ scene });
const shell = gm . locator ( `[id=" ${ sheetId } "]` );
const fieldset = shell . locator ( 'fieldset[data-adaptive-music="assignments"]' );
await fieldset . waitFor ({ state : 'attached' });
const tab = await fieldset . evaluate ( node => node . closest ( '.tab' ) ? . dataset . tab );
if ( tab &&! await fieldset . isVisible ()) await gm . evaluate (({ sheetId , tab })=>
foundry . applications . instances . get ( sheetId ) ? . changeTab ( tab , 'sheet' ),{ sheetId , tab });
stage ( 'scene-config-catalog-' + ( index + 1 ));
const options = await fieldset . getByLabel ( 'Ambient playlist' ). locator ( 'option' ). evaluateAll ( items => items
. filter ( item => item . value . startsWith ( '["ma",' )). map ( item =>({ value : item . value , name : item . textContent . replace ( /^Music Assistant: / , '' )})));
check ( playlistIndexes . every ( index => options [ index ]), 'review-playlist-index-out-of-range' );
keys ??= playlistIndexes . map ( index => options [ index ]);
for ( const [ slot , label ] of priorities . entries ()){
const choice = keys [( index + slot ) % keys . length ], target = fieldset . getByLabel ( label );
if ( index === 0 && slot === 0 ){
stage ( 'scene-config-pointer-drag' );
const entries = catalog . locator ( 'li' );
const row = await entries . evaluateAll (( nodes , value )=> nodes . findIndex ( node => node . dataset . reference === value ), choice . value );
check ( row >= 0 , 'assigned-playlist-missing-from-foundry-sidebar' );
const source = entries . nth ( row ), destination = target . locator ( '..' );
report . dragEndpoints = { sourceVisible : await source . isVisible (), destinationVisible : await destination . isVisible ()};
await source . dragTo ( destination ,{ targetPosition : { x : 15 , y : 8 }});
usedPointerDrag = await target . inputValue () === choice . value ;
check ( usedPointerDrag , 'native-playlist-pointer-drag-failed' );
}
stage ( 'scene-config-select-' + ( index + 1 ) + '-' + ( slot + 1 ));
await target . selectOption ( choice . value );
}
stage ( 'save-scene-config-' + ( index + 1 ));
await fieldset . getByRole ( 'button' ,{ name : 'Save assignments' }). click ();
await fieldset . getByText ( 'Assignments saved.' ,{ exact : true }). waitFor ();
await documentAction ( 'close-scene' ,{ scene });
}
report . nativeAssignments = 2 ;
report . playlistSidebarEntries = await catalog . locator ( 'li' ). count ();
report . pointerDragAssigned = usedPointerDrag ;
check ( usedPointerDrag , 'native-playlist-pointer-drag-failed' );
stage ( 'gameplay-controls-and-scene-automation' );
await documentAction ( 'activate' ,{ scene : scenes [ 0 ]});
const toolbar = gm . locator ( 'button[data-tool="adaptiveMusic"],button[data-control="adaptiveMusic"],button[data-tooltip="Adaptive Music controls"]' ). filter ({ visible : true });
await toolbar . first (). click ();
await controls . waitFor ();
report . toolbarOpened = true ;
await gm . evaluate (()=> foundry . applications . instances . get ( 'adaptive-music-controls' ). close ());
await openControls ();
await controls . waitFor ();
report . sidebarOpened = true ;
const writeIndex = wire . commands . length ;
await controls . getByRole ( 'button' ,{ name : 'Enable automation' }). click ();
const ambientFirst = await command ( writeIndex , 'play_media' , args => args . option === 'replace' );
await Promise . all ( players . map ( async page =>{
await openMenu ( page , 'listen' );
await page . locator ( '#adaptive-music-listener' ). getByRole ( 'button' ,{ name : 'Enable Audio' }). click ();
}));
await controls . getByText ( '2 connected listeners' ,{ exact : true }). waitFor ({ timeout : 40000 });
report . listenerAudio = { firstScene : await heard ()};
const sceneChange = wire . commands . length ;
await documentAction ( 'activate' ,{ scene : scenes [ 1 ]});
const ambientSecond = await command ( sceneChange , 'play_media' , args => args . option === 'replace' );
check ( JSON . stringify ( ambientFirst . args . media ) !== JSON . stringify ( ambientSecond . args . media ), 'scene-ambient-did-not-change' );
report . listenerAudio . secondScene = await heard ();
await delay ( 8500 );
stage ( 'combat-then-boss-then-restoration' );
combatId = await documentAction ( 'add-combat' ,{ scene : scenes [ 1 ]});
const beforeCombat = wire . commands . length ;
await documentAction ( 'start-combat' ,{ combat : combatId });
const combat = await command ( beforeCombat , 'play_media' , args => args . option === 'replace' );
check ( JSON . stringify ( ambientSecond . args . media ) !== JSON . stringify ( combat . args . media ), 'combat-did-not-change-playlist' );
await delay ( 3500 );
stage ( 'boss-override' );
await openSetup ();
await selectTab ( 'Scene Music' );
await setup . getByText ( 'World defaults and boss combatants' ,{ exact : true }). click ();
const boss = setup . getByLabel ( 'Boss combatant' );
const combatantId = await gm . evaluate ( id => game . combats . get ( id ) ? . combatants . contents [ 0 ] ? . id , combatId );
check ( combatantId , 'review-combatant-unavailable' );
await boss . selectOption ( ` ${ combatId } : ${ combatantId } ` );
await setup . getByLabel ( 'Boss override' ,{ exact : true }). check ();
const beforeBoss = wire . commands . length ;
await setup . getByRole ( 'button' ,{ name : 'Save boss override' }). click ();
const bossTrack = await command ( beforeBoss , 'play_media' , args => args . option === 'replace' );
check ( JSON . stringify ( combat . args . media ) !== JSON . stringify ( bossTrack . args . media ), 'boss-did-not-change-playlist' );
report . listenerAudio . boss = await heard ();
stage ( 'restoration-after-boss' );
const beforeRestore = wire . commands . length ;
await documentAction ( 'delete-combat' ,{ combat : combatId }); combatId = null ;
const seek = await command ( beforeRestore , 'play_index' );
const restored = await command ( beforeRestore , 'play_media' , args => args . option === 'add' );
const snapshot = wire . commands . slice ( beforeCombat , wire . commands . indexOf ( combat )). findLast ( entry => entry . queue ? . state === 'playing' ) ? . queue ;
check ( JSON . stringify ( ambientSecond . args . media ) === JSON . stringify ( restored . args . media ) && snapshot && seek . args . index === snapshot . index &&
Math . abs ( seek . args . seek_position - snapshot . position ) <= 2 && seek . args . seek_position > 0 , 'ambient-restore-not-verified' );
report . sceneCombatBossAndRestoration = true ;
report . restoredSeconds = seek . args . seek_position ;
report . listenerAudio . restored = await heard ();
stage ( 'manual-override-and-playback-actions' );
await openControls ();
await controls . getByText ( 'Manual playlist override' ,{ exact : true }). click ();
const beforeManual = wire . commands . length ;
await controls . getByLabel ( 'Override playlist' ). selectOption ( keys [ 0 ]. value );
await controls . getByRole ( 'button' ,{ name : 'Apply override' }). click ();
await command ( beforeManual , 'play_media' , args => args . option === 'replace' );
stage ( 'return-to-scene-music' );
await controls . getByRole ( 'button' ,{ name : 'Return to scene music' }). click ();
await controls . getByText ( 'Automation active' ,{ exact : true }). waitFor ();
stage ( 'pause-and-resume' );
await controls . getByRole ( 'button' ,{ name : 'Pause' , exact : true }). click ();
await controls . getByText ( 'Paused' ,{ exact : true }). waitFor ();
await controls . getByRole ( 'button' ,{ name : 'Resume' , exact : true }). click ();
await controls . getByText ( 'Playing' ,{ exact : true }). waitFor ();
stage ( 'seek-and-skip' );
const seekStart = wire . commands . length ;
await controls . getByLabel ( 'Playback position' ). press ( 'ArrowRight' );
await command ( seekStart , 'seek' );
const skip = wire . commands . length ;
await controls . getByRole ( 'button' ,{ name : 'Skip track' }). click ();
await command ( skip , 'next' );
await controls . getByLabel ( 'Campaign volume' ). press ( 'ArrowLeft' );
stage ( 'background-gm-tab' );
const [ cover ] = await Promise . all ([
gm . waitForEvent ( 'popup' ), gm . evaluate (()=>{ window . open ( 'about:blank' , '_blank' );}),
]);
await cover . bringToFront ();
const time = ()=> gm . evaluate (()=>{
const context = window . __adaptiveMusicTestAudio . contexts . at ( - 1 );
const meter = context ? . continuity ;
const analyser = context ? . analyser , samples = new Float32Array ( analyser ? . fftSize ?? 1 );
analyser ? . getFloatTimeDomainData ( samples );
return { visible :! document . hidden , time : context ? . context . currentTime ?? 0 , frames : meter ? . frames ?? 0 ,
trailingSilence : meter ? meter . trailingZeroRun / meter . sampleRate : null ,
outputRMS : Math . sqrt ( samples . reduce (( sum , sample )=> sum + sample * sample , 0 ) / samples . length )};
});
const [ beforeBackground , beforeListeners ] = await Promise . all ([ time (), Promise . all ( players . map ( safeStats ))]);
await delay ( 12000 );
const [ afterBackground , afterListeners ] = await Promise . all ([ time (), Promise . all ( players . map ( safeStats ))]);
report . backgroundTab = { hidden :! afterBackground . visible , contextSeconds : afterBackground . time - beforeBackground . time ,
outputFrameDelta : afterBackground . frames - beforeBackground . frames , trailingSilenceSeconds : afterBackground . trailingSilence ,
gmOutputRMS : afterBackground . outputRMS ,
listenersWithContinuedAudio : afterListeners . map (( listener , index )=> listener . bytes > beforeListeners [ index ]. bytes &&
( listener . rms > 0.001 || listener . energy > beforeListeners [ index ]. energy + 1e-6 ))};
await cover . close (); await gm . bringToFront ();
await controls . getByRole ( 'button' ,{ name : 'Stop playback' }). click ();
await controls . getByText ( 'Stopped' ,{ exact : true }). waitFor ();
report . manualAndPlayback = true ;
stage ( 'device-reconnect-disconnect-and-forget' );
const beforeReload = wire . commands . length ;
await reload ();
await openSetup (); await connected ();
check ( wire . commands . slice ( beforeReload ). some ( entry => entry . player ? . id === receiver ), 'remembered-receiver-did-not-reconnect' );
check ( ! wire . commands . slice ( beforeReload ). some ( entry => writes . has ( entry . command )), 'auto-reconnect-replaced-dedicated-queue' );
check ( await setup . getByLabel ( 'Private GM access token' ). inputValue () === '' , 'credential-field-leaked' );
report . tokenFreeReload = true ;
await setup . getByRole ( 'button' ,{ name : 'Disconnect' , exact : true }). click ();
await setup . getByText ( /Automatic reconnection is paused/ ). waitFor ();
const disconnected = wire . commands . length ;
await reload ();
await openSetup ();
await setup . getByRole ( 'button' ,{ name : 'Connect' , exact : true }). waitFor ();
await delay ( 1800 );
check ( ! wire . commands . slice ( disconnected ). some ( entry => entry . command === 'auth' ), 'automatic-reconnect-after-disconnect' );
await setup . getByRole ( 'button' ,{ name : 'Connect' , exact : true }). click (); await connected ();
await setup . getByRole ( 'button' ,{ name : 'Forget Credentials' , exact : true }). click ();
await setup . getByText ( 'Credentials removed from this device.' ,{ exact : true }). waitFor ();
const forgotten = wire . commands . length ;
await reload ();
await openSetup ();
await setup . getByRole ( 'button' ,{ name : 'Connect' , exact : true }). waitFor ();
await delay ( 1800 );
check ( ! wire . commands . slice ( forgotten ). some ( entry => entry . command === 'auth' ), 'automatic-reconnect-after-forgetting' );
check ( ! await setup . getByRole ( 'button' ,{ name : 'Forget Credentials' }). isVisible (), 'device-credential-remains-after-forgetting' );
report . disconnectPausesAutoReconnect = true ;
report . forgetPreventsAutoReconnect = true ;
const browserRenderedAudio = report . backgroundTab . outputFrameDelta > 0 && report . backgroundTab . trailingSilenceSeconds <= 4 ||
report . backgroundTab . gmOutputRMS > 0.001 ;
check ( report . backgroundTab . hidden && report . backgroundTab . contextSeconds >= 10 && browserRenderedAudio &&
report . backgroundTab . listenersWithContinuedAudio . every ( Boolean ), 'background-render-not-verified' );
stage ( 'passed' );
} finally {
report . onlyDedicatedQueueWritten = Boolean ( receiver ) && wire . commands . filter ( entry => writes . has ( entry . command )). every ( entry => entry . args ? . queue_id === receiver );
report . queueWrites = wire . commands . filter ( entry => writes . has ( entry . command )). map (({ command , reply , error })=>({ command , reply : reply === true , error }));
if ( report . stage !== 'passed' ) report . connectionVerification = {
apiAuthenticated : wire . commands . some ( entry => entry . authenticated ),
sendspinAuthenticated : wire . sendspinAuthenticated (),
lastCommandError : wire . commands . filter ( entry => entry . reply && entry . error !== null ). map (({ command , error })=>({ command , error })). at ( - 1 ),
recentMACommands : wire . commands . slice ( - 24 ). map (({ command , reply , error })=>({ command , reply : reply === true , error })),
notifications : await gm . evaluate (()=> window . __adaptiveReviewWarnings ?? []). catch (()=>[]),
combatState : combatId ? await gm . evaluate ( id =>{
const combat = game . combats . get ( id );
return { active : combat ? . active , started : combat ? . started , onActiveScene : ( combat ? . scene ? . id ?? combat ? . scene ) === game . scenes . active ? . id ,
hasCombatCue : Boolean ( game . scenes . active ? . getFlag ( 'adaptive-music' , 'music' ) ? . combat )};
}, combatId ). catch (()=> null ) : null ,
};
if ( saved ) report . cleanup = await documentAction ( 'cleanup' ,{ combat : combatId , baseline : saved , scenes , names ,
keepScenes : report . nativeAssignments === 2 && report . sceneCombatBossAndRestoration === true }). catch (()=> null );
2026-12-04 11:08:09 -05:00
}
2026-12-05 09:40:14 -05:00
check ( report . onlyDedicatedQueueWritten , 'non-dedicated-write' );
check ( report . cleanup && Object . entries ( report . cleanup ). every (([ key , value ])=> key === 'demonstrationScenes' ? value === 2 : value ), 'review-cleanup-not-verified' );
2026-12-04 11:08:09 -05:00
}