From 1a66361eb30383b440d4b4fea0c50a56a1a9095e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Wed, 18 Nov 2026 16:05:31 +0700 Subject: [PATCH] refactor(mv12): rebase device lifecycle fence onto merged MV-11 #790 --- ...oved_device_pin_identity_contract.test.cjs | 91 +++++++++++++++++++ web/approved-device-view-model.js | 40 +++++++- web/approved-native-bridge.js | 37 +++++++- 3 files changed, 166 insertions(+), 2 deletions(-) diff --git a/tests/approved_device_pin_identity_contract.test.cjs b/tests/approved_device_pin_identity_contract.test.cjs index f0101b160..cd29e47da 100644 --- a/tests/approved_device_pin_identity_contract.test.cjs +++ b/tests/approved_device_pin_identity_contract.test.cjs @@ -168,3 +168,94 @@ test("MV-8 DeviceVM remains pure; exactly one unchanged native Apply transport", assert.equal((region.match(/backend\.emitEvent\("arMixAction",begun\.request\)/g)||[]).length,1); assert.doesNotMatch(source,/document\.|window\.|AudioWorklet|new AudioContext|localStorage/); }); + + +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"}}; + 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); + assert.equal(JSON.stringify(base),original); + for(const epoch of [18446744073709551615,"01","-1","1.5","", + "18446744073709551616",null]) { + assert.equal(vm.nativeLifecycleLease({...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, + 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", + 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"); + 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"); + 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, + backend:"Windows Audio"}).expirePending,true); + assert.equal(vm.nativeLifecycleDecision(first,null).kind,"INVALID"); +}); + +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); + for(const [a,b] of [["M4","CHANNEL_ID"],["CHANNEL_ID","NEEDS_REMAP"], + ["NEEDS_REMAP","CHANNEL_ID"],["LOGICAL_ONLY","CHANNEL_ID"], + ["CHANNEL_ID","UNADMITTED"],["UNADMITTED","M4"], + ["STALE","CHANNEL_ID"]]) { + assert.deepEqual(vm.nativeLifecycleDecision(mk(a),mk(b)), + {kind:"AUTHORITY_CHANGED",expirePending:true},a+" -> "+b); + } + for(const kind of ["M4","CHANNEL_ID","LOGICAL_ONLY","NEEDS_REMAP", + "UNADMITTED","STALE"]) + assert.equal(vm.nativeLifecycleDecision(mk(kind),mk(kind)).expirePending, + false,"identical authority must not erase pending current work"); + const source=readFileSync("web/approved-device-view-model.js","utf8"); + assert.doesNotMatch(source,/document\.|window\.|AudioWorklet|new AudioContext|localStorage/); +}); + +test("MV-12 approved bridge invalidates transient UI leases, not durable JUCE state",()=>{ + const source=readFileSync("web/approved-native-bridge.js","utf8"); + const start=source.indexOf(" function expireTransientNativeUi(reason) {"); + const end=source.indexOf(" function onNativeReadback(next,confirmed)",start); + assert.ok(start>0&&end>start); + const cleanup=source.slice(start,end); + for(const token of ["pendingNativeSources.clear()","pendingSourceQueue.clear()", + "pendingNativeControl.clear()","liveFaderVisualTargets.clear()", + "lastNativeControlSent.clear()","pendingWireGains.clear()", + "pendingM4Controls.clear()","pendingM4RackPowers.clear()", + "pendingNativeFxPower=null","pendingGlobalFx=null", + "activeNativeSource=null","pendingIdentity"] ) + assert.ok(cleanup.includes(token),"missing old transaction cancellation: "+token); + assert.doesNotMatch(cleanup,/backend\.emitEvent|arMixAction|routingNative|audioDeviceApply|\.smix|new AudioContext/); + const readback=source.slice(end,source.indexOf(" if (connected) {\n controller = protocol.createController",end)); + assert.match(readback,/deviceVM\.nativeLifecycleLease\(next,readModel\.kind\)/); + assert.match(readback,/deviceVM\.nativeLifecycleDecision\(lastNativeLifecycleLease,lease\)/); + assert.match(readback,/if\(lifecycle\.expirePending\)/); + assert.match(readback,/confirmed=null;/); + assert.ok(readback.indexOf("if(readModel.kind===\"INVALID\")")< + readback.indexOf("deviceVM.nativeLifecycleLease("), + "invalid raw readback must not create a new device owner"); + assert.ok(readback.indexOf("expireTransientNativeUi(lifecycle.kind)")< + readback.indexOf("appearanceFromNative(next)"), + "stale cosmetic ACK cannot settle before device identity fence"); +}); diff --git a/web/approved-device-view-model.js b/web/approved-device-view-model.js index 8c43f1e74..2c7123e74 100644 --- a/web/approved-device-view-model.js +++ b/web/approved-device-view-model.js @@ -356,8 +356,46 @@ if(state.pending)return state; return {...state,phase:"IDLE",message:"",remapGeneration:null}; } + + // 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 + // ever publishing a retained/unavailable snapshot: UI requests must still + // lose their old lease. Graph revisions do NOT identify a new device. + function nativeLifecycleLease(snapshot,readModelKind) { + const d=snapshot?.device,epoch=d?.epoch; + const kinds=["CHANNEL_ID","M4","NEEDS_REMAP","LOGICAL_ONLY", + "UNADMITTED","STALE"]; + 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. + return Object.freeze({epoch,backend:d.backend, + captureDevice:d.captureDevice,playbackDevice:d.playbackDevice, + authority:readModelKind}); + } + function nativeLifecycleDecision(previous,next) { + if(!next || typeof next.epoch!=="string" || + typeof next.authority!=="string") + return Object.freeze({kind:"INVALID",expirePending:false}); + if(!previous) + return Object.freeze({kind:"INITIAL",expirePending:false}); + const changed=previous.epoch!==next.epoch || + previous.backend!==next.backend || + previous.captureDevice!==next.captureDevice || + previous.playbackDevice!==next.playbackDevice; + if(changed) + return Object.freeze({kind:"DEVICE_CHANGED",expirePending:true}); + if(previous.authority!==next.authority) + return Object.freeze({kind:"AUTHORITY_CHANGED",expirePending:true}); + return Object.freeze({kind:"SAME",expirePending:false}); + } return Object.freeze({activeInputPins,inputChoices,inputLabel,outputChoices, externalPresentation,setupDraft,setupPresentation,setupEditDraft, setupInitial,setupBegin,setupAck,setupReadback, - setupTimeout,setupClearResult}); + setupTimeout,setupClearResult,nativeLifecycleLease,nativeLifecycleDecision}); }); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index febad16fe..0b2003259 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2602,9 +2602,31 @@ if(from===undefined||to===undefined||to===scope?.master?.id)return; scope?.kickWireSpring?.(from,to); } + // The schema-v6 controller owns accepted snapshots. This single bridge + // cleanup drops only outstanding WebView intents from an older device or + // changed PCM authority; the native session, .smix, FX instances and + // approved controls remain owned by JUCE and will be repainted by readback. + let lastNativeLifecycleLease=null; + function expireTransientNativeUi(reason) { + pendingNativeSources.clear();pendingSourceQueue.clear(); + activeNativeSource=null;nativeUiSourcePending=null;pendingSourceId=0; + pendingOutputPatch=null;pendingNativeFxPower=null;pendingGlobalFx=null; + pendingBusCreate=null;pendingTrackDelete=null;pendingFxInsert=null; + startupWire=null;activeWireAttempt=null;pendingNativeGainIntent=false; + pendingWireGains.clear();pendingNativeControl.clear(); + liveFaderVisualTargets.clear();lastNativeControlSent.clear(); + pendingM4Controls.clear();pendingM4RackPowers.clear(); + if(pendingIdentity){ + if(pendingIdentity.migration)legacyDeferred.add(pendingIdentity.channelId); + rejectIdentity("Channel identity expired after audio connection change"); + } + lastPaintedSignature="";lastNativeTopologySignature=""; + status(reason==="DEVICE_CHANGED"? + "Audio connection changed · old control gestures discarded": + "Mixer authority changed · old control gestures discarded"); + } 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; @@ -2621,6 +2643,19 @@ status("NATIVE READBACK INVALID · existing GUI controls unchanged"); return; } + const lease=deviceVM.nativeLifecycleLease(next,readModel.kind); + if(!lease){ + status("NATIVE DEVICE IDENTITY INVALID · existing controls unchanged"); + return; + } + const lifecycle=deviceVM.nativeLifecycleDecision(lastNativeLifecycleLease,lease); + if(lifecycle.expirePending){ + expireTransientNativeUi(lifecycle.kind); + // Old readback confirmations must not animate or complete new PCM work. + confirmed=null; + } + lastNativeLifecycleLease=lease; + appearanceFromNative(next); settleNativeSourceReadback(next); if(readModel.kind==="LOGICAL_ONLY") { const staged=readModel.view;