import { test } from 'node:test'; import assert from 'node:assert/strict'; import { MusicController, MusicError, candidates } from '../../src/core/controller.mjs'; const ref = id => ({ provider: 'native', id }); const scene = (id = 'A') => ({ id, playlist: ref(id) }); const combat = (bosses = []) => ({ id: 'fight', active: true, started: true, sceneId: 'A', playlist: ref('combat'), bosses }); const boss = (id = 'boss', priority = 1) => ({ id, priority, active: true, playlist: ref(id) }); function fixture(options = {}) { const log = []; let playback = { items: ['duplicate','duplicate','third'], index: 1, offset: 42, paused: true }; const provider = { async resolve(r,c) { log.push(['resolve',r.id]); return r; }, async snapshot(c) { return { ...structuredClone(playback), campaign: c.campaign, session: c.session, generation: c.generation }; }, async stopOwned(c) { c.check(); log.push(['stop']); }, async apply(r,c) { c.check(); log.push(['apply',r.id]); playback = { items: [r.id], index: 0, offset: 0, paused: false }; }, async restore(s,c) { c.check(); log.push(['restore',s]); playback = structuredClone(s); } }; const controller = new MusicController({ campaign: 'campaign', session: 'session', providers: { native: provider, other: provider }, authority: () => true, ...options }); return { controller, provider, log, get playback() { return playback; }, set playback(p) { playback=p; } }; } test('policy precedence and explicit silence', () => { assert.equal(candidates({scene:scene(),combats:[combat([boss()])],overrides:[{id:'silence',playlist:null}]})[0].playlist,null); assert.equal(candidates({scene:scene(),combats:[combat([boss()])]})[0].playlist.id,'boss'); assert.equal(candidates({scene:scene(),combats:[combat()]})[0].playlist.id,'combat'); assert.equal(candidates({scene:scene()})[0].playlist.id,'A'); assert.equal(candidates({defaultPlaylist:ref('world')})[0].playlist.id,'world'); assert.equal(candidates({})[0].playlist,null); }); test('inactive, unstarted and other scene combats ignored; boss ties stable', () => { for (const change of [{active:false},{started:false},{sceneId:'B'}]) { assert.equal(candidates({scene:scene(),combats:[{...combat([boss()]),...change}]})[0].playlist.id,'A'); } assert.equal(candidates({scene:scene(),combats:[combat([boss('z',3),boss('a',3),boss('b',2)])]})[0].playlist.id,'a'); }); test('scene -> combat -> boss -> nested manual -> unwind restores offsets, duplicates and pause', async () => { const f=fixture(), c=f.controller; const base={scene:scene()}, fight={...base,combats:[combat()]}, big={...base,combats:[combat([boss()])]}; await c.update(base); f.playback={items:['same','same','end'],index:1,offset:42,paused:true}; await c.update(fight); await c.update(big); await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]}); await c.update({...big,overrides:[{id:'one',playlist:ref('one')},{id:'two',playlist:null}]}); assert.equal((await c.update({...big,overrides:[{id:'one',playlist:ref('one')}]})).restored,true); assert.equal((await c.update(big)).restored,true); assert.equal((await c.update(fight)).restored,true); assert.equal((await c.update(base)).restored,true); assert.deepEqual(f.playback.items,['same','same','end']); assert.equal(f.playback.index,1); assert.equal(f.playback.offset,42); assert.equal(f.playback.paused,true); }); test('scene change during manual never resurrects previous scene', async () => { const f=fixture(); const overrides=[{id:'manual',playlist:ref('manual')}]; await f.controller.update({scene:scene()}); await f.controller.update({scene:scene(),overrides}); await f.controller.update({scene:scene('B'),overrides}); await f.controller.update({scene:scene('B')}); assert.equal(f.playback.items[0],'B'); assert.equal(f.controller.frames.length,0); }); test('boss removed during manual and deleted combat cannot return', async () => { const f=fixture(); const base={scene:scene()}, big={...base,combats:[combat([boss()])]}; await f.controller.update(base); await f.controller.update(big); await f.controller.update({...big,overrides:[{id:'m',playlist:ref('m')}]}); await f.controller.update({...base,overrides:[{id:'m',playlist:ref('m')}]}); await f.controller.update(base); assert.equal(f.playback.items[0],'A'); assert.equal(f.controller.frames.length,0); }); test('duplicate intent causes zero provider mutations', async () => { const f=fixture(); await f.controller.update({scene:scene()}); const before=f.log.length; assert.equal((await f.controller.update({scene:scene()})).unchanged,true); assert.equal(f.log.length,before); }); test('prepare failure leaves current playback intact', async () => { const f=fixture(); await f.controller.update({scene:scene()}); f.provider.resolve=async()=>{throw new MusicError('unavailable');}; await assert.rejects(f.controller.update({scene:scene('B')}),{code:'unavailable'}); assert.equal(f.playback.items[0],'A'); assert.equal(f.log.filter(x=>x[0]==='stop').length,0); }); test('partial apply failure restores outgoing playback', async () => { const f=fixture(); await f.controller.update({scene:scene()}); f.provider.apply=async()=>{throw new MusicError('unavailable');}; await assert.rejects(f.controller.update({scene:scene('B')})); assert.equal(f.playback.items[0],'A'); }); test('obsolete async resolve is rejected before stop/apply', async () => { const f=fixture(); let resume, entered; const ready=new Promise(r=>entered=r), normal=f.provider.resolve; f.provider.resolve=async(r,c)=>{if(r.id==='A'){entered();await new Promise(r=>resume=r);} return normal(r,c);}; const first=f.controller.update({scene:scene()}); await ready; const second=f.controller.update({scene:scene('B')}); resume(); await assert.rejects(first,{code:'stale'}); await second; assert.deepEqual(f.log.filter(x=>x[0]==='apply'),[['apply','B']]); }); test('lease loss during stop prevents apply and stale rollback', async () => { let active=true; const f=fixture({authority:()=>active}); await f.controller.update({scene:scene()}); f.provider.stopOwned=async()=>{active=false;}; await assert.rejects(f.controller.update({scene:scene(),combats:[combat()]}),{code:'stale'}); assert.equal(f.log.filter(x=>x[0]==='restore').length,0); }); test('provider switch and bounded nested stack', async () => { const f=fixture({maxFrames:2}); await f.controller.update({scene:scene()}); await f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'other'}}}); assert.equal(f.playback.items[0],'other'); for(let i=0;i<5;i++) await f.controller.update({scene:scene(),overrides:Array.from({length:i+1},(_,j)=>({id:String(j),playlist:ref(String(j))}))}); assert.ok(f.controller.frames.length<=2); }); test('no authority retains playback without provider access', async () => { const f=fixture({authority:()=>false}); await assert.rejects(f.controller.update({scene:scene()}),{code:'stale'}); assert.deepEqual(f.log,[]); }); test('queued state is captured at submission rather than read after caller mutation',async()=>{ const f=fixture(),state={scene:scene()};const pending=f.controller.update(state);state.scene.playlist=ref('mutated'); await pending;assert.equal(f.playback.items[0],'A'); }); test('supersession after snapshot prevents mutations',async()=>{ const f=fixture();await f.controller.update({scene:scene()}); let resume,entered;const ready=new Promise(r=>entered=r),normal=f.provider.snapshot; f.provider.snapshot=async c=>{const s=await normal(c);entered();await new Promise(r=>resume=r);return s;}; const first=f.controller.update({scene:scene(),combats:[combat()]});await ready; f.provider.snapshot=normal;const second=f.controller.update({scene:scene('B')});resume(); await assert.rejects(first,{code:'stale'});await second; assert.equal(f.log.filter(x=>x[0]==='apply'&&x[1]==='combat').length,0); }); test('failed cross-provider apply cleans new owned audio before outgoing restoration',async()=>{ const f=fixture();await f.controller.update({scene:scene()});const effects=[]; f.controller.providers.other={resolve:async r=>r,apply:async()=>{effects.push('partial');throw new Error('failed');},stopOwned:async()=>effects.push('cleanup')}; await assert.rejects(f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}})); assert.deepEqual(effects,['partial','cleanup']);assert.equal(f.playback.items[0],'A'); }); test('superseded cross-provider apply is reconciled by stopping partially touched target',async()=>{ const f=fixture();await f.controller.update({scene:scene()}); let resume,entered;const ready=new Promise(r=>entered=r);let cleanups=0; f.controller.providers.other={resolve:async r=>r,apply:async()=>{entered();await new Promise(r=>resume=r);},stopOwned:async()=>{cleanups++;}}; const stale=f.controller.update({scene:{id:'B',playlist:{provider:'other',id:'B'}}});await ready; const newest=f.controller.update({scene:scene()});resume();await assert.rejects(stale,{code:'stale'});await newest; assert.equal(cleanups,1);assert.equal(f.playback.items[0],'A'); });