diff --git a/tests/approved_device_pin_identity_contract.test.cjs b/tests/approved_device_pin_identity_contract.test.cjs index 3893655ba..986b93824 100644 --- a/tests/approved_device_pin_identity_contract.test.cjs +++ b/tests/approved_device_pin_identity_contract.test.cjs @@ -4,6 +4,13 @@ const test=require("node:test"); const assert=require("node:assert/strict"); const {readFileSync}=require("node:fs"); const vm=require("../web/approved-device-view-model.js"); +const protocol=require("../web/approved-native-contract.js"); +// The v6 controller is the only normalizer of installed physical identity. +// Minimal VM fixtures explicitly reuse that canonical read-only fingerprint. +const lease=(snapshot,kind)=>vm.nativeLifecycleLease({ + ...snapshot, + hardwareConfiguration:protocol.nativeHardwareConfiguration(snapshot?.device) +},kind); function fixture(){ const active={ @@ -172,41 +179,46 @@ test("MV-8 DeviceVM remains pure; exactly one unchanged native Apply transport", test("MV-12 native lifecycle lease preserves exact uint64 device identity",()=>{ const base={device:{epoch:"18446744073709551615",backend:"ASIO", - captureDevice:"A",playbackDevice:"A"},graph:{revision:"9"}}; + captureDevice:"A",playbackDevice:"A",sampleRate:48000,bufferFrames:256, + enabledInputs:[1,0],enabledOutputs:[0,1]},graph:{revision:"9"}}; const original=JSON.stringify(base); - const lease=vm.nativeLifecycleLease(base,"CHANNEL_ID"); - assert.deepEqual(lease,{epoch:"18446744073709551615",backend:"ASIO", - captureDevice:"A",playbackDevice:"A",authority:"CHANNEL_ID"}); - assert.equal(Object.isFrozen(lease),true); + const identityLease=lease(base,"CHANNEL_ID"); + assert.deepEqual(identityLease,{epoch:"18446744073709551615",backend:"ASIO", + captureDevice:"A",playbackDevice:"A", + hardwareConfiguration:JSON.stringify([48000,256,[0,1],[0,1]]), + authority:"CHANNEL_ID"}); + assert.equal(Object.isFrozen(identityLease),true); assert.equal(JSON.stringify(base),original); for(const epoch of [18446744073709551615,"01","-1","1.5","", "18446744073709551616",null]) { - assert.equal(vm.nativeLifecycleLease({...base, + assert.equal(lease({...base, device:{...base.device,epoch}},"CHANNEL_ID"),null, "rounding, overflow and noncanonical epoch must fail closed"); } for(const kind of ["INVALID","DEMO","",null]) - assert.equal(vm.nativeLifecycleLease(base,kind),null); - assert.equal(vm.nativeLifecycleLease({device:{...base.device, + assert.equal(lease(base,kind),null); + assert.equal(lease({device:{...base.device, captureDevice:undefined}},"CHANNEL_ID"),null); }); test("MV-12 native lifecycle expires old device intents even when both graphs are admitted",()=>{ const s=(epoch="41",backend="ASIO",name="Studio ASIO")=> - ({device:{epoch,backend,captureDevice:name,playbackDevice:name}}); - const first=vm.nativeLifecycleLease(s(),"CHANNEL_ID"); - const same=vm.nativeLifecycleLease({...s(),graph:{revision:"500", + ({device:{epoch,backend,captureDevice:name,playbackDevice:name, + sampleRate:48000,bufferFrames:256, + enabledInputs:[0,1],enabledOutputs:[0,1]}}); + const first=lease(s(),"CHANNEL_ID"); + const same=lease({...s(),graph:{revision:"500", rosterRevision:"700"}},"CHANNEL_ID"); assert.deepEqual(vm.nativeLifecycleDecision(null,first), {kind:"INITIAL",expirePending:false}); assert.deepEqual(vm.nativeLifecycleDecision(first,same), {kind:"SAME",expirePending:false}, "graph/roster revisions and scalar telemetry cannot cancel same-device gestures"); - const afterReconnect=vm.nativeLifecycleLease(s("42"),"CHANNEL_ID"); + const afterReconnect=lease(s("42"),"CHANNEL_ID"); assert.deepEqual(vm.nativeLifecycleDecision(first,afterReconnect), {kind:"DEVICE_CHANGED",expirePending:true}, "back-to-back admitted PCM snapshots must still invalidate old leases"); - const otherDriver=vm.nativeLifecycleLease(s("41","ASIO","Backup ASIO"),"CHANNEL_ID"); + const otherDriver=lease(s("41","ASIO","Backup ASIO"),"CHANNEL_ID"); assert.equal(vm.nativeLifecycleDecision(first,otherDriver).kind,"DEVICE_CHANGED", "same-epoch endpoint replacement is never the old physical owner"); assert.equal(vm.nativeLifecycleDecision(first,{...first, @@ -216,8 +228,9 @@ test("MV-12 native lifecycle expires old device intents even when both graphs ar test("MV-12 authority transitions expire stale M4/ChannelId work; no duplicate owner",()=>{ const snapshot={device:{epoch:"91",backend:"ASIO", - captureDevice:"One",playbackDevice:"One"}}; - const mk=kind=>vm.nativeLifecycleLease(snapshot,kind); + captureDevice:"One",playbackDevice:"One",sampleRate:48000, + bufferFrames:256,enabledInputs:[0,1],enabledOutputs:[0,1]}}; + const mk=kind=>lease(snapshot,kind); for(const [a,b] of [["M4","CHANNEL_ID"],["CHANNEL_ID","NEEDS_REMAP"], ["NEEDS_REMAP","CHANNEL_ID"],["LOGICAL_ONLY","CHANNEL_ID"], ["CHANNEL_ID","UNADMITTED"],["STALE","CHANNEL_ID"]]) { @@ -229,7 +242,7 @@ test("MV-12 authority transitions expire stale M4/ChannelId work; no duplicate o "first accepted M4 input must not silently discard its own pending source"); const switched={device:{...snapshot.device,epoch:"92"}}; assert.deepEqual(vm.nativeLifecycleDecision(mk("UNADMITTED"), - vm.nativeLifecycleLease(switched,"M4")), + lease(switched,"M4")), {kind:"DEVICE_CHANGED",expirePending:true}, "first-sound exemption must never bypass a physical device change"); for(const kind of ["M4","CHANNEL_ID","LOGICAL_ONLY","NEEDS_REMAP", @@ -244,9 +257,10 @@ test("MV-12 authority transitions expire stale M4/ChannelId work; no duplicate o test("MV-18 physical device swap cancels output and FX leases even at unchanged epoch",()=>{ const snapshot=(backend,capture,playback)=>({device:{ epoch:"18446744073709551614",backend,captureDevice:capture, - playbackDevice:playback}}); - const old=vm.nativeLifecycleLease(snapshot("ASIO","Old ASIO","Old ASIO"),"M4"); - const changed=vm.nativeLifecycleLease(snapshot("ASIO","New ASIO","New ASIO"),"M4"); + playbackDevice:playback,sampleRate:48000,bufferFrames:256, + enabledInputs:[0,1],enabledOutputs:[0,1]}}); + const old=lease(snapshot("ASIO","Old ASIO","Old ASIO"),"M4"); + const changed=lease(snapshot("ASIO","New ASIO","New ASIO"),"M4"); assert.deepEqual(vm.nativeLifecycleDecision(old,changed), {kind:"DEVICE_CHANGED",expirePending:true}, "a driver can change even if the epoch was reused"); @@ -255,7 +269,7 @@ test("MV-18 physical device swap cancels output and FX leases even at unchanged assert.deepEqual(vm.nativeLifecycleDecision(old,old), {kind:"SAME",expirePending:false}); assert.deepEqual(vm.nativeLifecycleDecision( - vm.nativeLifecycleLease(snapshot("ASIO","Old ASIO","Old ASIO"),"UNADMITTED"), + lease(snapshot("ASIO","Old ASIO","Old ASIO"),"UNADMITTED"), old),{kind:"M4_FIRST_SOUND",expirePending:false}, "first M4 input patch must preserve its own pending source"); const bridge=readFileSync("web/approved-native-bridge.js","utf8"); @@ -267,6 +281,54 @@ test("MV-18 physical device swap cancels output and FX leases even at unchanged "UI cleanup cannot send native commands, reset FX, or reopen devices"); }); +test("G-MV20 same-epoch native hardware remap invalidates transient GUI leases",()=>{ + const snapshot=(overrides={})=>({device:{ + epoch:"18446744073709551614",backend:"ASIO", + captureDevice:"Studio ASIO",playbackDevice:"Studio ASIO", + sampleRate:48000,bufferFrames:256, + enabledInputs:[0,2],enabledOutputs:[0,1,4,5], + outputArmed:false,...overrides}}); + const base=snapshot(),before=JSON.stringify(base); + const old=lease(base,"M4"); + assert.ok(old); + for(const changes of [ + {enabledInputs:[0,1]}, // physically different capture pins + {enabledOutputs:[0,1]}, // hardware output pair disappeared + {sampleRate:44100}, + {bufferFrames:512} + ]) { + const next=lease(snapshot(changes),"M4"); + assert.deepEqual(vm.nativeLifecycleDecision(old,next), + {kind:"DEVICE_CHANGED",expirePending:true}, + "stale FX, input/output, and WIRE intents must not cross "+JSON.stringify(changes)); + } + const reordered=lease(snapshot({ + enabledInputs:[2,0],enabledOutputs:[5,4,1,0], + outputArmed:true}),"M4"); + assert.equal(reordered.hardwareConfiguration,old.hardwareConfiguration); + assert.deepEqual(vm.nativeLifecycleDecision(old,reordered), + {kind:"SAME",expirePending:false}, + "pin enumeration/monitor outputArmed must not reset current gestures"); + assert.deepEqual(vm.nativeLifecycleDecision( + lease(snapshot({outputArmed:false}),"UNADMITTED"),reordered), + {kind:"M4_FIRST_SOUND",expirePending:false}, + "first route must preserve queued second input on unchanged hardware"); + assert.deepEqual(vm.nativeLifecycleDecision( + lease(snapshot({enabledInputs:[0,1]}),"UNADMITTED"),reordered), + {kind:"DEVICE_CHANGED",expirePending:true}, + "first-sound exemption must not keep a source from a different pin mask"); + assert.equal(JSON.stringify(base),before,"no native snapshot mutation"); + for(const bad of [ + {enabledInputs:[0,0]},{enabledOutputs:[0,256]}, + {enabledInputs:[0,"2"]},{sampleRate:NaN}, + {bufferFrames:1.5},{enabledOutputs:null},{sampleRate:undefined} + ])assert.equal(lease(snapshot(bad),"M4"),null, + "incomplete or malformed hardware identity must fail closed"); + const bridge=readFileSync("web/approved-native-bridge.js","utf8"); + assert.match(bridge,/deviceVM\.nativeLifecycleDecision\(lastNativeLifecycleLease,lease\)/); + assert.match(bridge,/if\(lifecycle\.expirePending\)\s*\{\s*expireTransientNativeUi\(lifecycle\.kind\)/); +}); + test("MV-19 invalid read-model and malformed device identity cannot mutate hardware UI",()=>{ const bridge=readFileSync("web/approved-native-bridge.js","utf8"); const readbackStart=bridge.indexOf(" function onNativeReadback(next,confirmed) {"); diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index ffcd82b96..ce85b2011 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -13,6 +13,89 @@ const fixtures=JSON.parse(read("integration/console-v6/fixtures.json")); const clone=x=>JSON.parse(JSON.stringify(x)); +// A real admitted v6 snapshot needs MAIN identity and an installed graph. +// The repository's g2 fixture is intentionally a partial graph source. +function gmv20AcceptedGraph() { + const fixture=clone(fixtures.g2); + fixture.graph.mainChannelId="200"; + // The illustrative g2 inserts predate accepted catalog identities. + for(const channel of fixture.graph.channels) + for(const fx of channel.inserts||[])fx.catalogId="fixture.catalog."+fx.id; + fixture.graph.edges=[["7","100"],["2","100"],["100","200"], + ["101","200"]].map(([from,to],i)=>({ + edgeId:String(i+1),from,to,signalKind:"AUDIO", + gainLinear:1,enabled:true,primaryOutput:true + })); + return fixture; +} + +test("G-MV20 schema-v6 pending intent is fenced on same-epoch physical pin or format change",()=>{ + const base=gmv20AcceptedGraph(),before=JSON.stringify(base); + const hardware=protocol.nativeHardwareConfiguration(base.device); + assert.equal(hardware,JSON.stringify([48000,128,[0,1],[0,1,2,3]])); + const normalized=protocol.normalizeSnapshot(base); + assert.equal(normalized.hardwareConfiguration,hardware); + const staleAck=(requestId)=>({ + requestId,status:"ACCEPTED",errorCode:"NONE",deviceEpoch:"69", + graphRevision:"5",rosterRevision:"5" + }); + for(const kind of ["input-mask","output-mask","rate","buffer"]){ + const sent=[],accepted=[]; + const controller=protocol.createController({ + emit:(name,payload)=>sent.push({name,payload}), + onAccepted:(next,confirmed)=>accepted.push({next,confirmed}) + }); + assert.equal(controller.onSnapshot(base),true); + assert.equal(accepted.length,1); + const issued=controller.intent("SET_FADER","7",{valueDb:-6}); + assert.equal(issued.ok,true); + const changed=clone(base); + if(kind==="input-mask"){ + changed.device.enabledInputs=[0]; + changed.device.inputEndpoints=changed.device.inputEndpoints.filter(p=>p.port===0); + }else if(kind==="output-mask"){ + changed.device.enabledOutputs=[0,1]; + changed.device.outputEndpoints=changed.device.outputEndpoints.filter(p=>p.port<2); + }else if(kind==="rate")changed.device.sampleRate=44100; + else changed.device.bufferFrames=256; + assert.equal(controller.onSnapshot(changed),true,kind); + assert.equal(controller.state().pending,null, + "physical remap must cancel old native pending intent: "+kind); + assert.equal(controller.state().lastError,"STALE_DEVICE"); + assert.equal(accepted.length,2, + "new physical config must repaint from native even before an old ACK: "+kind); + assert.notEqual(accepted[1].next.hardwareConfiguration,hardware); + assert.equal(accepted[1].confirmed,undefined,"no ACK-only or false PCM success"); + assert.equal(controller.onAck(staleAck(issued.requestId)),false, + "old ACK must not settle the replaced hardware configuration"); + assert.equal(controller.state().pending,null); + assert.equal(controller.state().current.hardwareConfiguration, + accepted[1].next.hardwareConfiguration); + assert.equal(sent.filter(x=>x.name==="arMixConsoleIntent").length,1, + "new hardware readback cannot silently redispatch an old edit"); + } + assert.equal(JSON.stringify(base),before,"native fixture cannot be mutated"); +}); + +test("G-MV20 pin order and MONITOR are not a new hardware owner",()=>{ + const base=gmv20AcceptedGraph(),seen=[]; + const c=protocol.createController({emit(){}, + onAccepted:next=>seen.push(next)}); + assert.equal(c.onSnapshot(base),true); + const issued=c.intent("SET_FADER","7",{valueDb:-6}); + assert.equal(issued.ok,true); + const rearranged=clone(base); + rearranged.device.enabledInputs.reverse(); + rearranged.device.enabledOutputs.reverse(); + rearranged.device.outputArmed=!base.device.outputArmed; + assert.equal(c.onSnapshot(rearranged),true); + assert.equal(c.state().pending?.requestId,issued.requestId, + "reordering physical pin sets must preserve a valid pending channel edit"); + assert.equal(seen.length,1,"unacknowledged operation does not repaint"); + assert.equal(protocol.nativeHardwareConfiguration(rearranged.device), + protocol.nativeHardwareConfiguration(base.device)); +}); + // GUI-4: SOURCE ONLY and physical PRIMARY OUT must not consume a parallel SEND. @@ -2511,7 +2594,8 @@ test("P0 output-only Audio I/O is a real native configuration, never blocked by }); -test("MV-18 real M4 FX slot lease survives no old device ACK on same-epoch driver switch",()=>{ +for(const scenario of ["driver","pin-mask"]) test( + "G-MV20 M4 pending slot FX remains fenced across same-epoch "+scenario+" remap",()=>{ const vm=require("node:vm"),listeners=new Map(),sent=[],timers=[],microtasks=[]; const tracks=Array.from({length:10},(_,i)=>({id:i+1,kind:"audio", name:"CH "+(i+1),input:"None",output:"Master",format:"mono", @@ -2617,20 +2701,26 @@ test("MV-18 real M4 FX slot lease survives no old device ACK on same-epoch drive assert.equal(click(),true); assert.equal(bypasses().length,1, "invalid candidate cannot release the pending physical FX lease"); - // A different VALID driver using the SAME epoch must expire the old slot lease. + // Different actual pins OR a different driver on the SAME epoch expires + // only the old UI lease; native instances are still readback-owned. const changed=clone(installed); - changed.device.captureDevice="Vendor B ASIO"; - changed.device.playbackDevice="Vendor B ASIO"; + if(scenario==="driver"){ + changed.device.captureDevice="Vendor B ASIO"; + changed.device.playbackDevice="Vendor B ASIO"; + }else{ + changed.device.enabledInputs=[0]; + changed.device.inputEndpoints=changed.device.inputEndpoints.filter(p=>p.port===0); + } changed.legacyM4.routingRevision="14"; changed.mixerSession.routeRevision="14"; publish(changed); while(microtasks.length)microtasks.shift()(); assert.equal(click(),true); assert.equal(bypasses().length,2, - "reconnected same-epoch driver cannot leave a slot uneditable for 5 seconds"); + "reconfigured hardware cannot leave a slot uneditable for 5 seconds"); const second=bypasses()[1]; assert.notEqual(first.requestId,second.requestId); - assert.equal(second.revision,14,"second bypass uses new accepted native revision"); + assert.equal(second.revision,14,"second bypass uses the newly accepted routing revision"); listeners.get("arMixRoutingFxBypassAck")({ requestId:first.requestId,channel:4,slot:0,ok:false,error:"OLD_DEVICE"}); oldTimer.fn(); diff --git a/web/approved-device-view-model.js b/web/approved-device-view-model.js index e263d650a..615dbf2af 100644 --- a/web/approved-device-view-model.js +++ b/web/approved-device-view-model.js @@ -357,6 +357,9 @@ return {...state,phase:"IDLE",message:"",remapGeneration:null}; } + // G-MV20: native schema-v6 normalizer publishes the *single* canonical + // installed pin/format fingerprint. DeviceVM consumes that read-only token; + // it must not independently calculate a competing physical identity. // MV-12: one pure identity fence for transient WebView control requests. // This is NOT a physical device manager or second native controller. A // ChannelId graph can be readmitted directly after a device switch without @@ -366,17 +369,20 @@ const d=snapshot?.device,epoch=d?.epoch; const kinds=["CHANNEL_ID","M4","NEEDS_REMAP","LOGICAL_ONLY", "UNADMITTED","STALE"]; + const hardwareConfiguration=snapshot?.hardwareConfiguration; if(!kinds.includes(readModelKind) || typeof epoch!=="string" || !/^(0|[1-9]\d*)$/.test(epoch) || epoch.length>20 || BigInt(epoch)>18446744073709551615n || typeof d.backend!=="string" || typeof d.captureDevice!=="string" || - typeof d.playbackDevice!=="string")return null; - // Store only physical identity and the canonical read-model authority. - // Never copy a native graph, device controller, DOM or PCM into the VM. + typeof d.playbackDevice!=="string" || + typeof hardwareConfiguration!=="string"|| + !hardwareConfiguration)return null; + // Store only physical identity/format and canonical read-model authority. + // Never copy a graph, mutable pin array, DOM, PCM or device controller. return Object.freeze({epoch,backend:d.backend, captureDevice:d.captureDevice,playbackDevice:d.playbackDevice, - authority:readModelKind}); + hardwareConfiguration,authority:readModelKind}); } function nativeLifecycleDecision(previous,next) { if(!next || typeof next.epoch!=="string" || @@ -387,7 +393,8 @@ const changed=previous.epoch!==next.epoch || previous.backend!==next.backend || previous.captureDevice!==next.captureDevice || - previous.playbackDevice!==next.playbackDevice; + previous.playbackDevice!==next.playbackDevice || + previous.hardwareConfiguration!==next.hardwareConfiguration; if(changed) return Object.freeze({kind:"DEVICE_CHANGED",expirePending:true}); // The very first accepted M4 physical SOURCE patch promotes an already diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 815107025..e5f1bbc5c 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -18,6 +18,22 @@ const fields = (item, names) => object(item) && names.every(key => Object.prototype.hasOwnProperty.call(item, key)); const isBool = x => typeof x === "boolean"; const unique = values => new Set(values).size === values.length; + // G-MV20: ONE canonical installed-hardware fingerprint for both the v6 + // ACK/readback controller and GUI lifecycle ViewModel. Pin masks are SETS: + // enumeration order and MONITOR/outputArmed are deliberately excluded. + // No driver name, PCM state, mutable pin array or graph revision is copied. + function nativeHardwareConfiguration(d) { + if(!object(d)||!Number.isFinite(d.sampleRate)||d.sampleRate<0|| + !Number.isSafeInteger(d.bufferFrames)||d.bufferFrames<0|| + !Array.isArray(d.enabledInputs)||!Array.isArray(d.enabledOutputs)|| + ![d.enabledInputs,d.enabledOutputs].every(pins=> + pins.length<=256&&pins.every(pin=> + Number.isInteger(pin)&&pin>=0&&pin<=255)&&unique(pins))) + return null; + const canonical=pins=>pins.slice().sort((a,b)=>a-b); + return JSON.stringify([d.sampleRate,d.bufferFrames, + canonical(d.enabledInputs),canonical(d.enabledOutputs)]); + } // Pure native UI presentation policy: no DOM, physical status rewrite, // optimistically accepted graph or alternative mixer renderer. const validPresentationName=name=>typeof name==="string"&&name.length>0&&name.length<=30&& @@ -85,6 +101,8 @@ !Array.isArray(caps.supportedOps) || !caps.supportedOps.every(s => typeof s === "string")) return null; const enabled = arr => unique(arr) && arr.every(n => Number.isInteger(n) && n >= 0 && n <= 255); if (!enabled(d.enabledInputs) || !enabled(d.enabledOutputs)) return null; + const hardwareConfiguration=nativeHardwareConfiguration(d); + if(hardwareConfiguration===null)return null; // Physical endpoint numbers are safe *port indices*; graph ChannelIds are never numbers. const goodEndpoints = (entries,pins,prefix) => entries.every(e => object(e) && Number.isInteger(e.port) && pins.includes(e.port) && @@ -171,7 +189,7 @@ if (raw.productionCallbackLive && !admitted) return null; if (caps.callbackOwnsChannelIds && !admitted) return null; return { raw, device:d, graph:g, telemetry:t, admitted, retained, - productLive:admitted && raw.productionCallbackLive, + hardwareConfiguration,productLive:admitted && raw.productionCallbackLive, identity: d.epoch + ":" + g.revision + ":" + g.rosterRevision }; } // MV-3: select exactly one existing native read authority for /preview/. @@ -621,7 +639,11 @@ cmp(next.graph.rosterRevision,current.graph.rosterRevision) < 0))) { lastError="OLD_NATIVE_REVISION";notify();return false; } - if (pending && (epochCompare !== 0 || next.retained)) { + // A same-epoch physical pin/format reconfiguration invalidates the + // current control lease even before ACK. Otherwise an older pending + // v6 edit would suppress the new admitted snapshot indefinitely. + if (pending && (epochCompare !== 0 || next.retained || + next.hardwareConfiguration!==current.hardwareConfiguration)) { pending=null;lastError="STALE_DEVICE"; } } @@ -752,5 +774,9 @@ } return Object.freeze({subscribe,onSnapshot,onAck,intent,state,expire}); } - return Object.freeze({decimal,cmp,normalizeSnapshot,selectNativeReadModel,readbackProvesIntent,logicalReadbackProves,diagnoseFirstSound,createController,validPresentationName,validPresentationColor,validPresentationIcon,operatorMessage,physicalOutputOverview}); + return Object.freeze({decimal,cmp,normalizeSnapshot, + nativeHardwareConfiguration,selectNativeReadModel,readbackProvesIntent, + logicalReadbackProves,diagnoseFirstSound,createController, + validPresentationName,validPresentationColor,validPresentationIcon, + operatorMessage,physicalOutputOverview}); });