diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 2289b00e4..dc3178d81 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -22,6 +22,7 @@ CANONICAL = ROOT / "site" / "preview-v2" NATIVE_ADAPTER = ROOT / "web" / "approved-native-bridge.js" ADAPTER_MARKER = ('\n' + '\n' '\n' '\n' '\n') @@ -359,6 +360,8 @@ def stage(out: Path) -> dict: out / "assets" / "approved-native-legal.js") shutil.copy2(ROOT / "web" / "approved-native-contract.js", out / "assets" / "approved-native-contract.js") + shutil.copy2(ROOT / "web" / "approved-device-view-model.js", + out / "assets" / "approved-device-view-model.js") native = native_html(approved.decode("utf-8")).encode("utf-8") (out / "index.html").write_bytes(native) files = [out / "index.html", *sorted(p for p in (out / "assets").rglob("*") if p.is_file())] diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 3ba705afa..9d7f05232 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -97,12 +97,35 @@ def main(): assert progress.locator('svg animate').count()==4 assert progress.locator('svg').evaluate('(svg)=>svg.animationsPaused()')==(width==1920) assert page.locator('[data-audio-close]').is_disabled() + # The transient request lives in the ViewModel, not in a DOM attribute. + apply_calls=[0] def wait_apply(): - pending=page.locator('.armix-audio-shade').get_attribute('data-pending-request') - assert pending - page.wait_for_function("""id=>window.__events.some(e=> - e.payload?.action==='audioDeviceApply'&&e.payload.requestId===id)""",arg=pending) + apply_calls[0]+=1 + page.wait_for_function("""count=>window.__events.filter(e=> + e.name==='arMixAction'&&e.payload?.action==='audioDeviceApply').length===count""", + arg=apply_calls[0]) assert page.evaluate('()=>window.__applyPainted') + + def emit_device_readback(actual, epoch): + # Native schema-v6 device proof without an installed PCM graph. + fresh=copy.deepcopy(json.loads( + (ROOT/'integration/console-v6/fixtures.json').read_text())['g0']) + inputs=actual['enabledInputs'] + outputs=actual['enabledOutputs'] + fresh['device'].update( + epoch=str(epoch),backend=actual['backend'], + captureDevice=actual['captureDevice'], + playbackDevice=actual['playbackDevice'], + sampleRate=actual['rate'],bufferFrames=actual['buffer'], + enabledInputs=inputs,enabledOutputs=outputs, + inputEndpoints=[dict(id=f'in:{pin}',port=pin,callback=i, + label=f'IN {pin+1}',active=True) + for i,pin in enumerate(inputs)], + outputEndpoints=[dict(id=f'out:{pin}',port=pin,callback=i, + label=f'OUT {pin+1}',active=True) + for i,pin in enumerate(outputs)], + outputArmed=False) + emit(page,'arMixConsoleSnapshot',fresh) wait_apply() request=page.evaluate("""()=>window.__events.filter(e=> e.payload?.action==='audioDeviceApply').at(-1)?.payload""") @@ -111,12 +134,15 @@ def wait_apply(): assert request['config']['enabledInputs']==[] assert request['config']['enabledOutputs']==[] out_active={**io_inventory['active'],'captureDevice':'', - 'inputNames':[],'enabledInputs':[], + 'inputNames':[],'enabledInputs':[],'deviceGeneration':70, 'outputNames':['WDM L','WDM R','Realtek L','Realtek R']} emit(page,'arMixAudioDeviceApplyAck',{ 'requestId':request['requestId'],'ok':True, 'state':'ACCEPTED_MUTED','active':out_active, 'outputMuted':True,'mixerBound':True}) + assert progress.is_visible() and apply.is_disabled(), ( + 'ACK-only must never announce an installed playback device') + emit_device_readback(out_active,'70') assert page.locator('.armix-audio-shade').is_hidden() page.locator('.command-bar [data-native-io]').click() io_inventory['active']=out_active @@ -138,12 +164,16 @@ def playback_pin(index): assert repatch['config']['assignSelectedPlaybackPinsToMain'] is True assert repatch['config']['enabledOutputs']==[2,3] assert repatch['config']['enabledInputs']==[] + main_active={**out_active,'deviceGeneration':71,'enabledOutputs':[2,3]} emit(page,'arMixAudioDeviceApplyAck',{ 'requestId':repatch['requestId'],'ok':True, - 'state':'ACCEPTED_MUTED','active':{**out_active,'enabledOutputs':[2,3]}, - 'outputMuted':True,'mixerBound':True}) + 'state':'ACCEPTED_MUTED','active':main_active, + 'outputMuted':True,'mixerBound':False}) + assert progress.is_visible() and apply.is_disabled() + emit_device_readback(main_active,'71') assert page.locator('.armix-audio-shade').is_hidden() g0=json.loads((ROOT/'integration/console-v6/fixtures.json').read_text())['g0'] + g0['device']['epoch']='72' g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} g0['legacyM4']={'active':True,'routeAccepted':False,'routingRevision':'1'} emit(page,'arMixConsoleSnapshot',g0) @@ -234,7 +264,8 @@ def show_select(value): assert page.locator('.console-pane').is_visible() assert not page.evaluate('()=>window.__nativeIntents.length') state=snapshot() - state['device'].update(enabledInputs=[],inputEndpoints=[]) + state['device'].update(epoch='72',enabledInputs=[],inputEndpoints=[]) + state['mixerSession']['deviceEpoch']='72' state['graph']['edges'].pop(1) # genuinely no existing channel send state['graph']['capabilities']['supportedOps'] += ['LOAD_INSERT'] for ident, role, name in [('101','GROUP','Vocal Group'), @@ -349,7 +380,7 @@ def show_select(value): page.locator('[data-native-io]').click() backend='Windows Audio' active={'backend':backend,'captureDevice':'New Capture','playbackDevice':'New Playback', - 'open':True,'authorized':True,'deviceGeneration':12,'rate':48000,'buffer':256, + 'open':True,'authorized':True,'deviceGeneration':92,'rate':48000,'buffer':256, 'inputNames':['Input 1'],'outputNames':['Output 1','Output 2'], 'enabledInputs':[0],'enabledOutputs':[0,1],'rates':[48000],'buffers':[256]} emit(page,'arMixAudioDeviceInventory',{'active':active,'types':[ @@ -365,17 +396,23 @@ def show_select(value): 'active':active,'canReusePins':True}) assert progress.is_visible() and apply.is_disabled() assert remap.is_hidden() + applied={**active,'deviceGeneration':93} emit(page,'arMixAudioDeviceApplyAck',{'requestId':opened['requestId'],'ok':True, - 'state':'ACCEPTED_LIVE','active':active,'mixerBound':True,'outputMuted':False}) - assert page.locator('.armix-audio-shade').is_hidden() + 'state':'ACCEPTED_LIVE','active':applied,'mixerBound':True,'outputMuted':False}) + assert progress.is_visible() and apply.is_disabled() rebound=copy.deepcopy(state) - rebound['device'].update(epoch='93',outputArmed=True, - enabledInputs=g0['device']['enabledInputs'],inputEndpoints=g0['device']['inputEndpoints']) + rebound['device'].update(epoch='93',backend=backend, + captureDevice=active['captureDevice'],playbackDevice=active['playbackDevice'], + sampleRate=48000,bufferFrames=256,outputArmed=True, + enabledInputs=active['enabledInputs'],enabledOutputs=active['enabledOutputs'], + inputEndpoints=g0['device']['inputEndpoints']) rebound['graph']['revision']='6' rebound['graph']['capabilities']['supportedOps'].append('CREATE_CHANNEL') rebound['mixerSession'].update(deviceEpoch='93',routeRevision='6') monitor_events=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length') emit(page,'arMixConsoleSnapshot',rebound) + assert page.locator('.armix-audio-shade').is_hidden(), ( + 'correlated installed PCM readback must settle device apply') page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__.state().current?.admitted') assert page.locator('[data-native-monitor]').is_enabled() assert page.locator('[data-native-monitor]').get_attribute('data-armed')=='true' @@ -405,14 +442,19 @@ def show_select(value): wait_apply() repeated=page.evaluate(read_apply) assert repeated['requestId']!=rejected['requestId'] + next_active={**active,'deviceGeneration':94} emit(page,'arMixAudioDeviceApplyAck',{'requestId':repeated['requestId'],'ok':True, - 'state':'ACCEPTED_LIVE','active':active,'mixerBound':True,'outputMuted':False}) + 'state':'ACCEPTED_LIVE','active':next_active,'mixerBound':True,'outputMuted':False}) + assert progress.is_visible() and apply.is_disabled() + rebound['device']['epoch']='94' + rebound['mixerSession']['deviceEpoch']='94' + emit(page,'arMixConsoleSnapshot',rebound) assert page.locator('.armix-audio-shade').is_hidden() assert page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length')==monitor_events add_track.click() request=page.evaluate(create)[-1]['payload'] assert (request['deviceEpoch'],request['graphRevision'],request['rosterRevision'])==( - '93','6',rebound['graph']['rosterRevision']) + '94','6',rebound['graph']['rosterRevision']) assert add_track.is_disabled() created_id='9007199254740997' emit(page,'arMixNativeBusAck',{'requestId':request['requestId'], diff --git a/tests/approved_native_gui_bundle_test.py b/tests/approved_native_gui_bundle_test.py index 98ed40812..51a5f19b8 100644 --- a/tests/approved_native_gui_bundle_test.py +++ b/tests/approved_native_gui_bundle_test.py @@ -58,6 +58,17 @@ def test_native_is_exact_assembled_public_pages_plus_nonvisual_native_seam(self) self.assertEqual(manifest["approvedPagesHtmlSha256"], bundle.sha256((source / "index.html").read_bytes())) self.assertNotEqual(native, (ROOT / "web/index.html").read_text("utf-8")) self.assertIn("approved-native-bridge.js", native) + # Native-only pure Device Setup VM must load BEFORE the approved + # bridge and must never change the public /preview/ HTML. + self.assertIn('assets/approved-device-view-model.js', native) + self.assertNotIn('assets/approved-device-view-model.js', approved) + self.assertLess(native.index('assets/approved-native-contract.js'), + native.index('assets/approved-device-view-model.js')) + self.assertLess(native.index('assets/approved-device-view-model.js'), + native.index('assets/approved-native-bridge.js')) + vm_source = (ROOT / "web/approved-device-view-model.js").read_bytes() + self.assertEqual((out / "assets/approved-device-view-model.js").read_bytes(), + vm_source) self.assertIn("approved-native-context-menu.js", native) context_menu = (out / "assets/approved-native-context-menu.js").read_text("utf-8") self.assertIn('document.addEventListener("contextmenu"', context_menu) @@ -134,6 +145,7 @@ def test_manifest_reproducibility_and_byte_map(self): self.assertIn("BinaryData::mixercontrolkeys_css", header) self.assertIn("BinaryData::arsonmixapprovedruntime_css", header) self.assertIn("BinaryData::mixercontrolkeys_js", header) + self.assertIn("BinaryData::approveddeviceviewmodel_js", header) self.assertIn('"/assets/mixer-keys-thin-flat-v9-approved-off-shadow-57x30.png"', header) for entry in first["files"]: self.assertEqual(bundle.sha256((a / entry["path"]).read_bytes()), entry["sha256"]) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 594e43069..209543c93 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -4,6 +4,7 @@ const test=require("node:test"); const assert=require("node:assert/strict"); const {readFileSync}=require("node:fs"); const protocol=require("../web/approved-native-contract.js"); +const deviceVM=require("../web/approved-device-view-model.js"); const read=p=>readFileSync(p,"utf8"); const fixtures=JSON.parse(read("integration/console-v6/fixtures.json")); const clone=x=>JSON.parse(JSON.stringify(x)); @@ -398,7 +399,8 @@ test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, assert.match(builder,/type==='input'&&window\.__JUCE__\?\.backend/); assert.match(builder,/__ARMIX_NATIVE_M2__\?\.inputChoices/); assert.match(bridge,/inputChoices\(t\)/); - assert.match(bridge,/hardware\.device\.enabledInputs\.includes\(p\.port\)/); + assert.match(bridge,/deviceVM\.inputChoices\(hardware\)/); + assert.match(read("web/approved-device-view-model.js"),/d\.enabledInputs\.includes\(p\.port\)/); assert.match(bridge,/field==="input"/); // Reordering /preview/ strips must NOT change the real hardware lane. assert.match(bridge,/const channel=m4Index\(t\)/); @@ -999,7 +1001,8 @@ test("single /preview/ GUI: channel IN, actual OUT and correlated device safety assert.match(bridge,/source:"\/preview\/ approved compiled Pages GUI"/); assert.match(bridge,/field==="input"/); assert.match(bridge,/nativeUiSourcePending=null;[\s\S]*?INPUT timeout/); - assert.match(bridge,/ack\?\.requestId!==devicePanel.dataset.pendingRequest/); + assert.match(bridge,/deviceVM\.setupAck\(deviceState,ack\)/); + assert.match(read("web/approved-device-view-model.js"),/ack\?\.requestId!==state\.pending\.requestId/); assert.match(native,/requestAutomaticMain\(\);\s*send\(true,engine_\.isMonitorEnabled\(\)\?"ACCEPTED_LIVE":"ACCEPTED_MUTED"/); assert.match(bridge,/Virtual output · No speakers/); assert.match(bridge,/Advanced driver recovery/); @@ -1245,7 +1248,7 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a querySelector:()=>null,addEventListener(){} }; const window={ - __JUCE__:{backend:native},ArSonApprovedNativeContract:protocol, + __JUCE__:{backend:native},ArSonApprovedNativeContract:protocol,ArSonApprovedDeviceViewModel:deviceVM, __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){},queueMicrotask(fn){microtasks.push(fn);},setTimeout(fn,ms){timers.push({fn,ms});return timers.length;} }; vm.runInNewContext(read("web/approved-native-bridge.js"),{ @@ -1469,7 +1472,7 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla querySelector:selector=>selector.startsWith('.strip[data-id=')?strip:null, addEventListener(){} }; - const win={__JUCE__:{backend:native},ArSonApprovedNativeContract:protocol, + const win={__JUCE__:{backend:native},ArSonApprovedNativeContract:protocol,ArSonApprovedDeviceViewModel:deviceVM, __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, setTimeout(){return 0},clearTimeout(){},queueMicrotask(fn){fn();}}; vm.runInNewContext(read("web/approved-native-bridge.js"), @@ -1618,7 +1621,7 @@ test("P0 output-only Audio I/O is a real native configuration, never blocked by assert.match(bridge,/No hardware input \(Player \/ FX\)/); assert.match(bridge,/t\?\.separate\?\["",\.\.\.\(t\.inputs\|\|\[\]\)\]/); assert.doesNotMatch(bridge,/ack\.active\.enabledInputs\.length>0/); - assert.match(bridge,/FX\/WIRE available/); + assert.match(read("web/approved-device-view-model.js"),/Mixer ready · Output muted/); }); test("P0 FIRST SOUND G0 offers verified input and leaves automatic MAIN to native",()=>{ const vm=require("node:vm"),sent=[],listeners=new Map(),renderedChoices=[]; @@ -1645,7 +1648,7 @@ test("P0 FIRST SOUND G0 offers verified input and leaves automatic MAIN to nativ addEventListener(){} }; win={ - __JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __JUCE__:{backend},ArSonApprovedNativeContract:protocol,ArSonApprovedDeviceViewModel:deviceVM, __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, setTimeout(){return 0},clearTimeout(){},queueMicrotask(fn){fn();} }; @@ -1732,7 +1735,7 @@ test("P0 native hardware IN remains selectable after ChannelId ownership, failed id==="preview"?{disabled:true}:null, querySelector:()=>null,addEventListener(){} }; - const win={__JUCE__:{backend},ArSonApprovedNativeContract:protocol, + const win={__JUCE__:{backend},ArSonApprovedNativeContract:protocol,ArSonApprovedDeviceViewModel:deviceVM, __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, setTimeout(){return 0},clearTimeout(){}, queueMicrotask(fn){microtasks.push(fn);}}; @@ -1808,9 +1811,11 @@ test("native Windows operator can explicitly patch first physical input, arm and assert.match(js,/AUDIO \/ SAFETY/); assert.match(js,/function openNativeAudioIO\(\)/); assert.match(js,/action:"audioDeviceInventory"/); - assert.match(js,/action:"audioDeviceApply"/); - assert.match(js,/d\.inputEndpoints\.filter\(p=>/); - assert.match(js,/d\.enabledInputs\.includes\(p\.port\)/); + assert.match(read("web/approved-device-view-model.js"),/action:"audioDeviceApply"/); + assert.match(js,/backend\.emitEvent\("arMixAction",begun\.request\)/); + assert.match(read("web/approved-device-view-model.js"),/d\.inputEndpoints\.filter\(p=>/); + assert.match(read("web/approved-device-view-model.js"),/d\.enabledInputs\.includes\(p\.port\)/); + assert.match(js,/deviceVM\.inputChoices\(hardware\)/); assert.match(js,/action:"routingSourceSwitch",requestId:pendingSourceId/); assert.match(js,/channel:0,mode:"MONO",left:pin,right:-1/); assert.match(js,/action:"monitor",value:true/); @@ -2152,9 +2157,11 @@ test("O2 SOURCE ONLY confirmed ASIO EXTERNAL OUT auto-arms without a second Moni test("O2 external OUT never reports LIVE while driver output is muted",()=>{ const bridge=read("web/approved-native-bridge.js"); const css=read("site/preview-v2/assets/mixer-section-controls.css"); - assert.match(bridge,/const pcmInstalled=row\?\.status==="LIVE"&&match/); - assert.match(bridge,/next\?\.device\?\.outputArmed===true\?"LIVE":"MUTED"/); - assert.match(bridge,/state==="MUTED"\?"ASIO pair connected/); + const projection=read("web/approved-device-view-model.js"); + assert.match(projection,/const installed=row\?\.status==="LIVE"&&match/); + assert.match(projection,/snapshot\?\.device\?\.outputArmed===true\?"LIVE":"MUTED"/); + assert.match(projection,/state==="MUTED"\?"ASIO pair connected/); + assert.match(bridge,/deviceVM\.externalPresentation\(next,row,choices\)/); assert.match(bridge,/state==="LIVE"\|\|state==="MUTED"/); assert.match(bridge,/EXTERNAL OUT patched · hardware output muted/); assert.match(css,/external-out-state\[data-status="MUTED"\]/); @@ -2162,9 +2169,11 @@ test("O2 external OUT never reports LIVE while driver output is muted",()=>{ test("O2 SHARED output means two or more ChannelIds, not one",()=>{ const bridge=read("web/approved-native-bridge.js"); - assert.match(bridge,/shared>1\?" · SHARED "\+shared\+" SOURCES"/); - assert.match(bridge,/const shared=Array\.isArray\(hardware\?\.raw\?\.externalOutputs\)/); - assert.doesNotMatch(bridge,/shared\?" · SHARED "\+shared/); + const projection=read("web/approved-device-view-model.js"); + assert.match(projection,/shared>1\?" · SHARED "\+shared\+" SOURCES"/); + assert.match(projection,/const shared=Array\.isArray\(snapshot\?\.raw\?\.externalOutputs\)/); + assert.doesNotMatch(projection,/shared\?" · SHARED "\+shared/); + assert.match(bridge,/deviceVM\.outputChoices\(hardware\)/); }); test("O3 OUTPUTS overview reflects real ASIO 8-pin ownership and callback status",()=>{ @@ -2283,3 +2292,214 @@ test("SOF double-click and target selection never commandeer MAIN fader",()=>{ assert.match(handler,/requestWireGain\(\{sourceId:t\.id,edgeId:id,levelDb:0\}\)/); assert.match(handler,/intent\("SET_INPUT_GAIN",t,\{valueDb:0\}\)/); }); + +test("MVVM device selector projects only the verified native physical input pins",()=>{ + const hardware={device:{backend:"ASIO",enabledInputs:[0,1,3], + inputEndpoints:[ + {port:0,label:"Mic 1",active:true},{port:1,label:"Mic 2",active:true}, + {port:2,label:"Disabled",active:true},{port:3,label:"Mic 4",active:true}, + {port:4,label:"Inactive",active:false}]},raw:{}}; + const original=JSON.stringify(hardware); + assert.deepEqual(deviceVM.activeInputPins(hardware).map(p=>p.port),[0,1,3]); + const choices=deviceVM.inputChoices(hardware); + assert.deepEqual(choices.map(x=>[x.mode,x.left,x.right]),[ + ["NONE",-1,-1],["MONO",0,-1],["MONO",1,-1],["MONO",3,-1],["STEREO",0,1] + ]); + assert.equal(deviceVM.inputLabel(hardware,{mode:"MONO",left:3,right:-1}), + "Mono · Mic 4 [IN 4]"); + assert.equal(deviceVM.inputLabel(hardware,{mode:"STEREO",left:0,right:1}), + "Stereo · IN 1 + 2"); + assert.equal(deviceVM.inputLabel(hardware,{mode:"STEREO",left:1,right:2}),"None"); + assert.equal(deviceVM.inputLabel(hardware,{mode:"BUS"}),"Internal BUS (read-only)"); + assert.equal(JSON.stringify(hardware),original,"view must not mutate native readback"); + assert.deepEqual(deviceVM.inputChoices({device:{inputEndpoints:[],enabledInputs:[]}}), + [{label:"None",mode:"NONE",left:-1,right:-1}]); + assert.deepEqual(deviceVM.activeInputPins({device:{inputEndpoints:hardware.device.inputEndpoints}}),[]); +}); +test("MVVM external outputs never offer MAIN/MONITOR pins, disabled pairs, or WASAPI copies",()=>{ + const snapshot={device:{backend:"ASIO",enabledOutputs:[0,1,2,3,4,5,7,8], + outputArmed:false,outputEndpoints:Array.from({length:9},(_,port)=>({ + port,label:"Physical "+(port+1),active:port!==6 + }))},raw:{physicalMainOutputs:[0,1],physicalMonitorOutputs:[4,5], + externalOutputs:[{physicalLeft:2,physicalRight:3},{physicalLeft:2,physicalRight:3}]}}; + const before=JSON.stringify(snapshot); + const choices=deviceVM.outputChoices(snapshot); + assert.equal(choices.length,2); + assert.deepEqual(choices[0],{label:"None",left:-1,right:-1}); + assert.deepEqual([choices[1].left,choices[1].right],[2,3]); + assert.match(choices[1].label,/SHARED 2 SOURCES/); + assert.equal(deviceVM.outputChoices({...snapshot,device:{...snapshot.device, + backend:"WASAPI"}}).length,1); + assert.equal(JSON.stringify(snapshot),before,"output projection must be read-only"); +}); +test("MVVM external readback needs verified pair and output-arm, never ACK-only LIVE",()=>{ + const snapshot={device:{backend:"ASIO",outputArmed:false, + outputEndpoints:[{port:2,label:"OUT L",active:true},{port:3,label:"OUT R",active:true}], + enabledOutputs:[2,3]},raw:{physicalMainOutputs:[],physicalMonitorOutputs:[],externalOutputs:[]}}; + const choices=deviceVM.outputChoices(snapshot); + const installed={status:"LIVE",physicalLeft:2,physicalRight:3}; + const muted=deviceVM.externalPresentation(snapshot,installed,choices); + assert.equal(muted.state,"MUTED"); + assert.equal(muted.marker,"MUTED"); + assert.equal(muted.value,choices[1].label); + assert.equal(deviceVM.externalPresentation({...snapshot, + device:{...snapshot.device,outputArmed:true}},installed,choices).state,"LIVE"); + assert.equal(deviceVM.externalPresentation(snapshot,{...installed,status:"PENDING"},choices).state, + "PENDING"); + const invalid=deviceVM.externalPresentation(snapshot, + {...installed,physicalLeft:6,physicalRight:7},choices); + assert.equal(invalid.state,"NEEDS_REMAP"); + assert.match(invalid.value,/Needs Remap/); + assert.equal(deviceVM.externalPresentation(snapshot,null,choices).state,"NONE"); + assert.equal(deviceVM.externalPresentation(null,installed).state,"NEEDS_REMAP"); +}); +test("MVVM native bridge uses the one device read model, not retired web/mixer-io.js",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const build=read("scripts/build_approved_native_gui.py"); + assert.match(bridge,/deviceVM\.inputChoices\(hardware\)/); + assert.match(bridge,/deviceVM\.externalPresentation\(next,row,choices\)/); + assert.match(bridge,/deviceVM\.outputChoices\(hardware\)/); + assert.doesNotMatch(bridge,/const monoLabel=|const hardwareOutputPairs=\(\)=>\{/); + assert.match(build,/assets\/approved-device-view-model\.js/); + assert.match(build,/web" \/ "approved-device-view-model\.js"/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet|createPluginInstance/); +}); + + +// Device Setup MVVM: the same native /preview/ bundle owns one transient UI +// transaction, but only installed schema-v6 readback may make it accepted. +function nativeDeviceSetupFixture() { + const active={backend:"ASIO",captureDevice:"ASIO Test",playbackDevice:"ASIO Test", + deviceGeneration:12,open:true,authorized:true,rate:48000,buffer:256, + enabledInputs:[0],enabledOutputs:[0,1]}; + const inventory={active,types:[{name:"ASIO",separate:false, + inputs:["ASIO Test"],outputs:["ASIO Test"]}]}; + const draft={backend:"ASIO",capture:"ASIO Test",playback:"ASIO Test", + inputPins:[0],outputPins:[0,1],rate:48000,buffer:256}; + const begin=requestId=>deviceVM.setupBegin(deviceVM.setupInitial(),{ + inventory,draft,requestId,baselineEpoch:"12"}); + const ack=(requestId,overrides={})=>({ + requestId,ok:true,state:"ACCEPTED_LIVE", + active:{...active,deviceGeneration:13},mixerBound:true, + outputMuted:false,...overrides}); + const readback={raw:{schemaVersion:6},retained:false,admitted:true, + productLive:true,device:{epoch:"13",backend:active.backend, + captureDevice:active.captureDevice,playbackDevice:active.playbackDevice, + sampleRate:48000,bufferFrames:256,enabledInputs:[0], + enabledOutputs:[0,1],outputArmed:true}}; + return {active,inventory,draft,begin,ack,readback}; +} +test("Device Setup VM requires matching ACK AND later installed v6 readback, never ACK-only LIVE",()=>{ + const f=nativeDeviceSetupFixture(); + const begun=f.begin("approved-io-42"); + assert.ok(begun);assert.equal(begun.request.action,"audioDeviceApply"); + assert.equal(begun.request.expectedDeviceGeneration,12); + assert.equal(begun.request.config.backend,"ASIO"); + assert.equal(begun.request.config.sampleRate,48000); + const waiting=deviceVM.setupAck(begun.state,f.ack("approved-io-42")); + assert.equal(waiting.phase,"VERIFYING"); + assert.equal(waiting.pending.requestId,"approved-io-42"); + assert.equal(waiting.message,""); + const beforeAckDevice={...f.readback,device:{...f.readback.device,epoch:"12"}}; + assert.equal(deviceVM.setupReadback(waiting,beforeAckDevice),waiting, + "matching old hardware cannot prove the later Apply ACK"); + assert.equal(deviceVM.setupReadback(waiting,{...f.readback,device:{ + ...f.readback.device,bufferFrames:128}}),waiting, + "rate/buffer mismatch never proves installed device"); + const ready=deviceVM.setupReadback(waiting,f.readback); + assert.equal(ready.phase,"ACCEPTED"); + assert.equal(ready.pending,null); + assert.match(ready.message,/Output live/); + assert.equal(deviceVM.setupReadback(waiting,{...f.readback,device:{ + ...f.readback.device,epoch:"14"}}).phase,"ACCEPTED", + "routing epoch may advance beyond JUCE's generation"); + assert.equal(deviceVM.setupAck(ready,f.ack("approved-io-42")),ready, + "late ACK cannot resurrect a finished request"); +}); +test("Device Setup VM fails closed for device loss, unadmitted graph, stale epoch and stale ACK",()=>{ + const f=nativeDeviceSetupFixture(); + const waiting=deviceVM.setupAck(f.begin("approved-io-5").state,f.ack("approved-io-5")); + const deviceOnly=deviceVM.setupReadback(waiting,{ + ...f.readback,admitted:false,productLive:false}); + assert.equal(deviceOnly.phase,"ACCEPTED", + "the real device may be ready before a ChannelId PCM graph is admitted"); + assert.match(deviceOnly.message,/route not yet verified/i); + assert.doesNotMatch(deviceOnly.message,/Mixer ready|Output live/); + const lost=deviceVM.setupReadback(waiting,{...f.readback, + device:{...f.readback.device,epoch:"14",sampleRate:0,enabledOutputs:[]}}); + assert.equal(lost.phase,"RECOVERY_REQUIRED"); + assert.equal(lost.pending,null); + const stale=deviceVM.setupReadback(waiting,{...f.readback, + device:{...f.readback.device,epoch:"11"}}); + assert.equal(stale.phase,"STALE"); + assert.equal(deviceVM.setupAck(waiting,f.ack("approved-io-4")),waiting, + "old request ID cannot change the current transaction"); + assert.equal(deviceVM.setupReadback(waiting,{...f.readback,retained:true}).phase, + "RECOVERY_REQUIRED"); +}); +test("Device Setup VM rejects driver negative ACK, safe rollback, wrong endpoint and absent generation",()=>{ + const f=nativeDeviceSetupFixture(); + const begun=f.begin("approved-io-6"); + const fail=deviceVM.setupAck(begun.state,{requestId:"approved-io-6",ok:false, + state:"REJECTED",error:"Driver refused",active:f.active}); + assert.equal(fail.phase,"REJECTED"); + assert.match(fail.message,/Driver refused/); + const rollback=deviceVM.setupAck(begun.state,{requestId:"approved-io-6",ok:false, + state:"RESTORED_MUTED",error:"Driver refused",active:f.active}); + assert.equal(rollback.phase,"REJECTED"); + assert.match(rollback.message,/Previous device restored/); + assert.deepEqual(f.inventory.active.enabledOutputs,[0,1], + "refused apply cannot mutate the installed output pins in the UI"); + const unverified=deviceVM.setupAck(begun.state,f.ack("approved-io-6",{ + active:{...f.active,deviceGeneration:13,authorized:false}})); + assert.equal(unverified.phase,"REJECTED"); + const wrongEndpoint=deviceVM.setupAck(begun.state,f.ack("approved-io-6",{ + active:{...f.active,deviceGeneration:13,playbackDevice:"Another ASIO"}})); + assert.equal(wrongEndpoint.phase,"REJECTED", + "same requestId cannot approve another physical output"); + const staleGeneration=deviceVM.setupAck(begun.state,f.ack("approved-io-6",{ + active:{...f.active,deviceGeneration:11}})); + assert.equal(staleGeneration.phase,"REJECTED", + "same requestId cannot approve an older driver generation"); + const accepted=deviceVM.setupAck(begun.state,f.ack("approved-io-6")); + assert.equal(deviceVM.setupReadback(accepted,{...f.readback, + device:{...f.readback.device,playbackDevice:"Unexpected"}}).phase,"VERIFYING"); + assert.equal(deviceVM.setupBegin(deviceVM.setupInitial(),{ + inventory:{...f.inventory,active:{...f.active,deviceGeneration:null}}, + draft:f.draft,requestId:"invalid"}),null); +}); +test("Device Setup VM times out both before and after ACK; late events never apply",()=>{ + const f=nativeDeviceSetupFixture(); + const begun=f.begin("approved-io-7"); + assert.equal(deviceVM.setupBegin(begun.state,{inventory:f.inventory, + draft:f.draft,requestId:"approved-io-8"}),null); + const timed=deviceVM.setupTimeout(begun.state,"approved-io-7"); + assert.equal(timed.phase,"TIMEOUT"); + assert.equal(deviceVM.setupAck(timed,f.ack("approved-io-7")),timed); + const verifying=deviceVM.setupAck(begun.state,f.ack("approved-io-7")); + const staleTimer=deviceVM.setupTimeout(verifying,"approved-io-6"); + assert.equal(staleTimer,verifying); + assert.equal(deviceVM.setupTimeout(verifying,"approved-io-7").phase,"TIMEOUT"); +}); +test("Device Setup VM retains offline .smix and never promotes rollback to output LIVE",()=>{ + const f=nativeDeviceSetupFixture(); + const document={schema:"arsonmix.native.logical-mixer.v1",revision:"18446744073709551615", + channels:[{id:"9007199254740993"}],outputArmed:false}; + const frozen=JSON.stringify(document); + const begun=f.begin("approved-io-9"); + const awaiting=deviceVM.setupAck(begun.state,f.ack("approved-io-9")); + const offline=deviceVM.setupReadback(awaiting,{...f.readback,retained:true, + raw:{schemaVersion:6,logicalMixer:document},admitted:false,productLive:false}); + assert.equal(offline.phase,"RECOVERY_REQUIRED"); + assert.equal(JSON.stringify(document),frozen); + assert.equal(deviceVM.setupAck(begun.state,{requestId:"approved-io-9", + ok:false,state:"RESTORED_LIVE",active:f.active}).phase,"REJECTED"); + const text=read("web/approved-native-bridge.js"); + assert.match(text,/deviceVM\.setupReadback\(deviceState,next\)/); + assert.match(text,/deviceVM\.setupAck\(deviceState,ack\)/); + const setup=text.slice(text.indexOf(" // Compact DAW-style device preferences"), + text.indexOf(" function installFirstSoundMenu()")); + assert.doesNotMatch(setup,/const accepted=ack\.ok===true/); + assert.doesNotMatch(text,/devicePanel\.dataset\.pendingRequest/); + assert.equal((text.match(/backend\.emitEvent\("arMixAction",begun\.request\)/g)||[]).length,1); +}); diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs index d6edfd800..0b2db1447 100644 --- a/tests/live_fader_held_drag.test.cjs +++ b/tests/live_fader_held_drag.test.cjs @@ -6,6 +6,7 @@ const assert=require("node:assert/strict"); const {readFileSync}=require("node:fs"); const vm=require("node:vm"); const protocol=require("../web/approved-native-contract.js"); +const deviceVM=require("../web/approved-device-view-model.js"); const read=p=>readFileSync(p,"utf8"); const clone=x=>JSON.parse(JSON.stringify(x)); const fixture=JSON.parse(read("integration/console-v6/fixtures.json")).g0; @@ -75,7 +76,7 @@ function harness({m4=false}={}){ },addEventListener(){} }; const window={ - __JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __JUCE__:{backend},ArSonApprovedNativeContract:protocol,ArSonApprovedDeviceViewModel:deviceVM, __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, setTimeout(fn,delay=0){timers.push({fn,at:now+Math.max(0,Number(delay)||0)});return timers.length;} }; diff --git a/web/approved-device-view-model.js b/web/approved-device-view-model.js new file mode 100644 index 000000000..f5aefe406 --- /dev/null +++ b/web/approved-device-view-model.js @@ -0,0 +1,224 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Read-only Device I/O presentation projection for the ONE approved native /preview/. +// This is NOT a device manager, session store, routing command bus, PCM engine, +// or physical availability authority. All choices derive from native readback. +(function (root, factory) { + const api = factory(); + if (typeof module === "object" && module.exports) module.exports = api; + if (root) root.ArSonApprovedDeviceViewModel = api; +})(typeof globalThis === "object" ? globalThis : undefined, function () { + "use strict"; + const INTERNAL_BUS = "Internal BUS (read-only)"; + const NONE = {label:"None",left:-1,right:-1}; + // The native contract validates endpoints before reaching this selector. + // Additional guards keep a lost/partial snapshot from advertising phantom pins. + function activeInputPins(snapshot) { + const d=snapshot?.device; + if(!Array.isArray(d?.inputEndpoints)||!Array.isArray(d.enabledInputs))return []; + return d.inputEndpoints.filter(p=>p?.active===true && + Number.isInteger(p.port) && d.enabledInputs.includes(p.port)); + } + function inputChoices(snapshot) { + const pins=activeInputPins(snapshot); + const entries=[{label:"None",mode:"NONE",left:-1,right:-1}]; + for(const p of pins)entries.push({ + label:"Mono · "+p.label+" [IN "+(p.port+1)+"]", + mode:"MONO",left:p.port,right:-1}); + // Preserve existing physical adjacency semantics, never pair packed + // callback ordinals or guess unavailable driver pins. + for(let i=0;i+1x.mode===row.mode && + x.left===row.left && x.right===row.right); + return found?.label||"None"; + } + function outputChoices(snapshot) { + const d=snapshot?.device,choices=[{...NONE}]; + if(d?.backend!=="ASIO"||!Array.isArray(d.outputEndpoints)|| + !Array.isArray(d.enabledOutputs))return choices; + const map=new Map(d.outputEndpoints.filter(p=> + p?.active===true&&Number.isInteger(p.port)&& + d.enabledOutputs.includes(p.port)&& + typeof p.label==="string"&&p.label.length>0).map(p=>[p.port,p])); + const main=Array.isArray(snapshot?.raw?.physicalMainOutputs)? + snapshot.raw.physicalMainOutputs:[]; + const monitor=Array.isArray(snapshot?.raw?.physicalMonitorOutputs)? + snapshot.raw.physicalMonitorOutputs:[]; + for(const [left,a] of map) { + if(left%2!==0||!map.has(left+1))continue; + const b=map.get(left+1); + if(main.includes(left)||main.includes(left+1)|| + monitor.includes(left)||monitor.includes(left+1))continue; + const shared=Array.isArray(snapshot?.raw?.externalOutputs)? + snapshot.raw.externalOutputs.filter(row=> + row.physicalLeft===left&&row.physicalRight===left+1).length:0; + choices.push({label:"OUT "+(left+1)+"/"+(left+2)+" · "+ + a.label+" + "+b.label+ + (shared>1?" · SHARED "+shared+" SOURCES":""), + left,right:left+1}); + } + return choices; + } + // Project one installed row for the existing DOM. ACK-only and logical + // assignments never promote output status to LIVE; that still requires + // matching verified pins AND accepted native graph AND armed output. + function externalPresentation(snapshot,row,choices=outputChoices(snapshot)) { + const match=row&&choices.find(p=>p.left===row.physicalLeft && + p.right===row.physicalRight); + const installed=row?.status==="LIVE"&&match; + const state=installed?(snapshot?.device?.outputArmed===true?"LIVE":"MUTED"): + row?.status==="PENDING"&&match?"PENDING":row?"NEEDS_REMAP":"NONE"; + const value=row?((state==="LIVE"||state==="MUTED")?match.label: + (state==="PENDING"?"Pending · ":"Needs Remap · ")+ + "OUT "+(row.physicalLeft+1)+"/"+(row.physicalRight+1)):"None"; + const marker=state==="NONE"?"":state==="NEEDS_REMAP"?"REMAP":state; + const title=state==="PENDING"?"Native PCM pending · wait for audio callback": + state==="NEEDS_REMAP"? + "Saved physical output disarmed; choose a verified ASIO pair": + state==="MUTED"?"ASIO pair connected · output muted, settings retained": + state==="LIVE"?"LIVE · independent native post-fader PCM": + "None · internal WIRE remains unchanged"; + return {match,state,value,marker,title}; + } + + // Device Setup UI transaction: pure presentation only. The native + // coordinator remains the sole device apply/rollback and output authority. + // Never treat a successful ACK as installed hardware readback. + function setupInitial() { + return {phase:"IDLE",pending:null,message:"",remapGeneration:null}; + } + function setupBegin(state,{inventory,draft,requestId,baselineEpoch=null, + confirmRetainedPinMapping=false,assignMain=false}) { + if(state.pending||!inventory?.active||!draft|| + typeof requestId!=="string"||!requestId||requestId.length>64)return null; + const active=inventory.active; + const generation=active.deviceGeneration; + if(!Number.isSafeInteger(generation)||generation<0)return null; + const type=inventory.types?.find(x=>x.name===draft.backend); + if(!type||!draft.backend||!draft.playback|| + !type.outputs?.includes(draft.playback)|| + (!type.separate&&!type.inputs?.includes(draft.capture))|| + (type.separate&&draft.capture&&!type.inputs?.includes(draft.capture))|| + (!type.separate&&draft.capture!==draft.playback))return null; + const same=active.open===true&&active.backend===draft.backend&& + active.captureDevice===draft.capture&& + active.playbackDevice===draft.playback; + if(confirmRetainedPinMapping && + (!same||state.remapGeneration!==generation))return null; + if(assignMain&&(!same||draft.outputPins?.length!==2))return null; + const rate=confirmRetainedPinMapping?active.rate:same?draft.rate:0; + const buffer=confirmRetainedPinMapping?active.buffer:same?draft.buffer:0; + const request={action:"audioDeviceApply",requestId, + expectedDeviceGeneration:generation, + config:{backend:draft.backend,captureDevice:draft.capture, + playbackDevice:draft.playback,sampleRate:rate,bufferSize:buffer, + enabledInputs:same?draft.inputPins:[], + enabledOutputs:same?draft.outputPins:[], + ...(confirmRetainedPinMapping?{confirmRetainedPinMapping:true}:{}), + ...(assignMain?{assignSelectedPlaybackPinsToMain:true}:{})}}; + const pending={requestId,expected:{backend:draft.backend, + captureDevice:draft.capture,playbackDevice:draft.playback, + generation,rate,buffer},baselineEpoch: + typeof baselineEpoch==="string"&&/^(0|[1-9]\d*)$/.test(baselineEpoch)? + baselineEpoch:null,ack:null}; + return {request,state:{phase:"APPLYING",pending,message:"", + remapGeneration:null}}; + } + function setupAck(state,ack) { + if(!state.pending||ack?.requestId!==state.pending.requestId)return state; + const active=ack.active; + const accepted=ack.ok===true && + (ack.state==="ACCEPTED_LIVE"||ack.state==="ACCEPTED_MUTED") && + active?.open===true&&active.authorized===true&& + active.backend===state.pending.expected.backend&& + active.captureDevice===state.pending.expected.captureDevice&& + active.playbackDevice===state.pending.expected.playbackDevice&& + Number.isSafeInteger(active.deviceGeneration)&& + active.deviceGeneration>=state.pending.expected.generation&& + (state.pending.expected.rate===0||active.rate===state.pending.expected.rate)&& + (state.pending.expected.buffer===0||active.buffer===state.pending.expected.buffer)&& + Array.isArray(active.enabledInputs)&&Array.isArray(active.enabledOutputs)&& + active.enabledOutputs.length>=2&& + Number.isFinite(active.rate)&&active.rate>0&& + Number.isInteger(active.buffer)&&active.buffer>0; + if(accepted)return {...state,phase:"VERIFYING", + pending:{...state.pending,ack:{ + active:{backend:active.backend,captureDevice:active.captureDevice, + playbackDevice:active.playbackDevice,rate:active.rate, + buffer:active.buffer,enabledInputs:active.enabledInputs.slice(), + enabledOutputs:active.enabledOutputs.slice(), + deviceGeneration:active.deviceGeneration}, + mixerBound:ack.mixerBound===true,outputMuted:ack.outputMuted===true}}}; + const remap=ack.state==="NEEDS_REMAP"&&ack.canReusePins===true&& + active?.open===true&&active?.authorized===true&& + Number.isSafeInteger(active.deviceGeneration)? + active.deviceGeneration:null; + return {phase:ack.state==="RECOVERY_REQUIRED"?"RECOVERY_REQUIRED":"REJECTED", + pending:null,remapGeneration:remap, + message:ack.state==="NEEDS_REMAP"? + String(ack.error||"Playback unavailable").replace(/^NEEDS_REMAP:\s*/,""): + ack.state==="RESTORED_LIVE"||ack.state==="RESTORED_MUTED"? + "New device rejected · Previous device restored": + "Device rejected · "+String(ack.error||"native hardware readback failed")}; + } + function setupReadback(state,snapshot) { + if(state.phase!=="VERIFYING"||!state.pending?.ack)return state; + const d=snapshot?.device,expected=state.pending.ack.active; + const epoch=d?.epoch; + if(typeof epoch!=="string"||!/^(0|[1-9]\d*)$/.test(epoch))return state; + const baseline=state.pending.baselineEpoch; + // Old epoch and disconnected/replaced devices may never qualify an ACK. + if(baseline!==null&&BigInt(epoch)BigInt(baseline))) + return {phase:"RECOVERY_REQUIRED",pending:null,remapGeneration:null, + message:"Audio device unavailable · Previous mixer settings retained"}; + // Route epoch can advance AHEAD of the JUCE generation on STOP/START, + // but an old hardware snapshot cannot verify a later accepted Apply. + if(BigInt(epoch)Array.isArray(a)&&Array.isArray(b)&& + a.length===b.length&&a.every((n,i)=>n===b[i]); + const same=d.backend===expected.backend&& + d.captureDevice===expected.captureDevice&& + d.playbackDevice===expected.playbackDevice&& + d.sampleRate===expected.rate&&d.bufferFrames===expected.buffer&& + equalPins(d.enabledInputs,expected.enabledInputs)&& + equalPins(d.enabledOutputs,expected.enabledOutputs); + if(!same)return state; // The driver or graph may still be publishing. + // Physical device Apply is a distinct transaction from ChannelId PCM + // admission. Legacy M4/G0 can have a verified open driver without an + // admitted ChannelId graph; never trap Audio I/O behind a PCM claim. + const mixerVerified=snapshot.admitted===true; + const live=state.pending.ack.outputMuted===false&& + snapshot.admitted===true&&snapshot.productLive===true&& + d.outputArmed===true; + return {phase:"ACCEPTED",pending:null,remapGeneration:null, + message:live?"Mixer ready · Output live": + mixerVerified?"Mixer ready · Output muted": + "Audio device ready · Mixer route not yet verified"}; + } + function setupTimeout(state,requestId) { + if(!state.pending||state.pending.requestId!==requestId)return state; + return {phase:"TIMEOUT",pending:null,remapGeneration:null, + message:"Device verification timed out · Refresh Audio I/O; previous settings not confirmed"}; + } + function setupClearResult(state) { + if(state.pending)return state; + return {...state,phase:"IDLE",message:"",remapGeneration:null}; + } + return Object.freeze({activeInputPins,inputChoices,inputLabel,outputChoices, + externalPresentation,setupInitial,setupBegin,setupAck,setupReadback, + setupTimeout,setupClearResult}); +}); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index aceb91868..f93f3270a 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -4,10 +4,11 @@ "use strict"; const backend = window.__JUCE__?.backend; const protocol = window.ArSonApprovedNativeContract; + const deviceVM = window.ArSonApprovedDeviceViewModel; // The public GUI owns one lexical model. Native-only bundle exports a narrow // reference to that SAME model; never reconstruct a parallel DOM/DSP. const scope = window.__ARMIX_NATIVE_SCOPE__ || null; - const connected = Boolean(backend?.emitEvent && backend?.addEventListener && protocol); + const connected = Boolean(backend?.emitEvent && backend?.addEventListener && protocol && deviceVM); // Public browser preview keeps its header; the native JUCE caption replaces it. if (backend?.emitEvent && backend?.addEventListener) document.documentElement?.classList?.add?.("armix-native-desktop"); @@ -863,42 +864,14 @@ // The shipped /preview/ IN dropdown is the sole normal hardware source // selector. Build options exclusively from JUCE-reported active pins, never // the public browser demo's hardcoded "Input 1 / CABLE / Realtek" strings. - const hardwarePins=()=>Array.isArray(hardware?.device?.inputEndpoints)? - hardware.device.inputEndpoints.filter(p=>p.active===true && - Number.isInteger(p.port) && hardware.device.enabledInputs.includes(p.port)):[]; + // Native endpoint choices are projected by a pure, testable ViewModel. + // Only accepted JUCE pin readback may populate these selectors. // BUS is verified engine state, not an available hardware input choice. const INTERNAL_BUS="Internal BUS (read-only)"; const NEEDS_REMAP="Audio connection lost"; - const monoLabel=p=>"Mono · "+p.label+" [IN "+(p.port+1)+"]"; - const stereoLabel=(a,b)=>"Stereo · IN "+(a.port+1)+" + "+(b.port+1); // Only driver-verified even/odd physical pin pairs (not packed ordinals). // MAIN and MONITOR retain exclusive ownership of their actual pins. - const hardwareOutputPairs=()=>{ - const d=hardware?.device,choices=[{label:"None",left:-1,right:-1}]; - if(d?.backend!=="ASIO" || !Array.isArray(d.outputEndpoints) || - !Array.isArray(d.enabledOutputs))return choices; - const map=new Map(d.outputEndpoints.filter(p=> - p.active===true&&Number.isInteger(p.port)&& - d.enabledOutputs.includes(p.port)&& - typeof p.label==="string"&&p.label.length>0).map(p=>[p.port,p])); - const main=Array.isArray(hardware?.raw?.physicalMainOutputs)? - hardware.raw.physicalMainOutputs:[]; - const monitor=Array.isArray(hardware?.raw?.physicalMonitorOutputs)? - hardware.raw.physicalMonitorOutputs:[]; - for(const [left,a] of map) { - if(left%2!==0 || !map.has(left+1))continue; - const b=map.get(left+1); - if(main.includes(left)||main.includes(left+1)|| - monitor.includes(left)||monitor.includes(left+1))continue; - const shared=Array.isArray(hardware?.raw?.externalOutputs)? - hardware.raw.externalOutputs.filter(row=> - row.physicalLeft===left && row.physicalRight===left+1).length:0; - choices.push({label:"OUT "+(left+1)+"/"+(left+2)+" · "+ - a.label+" + "+b.label+(shared>1?" · SHARED "+shared+" SOURCES":""), - left,right:left+1}); - } - return choices; - }; + const hardwareOutputPairs=()=>deviceVM.outputChoices(hardware); const paintExternalReadback=(next)=>{ const assignments=Array.isArray(next?.raw?.externalOutputs)? next.raw.externalOutputs:[]; @@ -906,17 +879,9 @@ for(const t of scope?.tracks||[]) { const id=nativeIdFor(t); const row=assignments.find(p=>p.channelId===id); - const match=row&&choices.find(p=>p.left===row.physicalLeft && - p.right===row.physicalRight); - // Control ACK/applied graph is not audible LIVE while the verified - // hardware output is MUTED. Keep patch identity without ghost meters. - const pcmInstalled=row?.status==="LIVE"&&match; - const state=pcmInstalled?(next?.device?.outputArmed===true?"LIVE":"MUTED"): - row?.status==="PENDING"&&match?"PENDING": - row?"NEEDS_REMAP":"NONE"; - const value=row?((state==="LIVE"||state==="MUTED")?match.label: - (state==="PENDING"?"Pending · ":"Needs Remap · ")+ - "OUT "+(row.physicalLeft+1)+"/"+(row.physicalRight+1)):"None"; + // Native PCM/armed status is projected, never asserted by the DOM. + const projected=deviceVM.externalPresentation(next,row,choices); + const {state,value}=projected; t.externalOutput=value; const select=document.querySelector('.strip[data-id="'+t.id+ '"] select[data-field="external"]'); @@ -935,15 +900,10 @@ select.dataset.status=state; const marker=select.parentElement?.querySelector(".external-out-state"); if(marker){ - marker.textContent=state==="NONE"?"":state==="NEEDS_REMAP"?"REMAP":state; + marker.textContent=projected.marker; marker.dataset.status=state; } - select.title=state==="PENDING"?"Native PCM pending · wait for audio callback": - state==="NEEDS_REMAP"? - "Saved physical output disarmed; choose a verified ASIO pair": - state==="MUTED"?"ASIO pair connected · output muted, settings retained": - state==="LIVE"?"LIVE · independent native post-fader PCM": - "None · internal WIRE remains unchanged"; + select.title=projected.title; const pending=pendingExternal.get(id); if(pending && next?.device?.epoch && next.device.epoch!==pending.epoch) pendingExternal.delete(id); // stale device: release only this strip @@ -959,25 +919,8 @@ if(!pendingExternal.has(id))select.removeAttribute("aria-busy"); } }; - const inputChoicesFor=()=>{ - const pins=hardwarePins(),entries=[{label:"None",mode:"NONE",left:-1,right:-1}]; - for(const p of pins)entries.push({ - label:monoLabel(p),mode:"MONO",left:p.port,right:-1}); - // Expose real adjacent physical stereo pairs, never guess disabled pins. - for(let i=0;i+1{ - if(!row||row.mode==="NONE")return "None"; - if(row.mode==="BUS")return INTERNAL_BUS; - const entries=inputChoicesFor(); - const exact=entries.find(x=>x.mode===row.mode && - x.left===row.left && x.right===row.right); - return exact?.label||"None"; - }; + const inputChoicesFor=()=>deviceVM.inputChoices(hardware); + const inputLabelFor=row=>deviceVM.inputLabel(hardware,row); // ChannelId and the existing M4 use the SAME ten native input ordinals. // GUI track reorder must never silently repatch a different physical lane. const m4TrackIds=Array.isArray(scope?.tracks)? @@ -2086,9 +2029,9 @@ // Compact DAW-style device preferences INSIDE the approved Windows GUI. // Only the existing AudioDeviceManager inventory/APPLY API is used. This // replaces the 740x590 default JUCE dialog for normal operator setup. - let devicePanel=null,deviceInventory=null,deviceBusy=false, - deviceRequest=0,deviceChoice=null,deviceResult="", - offeredPinRemap=null; + let devicePanel=null,deviceInventory=null,deviceChoice=null,deviceRequest=0, + deviceState=deviceVM.setupInitial(),deviceApplyTimer=0; + const deviceBusy=()=>Boolean(deviceState.pending); let toastTimer=0; function nativeToast(message){ let element=document.getElementById("armixNativeToast"); @@ -2208,15 +2151,14 @@ `; devicePanel.querySelector("[data-audio-close]").onclick=()=>{ - if(!deviceBusy)devicePanel.hidden=true; + if(!deviceBusy())devicePanel.hidden=true; }; devicePanel.addEventListener("click",e=>{ - if(e.target===devicePanel&&!deviceBusy)devicePanel.hidden=true; + if(e.target===devicePanel&&!deviceBusy())devicePanel.hidden=true; }); devicePanel.addEventListener("change",e=>{ if(!deviceChoice)return; - offeredPinRemap=null; - deviceResult=""; + deviceState=deviceVM.setupClearResult(deviceState); const pinSide=e.target.dataset.audioPin; if(pinSide==="input"||pinSide==="output"){ const index=Number(e.target.dataset.pinIndex); @@ -2249,27 +2191,26 @@ renderDevicePanel(); }); devicePanel.querySelector("[data-audio-apply]").onclick=()=>{ - if(deviceBusy||!deviceChoice||!deviceInventory?.active)return; + if(deviceBusy()||!deviceChoice||!deviceInventory?.active)return; const draft=deviceChoice,active=deviceInventory.active; const separate=deviceInventory.types?.find(x=>x.name===draft.backend)?.separate===true; if(!draft.backend||!draft.playback||(!separate&&!draft.capture))return; sendDeviceApply(); }; devicePanel.querySelector("[data-audio-main-pins]").onclick=()=>{ - if(!deviceBusy)sendDeviceApply(false,true); + if(!deviceBusy())sendDeviceApply(false,true); }; devicePanel.querySelector("[data-audio-remap]").onclick=()=>{ - if(!deviceBusy && offeredPinRemap!==null) + if(!deviceBusy() && deviceState.remapGeneration!==null) sendDeviceApply(true); }; document.body.appendChild(devicePanel); } devicePanel.hidden=false; paintPhysicalOutputs(hardware); - if(deviceBusy)return; + if(deviceBusy())return; const active=devicePanel.querySelector("[data-audio-active]"); - deviceResult=""; - offeredPinRemap=null; + deviceState=deviceVM.setupClearResult(deviceState); if(active)active.textContent="Reading verified audio devices…"; backend.emitEvent("arMixAction",{action:"audioDeviceInventory"}); } @@ -2284,7 +2225,7 @@ return option; })); if(values.includes(current))el.value=current; - el.disabled=deviceBusy; + el.disabled=deviceBusy(); } function renderDevicePanel(){ if(!devicePanel||devicePanel.hidden||!deviceInventory)return; @@ -2319,8 +2260,8 @@ fillAudioSelect("buffer",["0",...buffers.map(String)],String(deviceChoice.buffer||0)); const rateSelect=devicePanel.querySelector('[data-audio-field="rate"]'); const bufferSelect=devicePanel.querySelector('[data-audio-field="buffer"]'); - if(rateSelect){rateSelect.options[0].textContent="Driver default";rateSelect.disabled=!same||deviceBusy;} - if(bufferSelect){bufferSelect.options[0].textContent="Driver default";bufferSelect.disabled=!same||deviceBusy;} + if(rateSelect){rateSelect.options[0].textContent="Driver default";rateSelect.disabled=!same||deviceBusy();} + if(bufferSelect){bufferSelect.options[0].textContent="Driver default";bufferSelect.disabled=!same||deviceBusy();} const pins=document.querySelector(".armix-audio-dialog [data-audio-pins]"); if(pins){ pins.replaceChildren(); @@ -2340,7 +2281,7 @@ control.type="checkbox";control.dataset.audioPin=side; control.dataset.pinIndex=String(index); control.checked=(deviceChoice[key]||enabled||[]).includes(index); - control.disabled=deviceBusy; + control.disabled=deviceBusy(); label.append(control,document.createTextNode(String(name))); group.appendChild(label); }); @@ -2352,19 +2293,19 @@ const activeText=devicePanel.querySelector("[data-audio-active]"); const mainPins=Array.isArray(active.mainOutputs)?active.mainOutputs .map(pin=>active.outputNames?.[pin]).filter(Boolean):[]; - if(activeText && !deviceBusy)activeText.textContent=deviceResult||(active.open? + if(activeText && !deviceBusy())activeText.textContent=deviceState.message||(active.open? "ACTIVE · "+active.backend+" · "+active.rate+" Hz / "+active.buffer+" samples"+ (mainPins.length===2?" · MAIN "+mainPins.join(" / "):""): "No verified audio device. Select a supported input and output."); - devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| + devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy()|| !deviceChoice.backend||(!t?.separate&&!deviceChoice.capture)|| !deviceChoice.playback; const assignMain=devicePanel.querySelector("[data-audio-main-pins]"); assignMain.hidden=!same || deviceChoice.outputPins?.length!==2; - assignMain.disabled=deviceBusy; + assignMain.disabled=deviceBusy(); const remap=devicePanel.querySelector("[data-audio-remap]"); - remap.hidden=!same || offeredPinRemap!==active.deviceGeneration; - remap.disabled=deviceBusy; + remap.hidden=!same || deviceState.remapGeneration!==active.deviceGeneration; + remap.disabled=deviceBusy(); remap.title="Reuse existing input and output pin numbers on the selected device. MONITOR stays off."; } function showDeviceApplyProgress(pending){ @@ -2382,76 +2323,75 @@ }else svg.pauseAnimations?.(); } function sendDeviceApply(confirmRetainedPinMapping=false,assignMain=false){ - if(deviceBusy||!deviceChoice||!deviceInventory?.active)return; - const c=deviceChoice,a=deviceInventory.active; - const same=a.open&&a.backend===c.backend&& - a.captureDevice===c.capture&&a.playbackDevice===c.playback; - if(confirmRetainedPinMapping && (!same || offeredPinRemap!==a.deviceGeneration))return; - if(assignMain && (!same || c.outputPins?.length!==2))return; - deviceBusy=true; + if(deviceBusy()||!deviceChoice||!deviceInventory?.active)return; const requestId="approved-io-"+(++deviceRequest); - devicePanel.dataset.pendingRequest=requestId; + const begun=deviceVM.setupBegin(deviceState,{ + inventory:deviceInventory,draft:deviceChoice,requestId, + baselineEpoch:hardware?.device?.epoch, + confirmRetainedPinMapping,assignMain}); + if(!begun)return; + deviceState=begun.state; showDeviceApplyProgress(true); renderDevicePanel(); - const request={action:"audioDeviceApply", - requestId,expectedDeviceGeneration:Number(a.deviceGeneration), - config:{backend:c.backend,captureDevice:c.capture, - playbackDevice:c.playback, - sampleRate:confirmRetainedPinMapping?a.rate:same?c.rate:0, - bufferSize:confirmRetainedPinMapping?a.buffer:same?c.buffer:0, - enabledInputs:same?c.inputPins:[], - enabledOutputs:same?c.outputPins:[], - ...(confirmRetainedPinMapping?{confirmRetainedPinMapping:true}:{}), - ...(assignMain?{assignSelectedPlaybackPinsToMain:true}:{})}}; - // Give WebView a paint before the native driver open can block JUCE. - // The fallback also submits when animation frames are throttled. + // Reuse the ONLY native arMixAction dispatcher. UI state cannot touch PCM. + // Allow WebView to paint before a blocking driver dialog, with one fallback. let submitted=false; const submit=()=>{ if(submitted)return; submitted=true; window.clearTimeout(fallback); - backend.emitEvent("arMixAction",request); + backend.emitEvent("arMixAction",begun.request); }; const fallback=window.setTimeout(submit,120); window.requestAnimationFrame(()=>window.requestAnimationFrame(submit)); + window.clearTimeout(deviceApplyTimer); + deviceApplyTimer=window.setTimeout(()=>{ + const previous=deviceState; + deviceState=deviceVM.setupTimeout(deviceState,requestId); + if(deviceState===previous)return; // expired / unrelated request + finishDeviceApplyUi(); + controller?.subscribe(); // authoritative current state, not retry Apply + backend.emitEvent("arMixAction",{action:"audioDeviceInventory"}); + },12000); + } + function finishDeviceApplyUi(){ + window.clearTimeout(deviceApplyTimer); + deviceApplyTimer=0; + if(!devicePanel)return; + showDeviceApplyProgress(false); + if(deviceState.phase==="ACCEPTED"){ + deviceChoice=null; + devicePanel.hidden=true; + const active=deviceInventory?.active; + status("DEVICE READY · "+String(active?.backend||"Audio")+ + " · "+String(active?.rate||0)+" Hz / "+String(active?.buffer||0)+" samples"); + nativeToast(deviceState.message); + }else{ + deviceChoice=null; + renderDevicePanel(); + if(deviceState.phase==="RECOVERY_REQUIRED"||deviceState.phase==="STALE") + nativeToast(deviceState.message); + } } if(connected){ backend.addEventListener("arMixAudioDeviceInventory",inventory=>{ - if(!inventory||!Array.isArray(inventory.types))return; + if(!inventory||!Array.isArray(inventory.types)||deviceBusy())return; + // Inventory is a native observation, not accepted Apply proof. deviceInventory=inventory; - if(!deviceBusy)deviceChoice=null; + deviceChoice=null; renderDevicePanel(); }); backend.addEventListener("arMixAudioDeviceApplyAck",ack=>{ - if(!devicePanel||!deviceBusy||ack?.requestId!==devicePanel.dataset.pendingRequest)return; - deviceBusy=false; - delete devicePanel.dataset.pendingRequest; - showDeviceApplyProgress(false); - if(ack.active)deviceInventory.active=ack.active; - offeredPinRemap=ack.state==="NEEDS_REMAP" && ack.canReusePins===true && - ack.active?.open===true && ack.active?.authorized===true && - Number.isSafeInteger(ack.active.deviceGeneration)? - ack.active.deviceGeneration:null; - const accepted=ack.ok===true&&["ACCEPTED_LIVE","ACCEPTED_MUTED"].includes(ack.state) && - ack.active?.open===true && ack.active?.authorized===true && - Array.isArray(ack.active.enabledInputs) && - Array.isArray(ack.active.enabledOutputs) && - ack.active.enabledOutputs.length>=2; - const outputReady=ack.outputMuted===false; - deviceResult=accepted? - (outputReady?"Mixer ready · Output live": - ack.mixerBound?"Mixer ready · FX/WIRE available":"Audio device ready · no hardware input required"): - ack.state==="NEEDS_REMAP"? - String(ack.error||"Playback unavailable").replace(/^NEEDS_REMAP:\s*/,""): - "Device rejected · "+(ack.error||"native hardware readback failed"); - deviceChoice=null; - if(accepted){ - devicePanel.hidden=true; - status("DEVICE READY · "+ack.active.backend+" · "+ - ack.active.rate+" Hz / "+ack.active.buffer+" samples"); - nativeToast(deviceResult); + if(!devicePanel)return; + const next=deviceVM.setupAck(deviceState,ack); + if(next===deviceState)return; // delayed or unrelated ACK + deviceState=next; + if(ack?.active && deviceInventory) + deviceInventory={...deviceInventory,active:ack.active}; + if(deviceBusy()){ + // ACK alone NEVER closes the dialog or announces LIVE. controller?.subscribe(); - }else renderDevicePanel(); + }else finishDeviceApplyUi(); }); } @@ -2809,6 +2749,11 @@ function onNativeReadback(next,confirmed) { scope?.syncNativeWireGains?.([]); // flush accepted paint after pointer release appearanceFromNative(next); + // This callback is invoked only by the existing schema-v6 reconciler. + // A correlated Apply ACK waits for a subsequent installed PCM snapshot. + const previousSetup=deviceState; + deviceState=deviceVM.setupReadback(deviceState,next); + if(deviceState!==previousSetup && !deviceState.pending)finishDeviceApplyUi(); updateHardwarePanel(next); paintExternalReadback(next); // The installed native SessionSnapshot selects exactly one UI authority.