2026-12-03 16:11:47 -05:00
import { test } from 'node:test' ;
import assert from 'node:assert/strict' ;
import { MAPlaybackProvider } from '../../gateway/ma-provider.mjs' ;
import { MAReadClient } from '../../gateway/ma-client.mjs' ;
const key = Buffer . alloc ( 32 , 7 );
const track = ( id )=>({ queue_item_id : id , duration : 120 , media_item : { media_type : 'track' , provider_mappings : [{ provider_instance : 'approved' , item_id : id , available : true }]}});
function fixture (){
let items = [ track ( 'a' ), track ( 'a' ), track ( 'b' )], state = { items : 3 , state : 'paused' , repeat_mode : 'all' , shuffle_enabled : false , current_index : 1 , elapsed_time : 17 , elapsed_time_last_updated : Date . now () / 1000 , playback_speed : 1 };
const writes = []; let allowed = true ;
const client = { verifyTarget : async ()=>{}, queueState : async ()=>({... state , current_item : items [ state . current_index ]}), queueItems : async offset => items . slice ( offset , offset + 100 ), mediaURI : i => `approved://track/ ${ i . media_item . provider_mappings [ 0 ]. item_id } ` , resolveCatalog : ref => `approved://playlist/ ${ ref . id } ` ,
async mutate ( action , args , ctx ){ ctx . check (); writes . push ({ action , args }); if ( action === 'stop' ) state . state = 'idle' ; if ( action === 'clear' ){ items = []; state . items = 0 ; state . current_index = null ; state . elapsed_time = 0 ;} if ( action === 'play_media' ){ items = args . media . flatMap ( uri => uri . includes ( '://playlist/' ) ? [ track ( uri . split ( '/' ). at ( - 1 ) + '1' ), track ( uri . split ( '/' ). at ( - 1 ) + '2' )] : [ track ( uri . split ( '/' ). at ( - 1 ))]); state . items = items . length ; state . current_index = 0 ; state . elapsed_time = 0 ; if ( args . option === 'replace' ) state . state = 'playing' ;} if ( action === 'play_index' ){ state . current_index = args . index ; state . elapsed_time = args . seek_position ; state . state = 'playing' ;} if ( action === 'pause' ) state . state = 'paused' ;}};
const provider = new MAPlaybackProvider ({ client , campaign : 'c' , session : 's' , fence : 1 , authority : ()=>{ if ( ! allowed ) throw Object . assign ( Error (),{ code : 'stale' });}, snapshotKey : key });
const ctx = { campaign : 'c' , session : 's' , generation : 1 , check (){}};
return { provider , client , ctx , writes , state , set allowed ( v ){ allowed = v ;}};
}
test ( 'MA snapshots ordered duplicate occurrences, pause and seek then reconstructs exact unshuffled order' , async ()=>{
const f = fixture (), snapshot = await f . provider . snapshot ( f . ctx ); assert . equal ( snapshot . value . items . length , 3 ); assert . equal ( snapshot . value . index , 1 ); assert . equal ( snapshot . value . position , 17 );
await f . provider . restore ( snapshot ,{... f . ctx , generation : 2 }); assert . deepEqual ( f . writes . map ( w => w . action ),[ 'stop' , 'clear' , 'repeat' , 'play_media' , 'play_index' , 'pause' ]); assert . equal ( f . state . current_index , 1 ); assert . equal ( f . state . elapsed_time , 17 ); assert . equal ( f . state . state , 'paused' );
});
test ( 'tampered, foreign/future snapshots and stale authority deny before MA mutations' , async ()=>{
const f = fixture (), snapshot = await f . provider . snapshot ( f . ctx ); const bad = structuredClone ( snapshot ); bad . value . position = 0 ;
await assert . rejects ( f . provider . restore ( bad , f . ctx ),{ code : 'stale' });
await assert . rejects ( f . provider . restore ( snapshot ,{... f . ctx , campaign : 'other' }),{ code : 'stale' });
f . allowed = false ; await assert . rejects ( f . provider . restore ( snapshot ,{... f . ctx , generation : 2 }),{ code : 'stale' }); assert . equal ( f . writes . length , 0 );
});
test ( 'shuffled snapshot fails before interruption rather than promising exact restore' , async ()=>{
const f = fixture (); f . state . shuffle_enabled = true ; await assert . rejects ( f . provider . snapshot ( f . ctx ),{ code : 'unsupported' }); assert . equal ( f . writes . length , 0 );
});
test ( 'prepared media cannot be forged and stale generations cannot issue controls' , async ()=>{
const f = fixture (); await assert . rejects ( f . provider . apply ({ uri : 'approved://playlist/forged' }, f . ctx ),{ code : 'denied' });
await f . provider . control ( 'pause' , null ,{... f . ctx , generation : 4 }); await assert . rejects ( f . provider . control ( 'resume' , null ,{... f . ctx , generation : 3 }),{ code : 'stale' });
});
function wireFixture (){
const commands = []; let grouped = false , expired = false ;
const player = { player_id : 'dev' , name : 'Adaptive Music DEV' , provider : 'sendspin-test' , enabled : true , available : true , group_members : [], group_childs : [], static_group_members : []};
const client = new MAReadClient ({ baseUrl : 'http://localhost' , token : 'fixture' , target : 'dev' , approvedProviders : [ 'approved' ], expectedName : player . name , expectedProvider : player . provider ,
fetchImpl : async ( url , options )=>{ const body = JSON . parse ( options . body ); commands . push ( body ); if ( body . command === 'players/get' ) return Response . json ({... player , active_group : grouped ? 'household' : null }); if ([ 'player_queues/get' , 'player_queues/get_active_queue' ]. includes ( body . command )){ expired = true ; return Response . json ({ queue_id : 'dev' , active : true , available : true , is_dynamic : false , autoplay_enabled : false , dont_stop_the_music_enabled : false , overlay_enabled : false , playback_speed : 1 });} return new Response ( null ,{ status : 200 });}});
return { client , commands , set grouped ( v ){ grouped = v ;}, get expired (){ return expired ;}};
}
test ( 'every wire mutation revalidates exact identity/topology and uses fixed dedicated queue' , async ()=>{
const f = wireFixture (), ctx = { check (){}}; await f . client . mutate ( 'pause' ,{}, ctx ); await f . client . mutate ( 'resume' ,{}, ctx );
assert . equal ( f . commands . filter ( c => c . command === 'players/get' ). length , 2 );
assert . ok ( f . commands . filter ( c => c . command . startsWith ( 'player_queues/' )). every ( c => c . args . queue_id === 'dev' || c . command === 'player_queues/get_active_queue' && c . args . player_id === 'dev' ));
f . grouped = true ; await assert . rejects ( f . client . mutate ( 'stop' ,{}, ctx ),{ code : 'denied' }); assert . equal ( f . commands . filter ( c => c . command === 'player_queues/stop' ). length , 0 );
});
test ( 'queue injection, transfer, arbitrary media URL and authority loss deny without writes' , async ()=>{
const f = wireFixture (); for ( const [ action , args ] of [[ 'transfer' ,{}],[ 'pause' ,{ queue_id : 'household' }],[ 'play_media' ,{ media : [ 'approved://track/unregistered' ], option : 'replace' , shuffle : false }],[ 'play_media' ,{ media : [ 'https://example.test/secret' ], option : 'replace' , shuffle : false }]]) await assert . rejects ( f . client . mutate ( action , args ,{ check (){}}),{ code : 'denied' });
await assert . rejects ( f . client . mutate ( 'pause' ,{}, { check (){ if ( f . expired ) throw Object . assign ( Error (),{ code : 'stale' });}}),{ code : 'stale' });
assert . ok ( ! f . commands . some ( c => c . command === 'player_queues/pause' ));
});
test ( 'catalog IDs survive independent adapter construction and differ across campaigns' , async ()=>{
const make = campaign => new MAReadClient ({ baseUrl : 'http://localhost' , token : 'fixture' , target : 'dev' , approvedProviders : [ 'approved' ], catalogKey : key , campaign ,
fetchImpl : async ( url , opts )=> Response . json ( JSON . parse ( opts . body ). command . includes ( '/radios/' ) ? [] : [{ name : 'music' , media_type : 'playlist' , is_playable : true , provider_mappings : [{ provider_instance : 'approved' , item_id : 'p' , available : true }]}])});
const a = await make ( 'a' ). catalog (), again = await make ( 'a' ). catalog (), b = await make ( 'b' ). catalog (); assert . equal ( a [ 0 ]. id , again [ 0 ]. id ); assert . notEqual ( a [ 0 ]. id , b [ 0 ]. id );
});
test ( 'same-generation duplicate controls and restores issue no duplicate mutations' , async ()=>{
const f = fixture (), snapshot = await f . provider . snapshot ( f . ctx );
await Promise . all ([ f . provider . control ( 'pause' , null , f . ctx ), f . provider . control ( 'pause' , null , f . ctx )]); assert . equal ( f . writes . length , 1 );
const context = {... f . ctx , generation : 2 }; await Promise . all ([ f . provider . restore ( snapshot , context ), f . provider . restore ( snapshot , context )]); assert . equal ( f . writes . length , 7 );
});
test ( 'MA provider with mock MA client composes with controller for nested contexts and rapid supersession' , async ()=>{
const { MusicController } = await import ( '../../src/core/controller.mjs' );
const f = fixture ();
const controller = new MusicController ({ campaign : 'c' , session : 's' , providers : { ma : f . provider }, authority : ()=> true });
const ref = id =>({ provider : 'ma' , id });
const base = { scene : { id : 'scene' , playlist : ref ( 'ambient' )}, combats : []};
const combat = { id : 'combat' , sceneId : 'scene' , active : true , started : true , playlist : ref ( 'combat' ), bosses : []};
await controller . update ( base ); await controller . update ({... base , combats : [ combat ]});
await controller . update ({... base , combats : [{... combat , bosses : [{ id : 'boss' , active : true , priority : 1 , playlist : ref ( 'boss' )}]}]});
await controller . update ({... base , combats : [ combat ], overrides : [{ id : 'manual' , playlist : ref ( 'manual' )}]});
await controller . update ({... base , combats : [ combat ]}); await controller . update ( base );
const before = f . writes . length ; const results = await Promise . allSettled ([ controller . update ({... base , combats : [ combat ]}), controller . update ({... base , overrides : [{ id : 'rapid' , playlist : ref ( 'manual' )}]}), controller . update ( base )]);
assert . equal ( f . writes . length , before ); assert . equal ( results . at ( - 1 ). status , 'fulfilled' ); assert . equal ( controller . current . playlist . id , 'ambient' );
});
test ( 'ambiguous wire mutation failure latches closed instead of retrying or restoring blindly' , async ()=>{
let effects = 0 ; const client = new MAReadClient ({ baseUrl : 'http://localhost' , token : 'fixture' , target : 'dev' , approvedProviders : [ 'approved' ], expectedName : 'Adaptive Music DEV' , expectedProvider : 'sendspin-test' , fetchImpl : async ( url , options )=>{
const { command } = JSON . parse ( options . body );
if ( command === 'players/get' ) return Response . json ({ player_id : 'dev' , name : 'Adaptive Music DEV' , provider : 'sendspin-test' , enabled : true , available : true , group_members : [], group_childs : [], static_group_members : []});
if ( command === 'player_queues/get' || command === 'player_queues/get_active_queue' ) return Response . json ({ queue_id : 'dev' , active : true , available : true , is_dynamic : false , autoplay_enabled : false , dont_stop_the_music_enabled : false , overlay_enabled : false , playback_speed : 1 });
effects ++ ; throw Error ( 'lost response' );
}});
2026-12-04 08:58:47 -05:00
await assert . rejects ( client . mutate ( 'pause' ,{}, { check (){}}),{ code : 'uncertain' , command : 'player_queues/pause' });
await assert . rejects ( client . mutate ( 'pause' ,{}, { check (){}}),{ code : 'uncertain' , command : 'player_queues/pause' }); assert . equal ( effects , 1 );
2026-12-03 16:11:47 -05:00
});
test ( 'listener cannot obtain a playback fence guard or renew a controller lease' , async ()=>{
const { GatewayControl } = await import ( '../../gateway/control.mjs' );
const g = new GatewayControl ({ campaigns : { c : {}}, origin : 'https://example.test' });
const request = { campaign : 'c' , session : 's' , origin : 'https://example.test' , token : g . mint ({ campaign : 'c' , session : 's' , role : 'listener' }), fence : 1 };
assert . throws (()=> g . fenceGuard ( request )( 1 ),{ code : 'denied' }); assert . throws (()=> g . renew ( request ),{ code : 'denied' });
});
test ( 'playlist preparation expands approved ordered tracks before any playback mutation' , async ()=>{
const commands = []; const client = new MAReadClient ({ baseUrl : 'http://localhost' , token : 'fixture' , target : 'dev' , approvedProviders : [ 'approved' ], fetchImpl : async ( url , options )=>{
const { command } = JSON . parse ( options . body ); commands . push ( command );
if ( command === 'music/playlists/library_items' ) return Response . json ([{ name : 'Fixture catalog' , is_playable : true , is_dynamic : false , media_type : 'playlist' , provider_mappings : [{ provider_instance : 'approved' , item_id : 'p' , available : true }]}]);
if ( command === 'music/radios/library_items' ) return Response . json ([]);
if ( command === 'music/playlists/get' ) return Response . json ({ is_dynamic : false });
if ( command === 'music/playlists/playlist_tracks' ) return Response . json ([ track ( 'a' ). media_item , track ( 'a' ). media_item , track ( 'b' ). media_item ]);
throw Error ( 'unexpected command' );
}});
const catalog = await client . catalog (); assert . deepEqual ( await client . prepareMedia ( catalog [ 0 ]),[ 'approved://track/a' , 'approved://track/a' , 'approved://track/b' ]); assert . ok ( ! commands . some ( c => c . startsWith ( 'player_queues/' )));
});
2026-12-04 08:58:47 -05:00
test ( 'ambient snapshot remains restorable after a combat longer than five minutes' , async ()=>{
const f = fixture (), snapshot = await f . provider . snapshot ( f . ctx ), now = Date . now ;
try { Date . now = ()=> now () + 10 * 60 * 1000 ; await f . provider . restore ( snapshot ,{... f . ctx , generation : 2 }); assert . equal ( f . state . state , 'paused' ); assert . equal ( f . state . elapsed_time , 17 );} finally { Date . now = now ;}
});
test ( 'Sendspin pause emulation retains position and restores paused queues without briefly playing' , async ()=>{
const f = fixture (); f . state . state = 'playing' ; f . client . supportsNativePause = ()=> false ;
await f . provider . control ( 'pause' , null , f . ctx ); assert . equal ( f . state . state , 'idle' );
const paused = await f . provider . snapshot ({... f . ctx , generation : 2 }); assert . equal ( paused . value . state , 'paused' ); assert . equal ( paused . value . position , 17 );
await f . provider . control ( 'seek' , 3 ,{... f . ctx , generation : 3 }); const sought = await f . provider . snapshot ({... f . ctx , generation : 4 }); assert . equal ( sought . value . position , 3 );
await f . provider . control ( 'resume' , null ,{... f . ctx , generation : 5 }); assert . equal ( f . state . state , 'playing' ); assert . equal ( f . state . elapsed_time , 3 );
const before = f . writes . length ; await f . provider . restore ( paused ,{... f . ctx , generation : 6 });
assert . deepEqual ( f . writes . slice ( before ). map ( w => w . action ),[ 'stop' , 'clear' , 'repeat' , 'play_media' ]);
const again = await f . provider . snapshot ({... f . ctx , generation : 7 }); assert . equal ( again . value . state , 'paused' ); assert . equal ( again . value . index , 1 ); assert . equal ( again . value . position , 17 );
});