Release v0.7.2 - Redesigned interface and persistent account settings
Validate and generate manual release / package (push) Canceled after 0s

This commit is contained in:
Jason committed 2026-12-04 11:08:09 -05:00
1 parent 1d894f59fb
commit 398749210a
35 files changed
+2807 -256

No files matched your search

+145 -61
View File
@@ -1,11 +1,18 @@
import {gmAccessPolicy} from '../audio/gm-host.mjs';
import {validateIceServers} from '../audio/peer-audio.mjs';
import {probeWebSockets,diagnosticMessage} from '../providers/ma/diagnostics.mjs';
const messages={
'saved-connection-unavailable':'This token could not unlock the saved connection. Enter the server address and a valid token to save a new connection.',
'saved-connection-write-failed':'Connected, but Foundry could not save the connection for this account.',
'ice-config-invalid':'Enter a valid existing STUN/TURN URL. TURN also needs a username, credential and UTC expiry within one hour. No network setting was applied.',
'token-required':'Enter a Music Assistant access token for this server.',
'token-invalid':'Remove line breaks from the access token and try again.',
'receiver-name-invalid':'Use at most 120 characters for the receiver name, without line breaks.',
'automation-disabled':'Enable automation before applying a manual playlist override.',
'address-invalid':'Enter the MA server origin, such as https://ma.example.test, without a path or query.',
'ws-upgrade-failed':'The browser could not open the API WebSocket. Run Check browser connection below. If it works from MA’s page only, compare this browser’s local-network permission, private DNS and site restrictions.',
'ws-auth-timeout':'The API socket opened, but authentication did not finish. Check that /ws reaches MA rather than a login portal.',
'ws-auth-denied':'MA rejected the token. Enter a replacement and Authenticate again; the receiver is remembered.',
'ws-auth-denied':'MA rejected the token. Enter a replacement and select Connect again; the receiver is remembered.',
'ws-disconnected':'The API socket closed. Your private inputs remain in this tab. Retry after checking the private route.',
'ws-command-timeout':'MA did not answer a command before its deadline. Catalog reads have a 10-second limit; stream startup has a 60-second limit. Unconfirmed queue writes stop automation for review.',
'ws-command-failed':'MA rejected a command. The account needs music-provider access and permission to control and pair its dedicated web receiver.',
@@ -27,64 +34,141 @@ const messages={
'unavailable':'The operation failed. Your private inputs are retained. Run the browser connection check to separate transport failures from receiver and audio setup.'
};
export const connectionMessage=error=>error?.upstreamCode===2&&['player_queues/play_media','player_queues/play_index'].includes(error.command)?'MA could not find playable media for this playlist (MA error 2). Check its content/provider in MA or choose another playlist. Automation stopped; an unconfirmed queue write is never retried.':messages[error?.code]??messages.unavailable;
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{}}){
const dom=container.ownerDocument,panel=dom.createElement('fieldset'),legend=dom.createElement('legend');legend.textContent='1. Music Assistant';panel.append(legend);
const note=dom.createElement('p');note.textContent='Enter your server and access token. A dedicated campaign receiver is created and paired automatically. The token stays in this GM tab; its receiver identity is remembered privately in this browser.';panel.append(note);
const status=dom.createElement('p');status.setAttribute('role','status');panel.append(status);
const steps=Array.from({length:2},()=>{const step=dom.createElement('div');step.className='adaptive-music-step';panel.append(step);return step;});
const go=index=>steps.forEach((step,i)=>{step.hidden=i!==index;});
const field=(parent,label,type='text')=>{const l=dom.createElement('label');l.textContent=label;const input=dom.createElement('input');input.type=type;input.autocomplete='off';input.spellcheck=false;l.append(input);parent.append(l);return input;};
const button=(parent,label,action)=>{const b=dom.createElement('button');b.type='button';b.textContent=label;b.addEventListener('click',async()=>{b.disabled=true;try{if(!game.user.isGM)throw {code:'denied'};await action();}catch(error){status.textContent=connectionMessage(error);onError(error);}finally{b.disabled=false;show();}});parent.append(b);return b;};
const draft=connection.draftFields??{},address=field(steps[0],'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=draft.maUrl??'';
const token=field(steps[0],'Private GM access token','password');
const advanced=dom.createElement('details'),summary=dom.createElement('summary');summary.textContent='Receiver options';advanced.append(summary);steps[0].append(advanced);
const name=field(advanced,'Dedicated receiver name');name.value=draft.targetName??'Adaptive Music '+(game.world?.title??'campaign');
const iceURL=field(advanced,'Existing ICE server URL (optional)');iceURL.placeholder='stun:stun.example.test:3478';
const iceUsername=field(advanced,'TURN username (if required)'),iceCredential=field(advanced,'Short-lived TURN credential','password'),iceExpiry=field(advanced,'TURN credential expiry (UTC)','datetime-local');
const networkNote=dom.createElement('p');networkNote.textContent='Direct connections use no external ICE service. For remote players, you may supply an existing STUN/TURN service. TURN credentials must expire within one hour; no service is installed.';advanced.append(networkNote);
const logging=dom.createElement('p');logging.textContent='Keep MA raw-frame VERBOSE logging disabled: it can record authentication frames. No server logging settings are changed by this module.';advanced.append(logging);
button(steps[0],'Authenticate',async()=>{
if(!address.value.trim())throw {code:'address-invalid'};status.textContent='Authenticating with Music Assistant…';
const network={};
if(iceURL.value.trim()){
const server={urls:iceURL.value.trim()};
if(/^turns?:/.test(server.urls)){server.username=iceUsername.value.trim();server.credential=iceCredential.value;server.expires=Date.parse(iceExpiry.value+'Z');}
try{validateIceServers([server]);}catch{throw {code:'ice-config-invalid'};}network.listenerNetwork={iceServers:[server]};
}
let result;try{result=await connection.test({maUrl:address.value.trim(),token:token.value,targetName:name.value.trim(),allowCatalogPlayback:true,webSocketAuthLogSafe:true,...network});}
finally{if(connection.status.hasPrivateDraft){token.value='';}}
token.value='';setTarget(result.target,result.targetName);go(1);connect.disabled=false;
status.textContent='Authenticated. Connect this dedicated campaign receiver to pair it and load your playlists.';
});
const target=dom.createElement('select'),label=dom.createElement('label');label.textContent='Dedicated campaign receiver';label.append(target);steps[1].append(label);
const setTarget=(id,name)=>{target.replaceChildren();const option=dom.createElement('option');option.value=id;option.textContent=name;target.append(option);target.value=id;};
const connect=button(steps[1],'Connect audio',async()=>{
status.textContent='Connecting and pairing the dedicated receiver…';
const result=await connection.connect(target.value);await onCatalog();status.textContent=result?.attachedExistingQueue?'Campaign audio reconnected. The existing queue was preserved. Apply the automation setting below when ready to resume scene control.':'Campaign audio connected. Assign ambient and combat playlists below, then enable automation. Players connect automatically.';
});
button(steps[1],'Enable GM audio',()=>connection.resume());
const volume=field(steps[1],'Campaign volume','range');volume.min='0';volume.max='100';volume.value=String(connection.status.volume??100);volume.addEventListener('change',()=>{try{connection.setVolume?.(Number(volume.value));}catch(error){status.textContent=connectionMessage(error);onError(error);}});
button(steps[1],'Refresh playlists',async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';});
button(steps[1],'Back to authentication',()=>go(0));
const diagnostics=dom.createElement('p');diagnostics.setAttribute('role','status');panel.append(diagnostics);
const report=dom.createElement('div');report.setAttribute('aria-live','polite');panel.append(report);let transportResults=[];
button(panel,'Check browser connection (no MA token)',async()=>{
report.replaceChildren();status.textContent='Checking both WebSocket routes from this Foundry page…';
try{transportResults=await probeWebSockets(address.value.trim());}catch(error){throw error?.code?error:{code:'address-invalid'};}
for(const result of transportResults){const line=dom.createElement('p');line.textContent=result.path+': '+diagnosticMessage(result);report.append(line);}
status.textContent='Browser checks complete. No MA token was sent. An open socket still needs authentication, pairing and clock synchronization.';
});
button(panel,'Copy connection diagnostics',async()=>{
const d=connection.status;const text=JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2);
await navigator.clipboard.writeText(text);status.textContent='Diagnostics copied. The report excludes the address, token, receiver identity and catalog titles.';
});
button(panel,'Disconnect Music Assistant',async()=>{await connection.disconnect();token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Disconnected. The token was forgotten; this browser remembers its campaign receiver.';await onCatalog();});
const recovery=dom.createElement('details'),recoveryTitle=dom.createElement('summary');recoveryTitle.textContent='Connection recovery';recovery.append(recoveryTitle);panel.append(recovery);
button(recovery,'Reconnect remembered receiver',async()=>{await connection.reconnect();await onCatalog();status.textContent='Receiver reconnected using retained private inputs. The queue was preserved and automation is paused. Review it, then Apply automation setting when ready.';});
button(recovery,'Forget remembered receiver',async()=>{await (connection.forgetReceiver?.()??connection.disconnect());token.value='';iceCredential.value='';target.replaceChildren();go(0);status.textContent='Local receiver identity forgotten. Reauthenticate to provision a new receiver. Existing MA queues were left untouched.';await onCatalog();});
const show=()=>{const d=connection.status;volume.disabled=d.state!=='connected';if(d.hasPrivateDraft)token.placeholder='Retained in this tab; leave blank to retry';connect.disabled=d.state==='connected'||d.state==='connecting';diagnostics.textContent=`${d.state}. ${d.stage??''} Playlists: ${d.catalog??0}. GM audio: ${d.audioContext??'closed'}. Decoded frames: ${d.decodedFrames??0}. Connected listeners: ${d.peers??0}.`;};
const d=connection.status;if(d.selectedTarget){setTarget(d.selectedTarget,d.selectedName);go(1);}else go(0);show();container.append(panel);
// Refresh while the actual ApplicationV2 window is mounted; no secret-bearing events.
if(globalThis.document===dom&&typeof panel.isConnected==='boolean'){const timer=setInterval(()=>{if(!panel.isConnected){clearInterval(timer);return;}show();},1000);}
return panel;
function failureStage(error) {
if (['ws-upgrade-failed', 'ws-disconnected', 'mixed-content', 'insecure-context'].includes(error?.code)) return 'Connection failed';
if (['ws-auth-denied', 'ws-auth-timeout'].includes(error?.code) || error?.stage === 'API authentication') return 'Authentication failed';
if (['receiver pairing','dedicated receiver verification','dedicated queue verification','Noise handshake'].includes(error?.stage) || error?.code === 'sendspin-sync-failed') return 'Receiver setup failed';
if (error?.stage === 'Sendspin authentication' || error?.code === 'sendspin-auth-failed') return 'Receiver connection failed';
if (error?.stage === 'catalog retrieval' || error?.code === 'catalog-empty') return 'Playlist catalog unavailable';
return 'Setup failed';
}
function iceConfiguration(fields) {
const {url, username, credential, expires} = fields;
if (!url && !username && !credential && !expires) return undefined;
const scheme = url.match(/^(stun|stuns|turn|turns):/i)?.[1].toLowerCase();
const target = scheme && URL.canParse(`https://${url.slice(scheme.length + 1)}`) && new URL(`https://${url.slice(scheme.length + 1)}`);
const turn = scheme?.startsWith('turn');
if (!target || !target.hostname || target.username || target.password || target.pathname !== '/' || target.hash ||
/[\s/]/.test(url) || (target.search && !(turn && /^\?transport=(udp|tcp)$/.test(target.search))) ||
(!turn && (username || credential || expires))) throw {code:'ice-config-invalid'};
const server = {urls:url, ...(turn ? {username, credential, expires:Date.parse(expires + 'Z')} : {})};
try{validateIceServers([server]);}
catch{throw {code:'ice-config-invalid'};}
return {iceServers:[server]};
}
export function mountConnectionWizard({game,container,connection,onCatalog=()=>{},onError=()=>{},next,advancedContent}) {
const dom=container.ownerDocument;
const make=(tag,text,parent=container)=>{
const node=dom.createElement(tag);
if(text)node.textContent=text;
parent.append(node);
return node;
};
const input=(parent,label,type='text')=>{
const wrapper=make('label',label,parent),field=make('input',null,wrapper);
field.type=type;field.autocomplete='off';field.spellcheck=false;
return field;
};
const initial=connection.draftFields??{};
make('h2','Connect Music Assistant');
make('p','Enter your Music Assistant address and access token. Adaptive Music creates or reconnects your campaign receiver and loads your playlists.');
if(initial.savedConnection)make('p','This Foundry account has a saved connection. Enter its access token to unlock the address, or enter a different address to replace it.');
const fields=make('div');fields.className='adaptive-fields';
const address=input(fields,'Music Assistant server address','url');address.placeholder='https://ma.example.test';address.value=initial.maUrl??'';
const token=input(fields,'Private GM access token','password');
const retainError=make('p');retainError.setAttribute('role','alert');retainError.hidden=true;
const actions=make('div');actions.className='adaptive-actions';
const state=make('p');state.className='adaptive-state';
const status=make('p');status.setAttribute('role','status');
const advanced=make('details');make('summary','Advanced',advanced);
const advancedFields=make('div',null,advanced);advancedFields.className='adaptive-fields';
const name=input(advancedFields,'Dedicated receiver name');name.value=initial.targetName??'';name.placeholder='Adaptive Music '+(game.world?.title??'campaign');
const iceURL=input(advancedFields,'ICE server URL');iceURL.placeholder='stun:stun.example.test:3478';
const iceUsername=input(advancedFields,'TURN username'),iceCredential=input(advancedFields,'TURN credential','password');
const iceExpiry=input(advancedFields,'TURN credential expiry (UTC)','datetime-local');
const diagnosticsActions=make('div');diagnosticsActions.className='adaptive-actions';
const report=make('div');report.setAttribute('aria-live','polite');
let transportResults=[],busy=false;
const run=async(action,label)=>{
if(busy||!game.user.isGM)return;
busy=true;retainError.hidden=true;render();
try{await action();}
catch(error){
busy=false;render();error.field?.focus?.();
retainError.textContent=`${typeof label==='function'?label(error):label}. ${connectionMessage(error)}`;retainError.hidden=false;onError(error);
}finally{busy=false;render();}
};
const button=(parent,label,action)=>{
const b=make('button',label,parent);b.type='button';b.addEventListener('click',action);return b;
};
const pageUrl=()=>dom.location?.href??globalThis.location?.href??'https://foundry.invalid';
function validatedAddress(){
try{return gmAccessPolicy(address.value.trim(),pageUrl()).origin;}
catch(error){if(error.code==='denied')throw {code:'address-invalid'};throw error;}
}
function retainedToken(){
const draft=connection.draftFields??{};
try{return draft.retainedToken===true&&new URL(draft.maUrl).origin===validatedAddress();}
catch{return false;}
}
const connect=button(actions,'Connect',()=>run(async()=>{
let maUrl;
const useSaved=!address.value.trim()&&connection.draftFields?.savedConnection;
if(!useSaved)try{maUrl=validatedAddress();}catch(error){throw {code:error.code,field:address};}
if(!token.value.trim()&&(useSaved||!retainedToken()))throw {code:'token-required',field:token};
if(/[\r\n]/.test(token.value))throw {code:'token-invalid',field:token};
const targetName=name.value.trim();
if(targetName.length>120||/[\x00-\x1f\x7f]/.test(name.value)){advanced.open=true;throw {code:'receiver-name-invalid',field:name};}
let listenerNetwork;
try{listenerNetwork=iceConfiguration({url:iceURL.value.trim(),username:iceUsername.value.trim(),credential:iceCredential.value,expires:iceExpiry.value});}
catch{advanced.open=true;throw {code:'ice-config-invalid',field:iceURL};}
status.textContent='Contacting Music Assistant…';
let result;
try{result=await connection.open({maUrl,token:token.value.trim(),...(targetName&&{targetName}),...(listenerNetwork&&{listenerNetwork})});}
finally{if(connection.status.hasPrivateDraft){token.value='';iceCredential.value='';}}
address.value=connection.draftFields?.maUrl??address.value;
await onCatalog();
status.textContent=result?.attachedExistingQueue?'Connected. The existing queue is preserved. Enable automation from Playback when you’re ready.':'Campaign audio connected. Choose playlists for your scene.';
},error=>['address-invalid','token-invalid','token-required','receiver-name-invalid','ice-config-invalid'].includes(error.code)?'Check your settings':failureStage(error)));
connect.className='adaptive-primary';
const nextButton=button(actions,'Choose scene music',()=>next?.());
const disconnect=button(actions,'Disconnect',()=>run(async()=>{
await connection.disconnect();token.value='';iceCredential.value='';status.textContent='Disconnected. The receiver is remembered for next time.';await onCatalog();
},'Disconnect failed'));
button(diagnosticsActions,'Check browser connection',()=>run(async()=>{
report.replaceChildren();transportResults=await probeWebSockets(validatedAddress());
for(const result of transportResults)make('p',`${result.path} — ${diagnosticMessage(result)}`,report);
status.textContent='Browser checks complete.';
},'Browser connection check failed'));
button(diagnosticsActions,'Copy connection diagnostics',()=>run(async()=>{
const d=connection.status;
await navigator.clipboard.writeText(JSON.stringify({state:d.state,stage:d.stage,catalog:d.catalog,audioContext:d.audioContext,decodedFrames:d.decodedFrames,scheduledFrames:d.scheduledFrames,droppedLate:d.droppedLate,droppedAhead:d.droppedAhead,muted:d.muted,pauseMode:d.pauseMode,signalRMS:d.rms,outputRMS:d.outputRMS,listenerConnections:d.peers??0,lastError:d.lastError,listenerDiagnostics:d.listenerDiagnostics,transport:transportResults,secureContext:globalThis.isSecureContext},null,2));
status.textContent='Connection diagnostics copied.';
},'Could not copy diagnostics'));
const advancedActions=make('div',null,advanced);advancedActions.className='adaptive-actions';
const refresh=button(advancedActions,'Refresh playlists',()=>run(async()=>{await connection.refresh();await onCatalog();status.textContent='Playlists refreshed.';},'Catalog refresh failed'));
const forget=button(advancedActions,'Forget saved connection',()=>run(async()=>{
await connection.forgetReceiver();address.value='';token.value='';iceCredential.value='';name.value='';status.textContent='Saved connection removed from this account.';await onCatalog();
},'Could not forget the connection'));
if(advancedContent)advanced.append(advancedContent);
function render(){
const d=connection.status,connected=d.state==='connected';
const label=connected?'Connected':busy?'Working':d.state==='connection-lost'?'Connection lost':'Disconnected';
const summary=connected?`${label} · ${d.catalog??0} catalog choices`:
busy&&d.stage&&d.stage!=='idle'?`${label} · ${d.stage}`:label;
if(state.textContent!==summary)state.textContent=summary;
state.dataset.connected=String(connected);
connect.hidden=connected;connect.disabled=busy;connect.textContent=busy?'Connecting…':'Connect';
disconnect.hidden=!connected;disconnect.disabled=busy;
nextButton.hidden=!connected||!next;nextButton.disabled=busy;refresh.hidden=!connected;
forget.disabled=busy||(!d.hasPrivateDraft&&!connection.draftFields?.savedConnection);
for(const field of [address,token,name,iceURL,iceUsername,iceCredential,iceExpiry])field.disabled=connected||busy;
token.placeholder=retainedToken()?'Retained for this address':'Paste your access token';
}
address.addEventListener('input',render);
render();
return render;
}