From 886ea57ec260d8d1ab74fdcb9d3ea1cf197433f7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 15:02:41 +0700 Subject: [PATCH 001/219] feat(first-sound): integrate approved DAW-style input selector on latest GUI-optimized main --- integration/ApprovedNativeRuntimeSnapshot.h | 42 +++ scripts/build_approved_native_gui.py | 6 + tests/approved_native_m2_contract.test.cjs | 29 +- web/approved-native-bridge.js | 300 +++++++++++++++++++- 4 files changed, 372 insertions(+), 5 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index eaafd93b0..77014352a 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -82,6 +82,48 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, boolIs(route,"hasAcceptedRoute",true)); firstSound->setProperty("routingRevision",physicalReady ?juce::String(static_cast(revision)):juce::String("0")); + // Exactly ten hardware INPUT readbacks from the existing accepted M4 + // compiler, not the public Pages demo. A new unpatched session reports + // an empty array: we must not fabricate a default CH1 microphone. + juce::Array verifiedChannels; + if(physicalReady && boolIs(route,"hasAcceptedRoute",true)) { + const auto accepted=route.getProperty("acceptedRoute",{}); + const auto channels=accepted.getProperty("channels",{}); + if(auto* list=channels.getArray();list!=nullptr && + list->size()==10) { + bool valid=true; + for(const auto& item:*list) { + if(!item.isObject()) {valid=false;break;} + const auto mode=item.getProperty("mode",{}).toString(); + const auto left=item.getProperty("left",juce::var()); + const auto right=item.getProperty("right",juce::var()); + const auto main=item.getProperty("main",{}); + if((mode!="NONE" && mode!="MONO" && mode!="STEREO") || + !(left.isInt()||left.isInt64()) || + !(right.isInt()||right.isInt64()) || !main.isBool()) { + valid=false;break; + } + const int l=static_cast(left),r=static_cast(right); + if((mode=="NONE"&&(l!=-1||r!=-1)) || + (mode=="MONO"&&(r!=-1||l<0)) || + (mode=="STEREO"&&(l<0||r<0||l==r))) { + valid=false;break; + } + if(mode!="NONE"&&(!inputs.getArray()->contains(l)|| + (mode=="STEREO"&&!inputs.getArray()->contains(r)))) { + valid=false;break; + } + auto verified=std::make_unique(); + verified->setProperty("mode",mode); + verified->setProperty("left",l); + verified->setProperty("right",r); + verified->setProperty("main",main); + verifiedChannels.add(juce::var(verified.release())); + } + if(!valid)verifiedChannels.clear(); + } + } + firstSound->setProperty("channels",juce::var(verifiedChannels)); // Do not write the route to the graph or change native capability flags. snapshot.getDynamicObject()->setProperty("legacyM4",juce::var(firstSound.release())); return physicalReady; diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 0aa79f524..0c4fa7111 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -57,6 +57,12 @@ def accepted_pages_html() -> str: # HTML at native build time. Every anchor must occur exactly once: no silent # breakage if Pages GUI source evolves. No extra layout or simulated PCM. NATIVE_EVENT_HOOKS = ( + # Only the compiled Windows WebView gets verified native driver inputs. + # Public /preview/ continues to show its labeled simulated reference. + ("const channelOptions=(t,type)=>{\n", + "const channelOptions=(t,type)=>{\n" + " if(type==='input'&&window.__JUCE__?.backend)\n" + " return window.__ARMIX_NATIVE_M2__?.inputChoices?.(t)||['None'];\n"), ("function wireGraphCommit(ops,{record=true}={}){\n", "function wireGraphCommit(ops,{record=true}={}){\n" " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops);return false;}\n"), diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 2b584dd09..f4e860f35 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -114,6 +114,31 @@ test("native signal evidence is produced from measured engine fields, never JS s assert.doesNotMatch(transport,/setProperty \("rawCapturePeak", 0\.0\)/); assert.match(bridge,/protocol\.diagnoseFirstSound/); }); +test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, never Pages demo",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const builder=read("scripts/build_approved_native_gui.py"); + const nativeMain=read("src/Main.cpp"); + 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,/field==="input"/); + assert.match(bridge,/scope\?\.tracks\?\.findIndex/); + assert.match(bridge,/action:"routingSourceSwitch"/); + assert.match(bridge,/row\?\.left===p\.choice\.left/); + assert.match(bridge,/expectedEpoch:p\.epoch,expectedRevision:Number\(next\.revision\)/); + assert.match(bridge,/inputSelect\.hidden=true;routeBtn\.hidden=true;armBtn\.hidden=true/); + assert.match(bridge,/openNativeAudioIO\(\)/); + assert.match(bridge,/\.armix-audio-shade\[hidden\]\{display:none\}/); + assert.match(producer,/firstSound->setProperty\("channels",juce::var\(verifiedChannels\)\)/); + assert.match(producer,/list->size\(\)==10/); + assert.match(nativeMain,/engine_\.switchDryRoutingLabSource\(channel,/); + assert.match(nativeMain,/engine_\.liveOutputArmFault\(\)/); + // Public Pages still has its simulation, but NONE of those fake inputs + // can be submitted by the native bridge. Only the native injected source. + assert.doesNotMatch(bridge,/channelOptions\(t,'input'\)/); +}); test("strict producer rejects JS Number identities, invalid hardware pins and fake LIVE",()=>{ const cases=[ s=>{s.device.epoch=69;}, @@ -433,7 +458,9 @@ test("native Windows operator can explicitly patch first physical input, arm and const main=read("src/Main.cpp"); const engine=read("src/LiveAudioEngine.h"); assert.match(js,/REAL AUDIO · FIRST SOUND/); - assert.match(js,/action:"audioSetup"/); + 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(js,/action:"routingSourceSwitch",requestId:pendingSourceId/); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 212cd2d9f..68568938e 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -81,6 +81,14 @@ t.pan=ch.controls.pan*100; t.mute=ch.controls.mute; t.solo=ch.controls.solo; + // Admitted ChannelId readback already carries actual physical pins. + // Do not retain the public demo's "None" when native PCM is active. + if(ch.role==="INPUT"){ + const src=ch.source||{},l=/^in:(\d+)$/.exec(src.portId||""), + r=/^in:(\d+)$/.exec(src.portIdRight||""); + t.input=l?inputLabelFor({mode:src.sourceFormat==="STEREO"?"STEREO":"MONO", + left:Number(l[1]),right:r?Number(r[1]):-1}):"None"; + } t.selected=previous.get(t.id)?.selected || false; if (Array.isArray(ch.inserts)) { t.fx=Array.from({length:8},(_,i)=>ch.inserts[i]?.name||"None"); @@ -173,18 +181,69 @@ return Number.isSafeInteger(number)&&number>0?number:null; }; const legacy=()=>hardware?.raw?.legacyM4; + // 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)):[]; + const monoLabel=p=>"Mono · "+p.label+" [IN "+(p.port+1)+"]"; + const stereoLabel=(a,b)=>"Stereo · IN "+(a.port+1)+" + "+(b.port+1); + 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"; + const entries=inputChoicesFor(); + const exact=entries.find(x=>x.mode===row.mode && + x.left===row.left && x.right===row.right); + return exact?.label||"None"; + }; + let lastM4UiSignature="",nativeUiSourcePending=null; + function refreshRealM4Inputs(next){ + if(!scope?.tracks || next?.admitted || !Array.isArray(scope.tracks) || + scope.tracks.length<10) return; + const m4=next?.raw?.legacyM4; + const rows=m4?.channels; + const signature=JSON.stringify([next?.device?.epoch, + next?.device?.enabledInputs,next?.device?.inputEndpoints, + m4?.active,m4?.routingRevision,rows]); + if(signature===lastM4UiSignature)return; + lastM4UiSignature=signature; + for(let i=0;i<10;++i){ + const t=scope.tracks[i]; + if(t?.kind!=="audio")continue; + const row=Array.isArray(rows)&&rows.length===10?rows[i]:null; + t.input=inputLabelFor(row); + if(row && typeof row.main==="boolean") + t.output=row.main?"Master":"SOURCE ONLY (No Main)"; + } + // One existing canonical mixer renderer, updated only when the actual + // hardware topology/route changes, never on periodic PCM meter frames. + scope.render?.(); + } + const deviceReady=()=>!!(hardware?.device?.backend && hardware.device.sampleRate>0 && hardware.device.enabledInputs.length>0 && hardware.device.enabledOutputs.length>=2 && legacy()?.active===true); function updateHardwarePanel(next) { hardware=next || null; + refreshRealM4Inputs(next); const d=next?.device; const deviceOpen=Boolean(d?.backend && d.sampleRate>0 && d.enabledOutputs.length>=2); const label=document.getElementById("transport"); - const transport=!deviceOpen?"Device not ready": - d.outputArmed?"Output armed":"Output muted"; + const transport=!deviceOpen?"Audio device not ready": + (d.outputArmed?"Monitoring":"Output muted")+" · "+(d.playbackDevice||"unknown output"); if(label && label.textContent!==transport)label.textContent=transport; const warning=document.querySelector?.(".status-bar .warning"); const warningText=!deviceOpen?"NO VERIFIED AUDIO DEVICE": @@ -231,6 +290,154 @@ if(hardwareNote.textContent!==note)hardwareNote.textContent=note; } } + // 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,pendingDeviceMute=false,deviceChoice=null; + function openNativeAudioIO(){ + if(!devicePanel){ + const style=document.createElement("style"); + style.textContent=` + .armix-audio-shade{position:fixed;inset:0;background:#020b12b8;z-index:99998; + display:flex;align-items:center;justify-content:center} + .armix-audio-shade[hidden]{display:none} + .armix-audio-dialog{background:#142631;border:1px solid #467083;border-radius:8px; + box-shadow:0 16px 56px #0009;color:#e3eff4;width:min(480px,94vw); + padding:17px;display:grid;gap:11px;font:12px system-ui,sans-serif} + .armix-audio-dialog h2{font-size:16px;font-weight:600;margin:0} + .armix-audio-dialog label{display:grid;gap:5px;color:#a9c5d2} + .armix-audio-dialog select{background:#09202c;border:1px solid #476778; + border-radius:4px;color:#edf9ff;min-height:30px;width:100%;padding:3px 7px} + .armix-audio-dialog button{background:#244254;border:1px solid #557b8d; + border-radius:4px;color:#e9f8ff;min-height:30px;padding:4px 12px} + .armix-audio-dialog button:disabled{opacity:.45} + .armix-audio-dialog .armix-device-actions{display:flex;gap:8px;justify-content:flex-end} + .armix-audio-dialog .armix-device-note{color:#a4c4d0;line-height:1.4} + `; + document.head.appendChild(style); + devicePanel=document.createElement("div"); + devicePanel.className="armix-audio-shade"; + devicePanel.innerHTML=``; + devicePanel.querySelector("[data-audio-close]").onclick=()=>{ + devicePanel.hidden=true; + }; + devicePanel.addEventListener("click",e=>{ + if(e.target===devicePanel)devicePanel.hidden=true; + }); + devicePanel.addEventListener("change",e=>{ + const field=e.target.dataset.audioField; + if(!deviceChoice||!field)return; + if(field==="backend"){ + deviceChoice.backend=e.target.value; + const t=deviceInventory?.types?.find(x=>x.name===deviceChoice.backend); + deviceChoice.capture=t?.inputs?.[0]||""; + deviceChoice.playback=t?.separate?t?.outputs?.[0]||"":deviceChoice.capture; + }else if(field==="capture")deviceChoice.capture=e.target.value; + else if(field==="playback")deviceChoice.playback=e.target.value; + renderDevicePanel(); + }); + devicePanel.querySelector("[data-audio-apply]").onclick=()=>{ + if(deviceBusy||!deviceChoice||!deviceInventory?.active)return; + const draft=deviceChoice,active=deviceInventory.active; + if(!draft.backend||!draft.capture||!draft.playback)return; + if(hardware?.device?.outputArmed){ + pendingDeviceMute=true; + devicePanel.querySelector("[data-audio-active]").textContent= + "Muting current output before changing driver…"; + backend.emitEvent("arMixAction",{action:"monitor",value:false}); + }else sendDeviceApply(); + }; + document.body.appendChild(devicePanel); + } + devicePanel.hidden=false; + const active=devicePanel.querySelector("[data-audio-active]"); + if(active)active.textContent="Reading verified audio devices…"; + backend.emitEvent("arMixAction",{action:"audioDeviceInventory"}); + } + function fillAudioSelect(name,values,current){ + const el=devicePanel?.querySelector('[data-audio-field="'+name+'"]'); + if(!el)return; + el.replaceChildren(...values.map(value=>{ + const option=document.createElement("option"); + option.value=value;option.textContent=value;return option; + })); + if(values.includes(current))el.value=current; + el.disabled=deviceBusy; + } + function renderDevicePanel(){ + if(!devicePanel||devicePanel.hidden||!deviceInventory)return; + const active=deviceInventory.active||{},types=deviceInventory.types||[]; + if(!deviceChoice){ + const backendName=active.backend||types[0]?.name||""; + const selected=types.find(x=>x.name===backendName); + const capture=active.captureDevice||selected?.inputs?.[0]||""; + deviceChoice={backend:backendName,capture, + playback:active.playbackDevice|| + (selected?.separate?selected?.outputs?.[0]:capture)||""}; + } + const t=types.find(x=>x.name===deviceChoice.backend); + fillAudioSelect("backend",types.map(x=>x.name),deviceChoice.backend); + fillAudioSelect("capture",t?.inputs||[],deviceChoice.capture); + fillAudioSelect("playback",t?.outputs||[],deviceChoice.playback); + const activeText=devicePanel.querySelector("[data-audio-active]"); + if(activeText && !deviceBusy)activeText.textContent=active.open? + "ACTIVE · "+active.backend+" · "+active.captureDevice+ + " → "+active.playbackDevice+" · "+active.rate+" Hz / "+active.buffer+" samples": + "No verified audio device. Select a supported input and output."; + devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| + !deviceChoice.backend||!deviceChoice.capture||!deviceChoice.playback; + } + function sendDeviceApply(){ + if(!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; + deviceBusy=true; + const requestId="approved-io-"+(++deviceRequest); + devicePanel.dataset.pendingRequest=requestId; + devicePanel.querySelector("[data-audio-active]").textContent= + "Applying audio device; verifying native readback…"; + backend.emitEvent("arMixAction",{action:"audioDeviceApply", + requestId,expectedDeviceGeneration:Number(a.deviceGeneration), + config:{backend:c.backend,captureDevice:c.capture, + playbackDevice:c.playback,sampleRate:0,bufferSize:0, + enabledInputs:same?a.enabledInputs:[], + enabledOutputs:same?a.enabledOutputs:[]}}); + } + if(connected){ + backend.addEventListener("arMixAudioDeviceInventory",inventory=>{ + if(!inventory||!Array.isArray(inventory.types))return; + deviceInventory=inventory; + if(!deviceBusy)deviceChoice=null; + renderDevicePanel(); + }); + backend.addEventListener("arMixAudioDeviceApplyAck",ack=>{ + if(!devicePanel||ack?.requestId!==devicePanel.dataset.pendingRequest)return; + deviceBusy=false; + if(ack.active)deviceInventory.active=ack.active; + const note=devicePanel.querySelector("[data-audio-active]"); + if(note)note.textContent=ack.ok? + "Device verified · choose a hardware input on any mixer channel.": + "Device rejected · "+(ack.error||"driver readback failed"); + deviceChoice=null; + renderDevicePanel(); + }); + } + function installFirstSoundMenu() { const menu=document.querySelector?.("#moreTools .more-tools-panel"); if(!menu || typeof document.createElement!=="function")return; @@ -243,8 +450,10 @@ const caption=item("span","more-tools-caption","REAL AUDIO · FIRST SOUND"); const setup=item("button","tool","Audio Setup"); setup.addEventListener("click",()=>{ - backend.emitEvent("arMixAction",{action:"audioSetup"}); - status("NATIVE: select actual ASIO/WASAPI input + output in Audio Setup."); + // Reuse the EXISTING custom driver/endpoint pane. The stock JUCE + // selector is reserved for explicitly requested advanced recovery. + // Never create a second Audio Setup workflow from the More menu. + openNativeAudioIO(); }); inputSelect=item("select","toolbar-select",""); inputSelect.setAttribute("aria-label","JUCE physical input for CH1"); @@ -286,7 +495,21 @@ }); hardwareNote=item("span","more-tools-caption","Device not initialized"); hardwareNote.style.whiteSpace="normal"; + // Legacy developer-first staging is no longer a user-facing workflow. + // IN is on every mixer strip; emergency MUTE stays accessible here. + caption.textContent="AUDIO / SAFETY"; + inputSelect.hidden=true;routeBtn.hidden=true;armBtn.hidden=true; menu.append(caption,setup,inputSelect,routeBtn,armBtn,muteBtn,hardwareNote); + // Single discoverable AUDIO I/O button next to ordinary mixer tools. + // The existing More entry remains a shortcut to THIS SAME panel. + const toolbar=document.querySelector(".command-bar"); + if(toolbar && !toolbar.querySelector("[data-native-io]")){ + const io=item("button","tool","Audio I/O"); + io.dataset.nativeIo="true"; + io.title="Select ASIO/WASAPI driver and capture/playback device"; + io.addEventListener("click",openNativeAudioIO); + toolbar.insertBefore(io,document.getElementById("moreTools")); + } updateHardwarePanel(hardware); } @@ -350,6 +573,34 @@ }); backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); backend.addEventListener("arMixSourceSwitchAck", ack=>{ + if(nativeUiSourcePending && + ack?.requestId===nativeUiSourcePending.requestId) { + const p=nativeUiSourcePending; + nativeUiSourcePending=null; + const next=ack?.state||{},row=next.acceptedRoute?.channels?.[p.channel]; + const verified=ack.ok===true && next.ready===true && + Number(next.epoch)===p.epoch && next.hasAcceptedRoute===true && + Number(next.revision)>=p.revision && + row?.mode===p.choice.mode && row?.left===p.choice.left && + row?.right===p.choice.right; + if(verified) { + // Native publisher + engine own the accepted graph; refresh the + // UI only from a subsequent authoritative snapshot. + controller.subscribe(); + if(p.autoListen && hardware?.device?.epoch===String(p.epoch)) { + // Selecting the first physical INPUT is user intent to monitor, + // no second ARM button. The C++ liveOutputArmFault gate still + // refuses invalid outputs and never opens an unrelated device. + backend.emitEvent("arMixAction",{action:"monitor",value:true, + expectedEpoch:p.epoch,expectedRevision:Number(next.revision)}); + } + status("CH "+(p.channel+1)+" native input accepted"); + } else { + status("NATIVE INPUT REJECTED · "+(ack?.error||"stale routing")); + controller.subscribe(); + } + return; + } if(!pendingSourceId||ack?.requestId!==pendingSourceId)return; pendingSourceId=0; if(ack.ok===true) { @@ -359,6 +610,14 @@ updateHardwarePanel(hardware); }); backend.addEventListener("arMixAudioArmAck", ack=>{ + if(pendingDeviceMute){ + pendingDeviceMute=false; + if(ack?.ok===true && ack?.armed===false)sendDeviceApply(); + else if(devicePanel) + devicePanel.querySelector("[data-audio-active]").textContent= + "Device change rejected: existing output could not be muted."; + return; + } if(ack?.ok===true){ status(ack.armed?"NATIVE: user ARM accepted; checking real PCM.": "NATIVE: output muted."); @@ -368,12 +627,45 @@ } const nativeHooks=Object.freeze({ enabled:connected, + inputChoices(t) { + if(t?.kind!=="audio")return ["None"]; + return inputChoicesFor().map(x=>x.label); + }, consumeField(event) { if (!connected)return false; const el=event.target,field=el?.dataset?.field; if (!field)return false; const t=scope?.findTrack?.(el) || null; if (!t)return true; + if(field==="input"){ + // Input selection is independent of Record Arm, transport START and + // ChannelId admission. A physical mixer strip can receive ANY active + // source, including the very first source in an unpatched session. + if(event.type!=="change")return true; + const channel=scope?.tracks?.findIndex?.(x=>x.id===t.id)??-1; + const choice=inputChoicesFor().find(x=>x.label===el.value); + const ep=safeNativeCounter(hardware?.device?.epoch); + const rev=safeNativeCounter(legacy()?.routingRevision); + if(channel<0||channel>=10||!choice||!deviceReady() || + ep===null||rev===null||pendingSourceId!==0 || + nativeUiSourcePending){ + status("NATIVE INPUT REJECTED · device/source changed or busy"); + el.value=t.input;return true; + } + if(el.value===t.input)return true; + const first=legacy()?.routeAccepted!==true; + const requestId=++sourceSerial; + nativeUiSourcePending={requestId,channel,choice,epoch:ep, + revision:rev,autoListen:first&&!hardware.device.outputArmed}; + // Keep the visible IN at its last accepted value until native ACK + // and a fresh verified revision arrive. No optimistic demo routing. + el.value=t.input; + backend.emitEvent("arMixAction",{action:"routingSourceSwitch", + requestId,channel,mode:choice.mode,left:choice.left,right:choice.right, + deviceEpoch:ep,revision:rev}); + status("CH "+(channel+1)+" INPUT · verifying physical routing"); + return true; + } if (!flags.acceptedGraphConnected) { if (field==="level")el.value=String(t.level); else if (field==="pan")el.value=String(t.pan); From 57fbc4cfa0f5532c60a46b0001dd8c359c2d564c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 15:07:39 +0700 Subject: [PATCH 002/219] feat(audio I/O): expose verified per-device input/output pin masks and supported rate/buffer inside custom native setup --- web/approved-native-bridge.js | 93 +++++++++++++++++++++++++++++++---- 1 file changed, 83 insertions(+), 10 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 68568938e..9a27db614 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -314,6 +314,11 @@ .armix-audio-dialog button:disabled{opacity:.45} .armix-audio-dialog .armix-device-actions{display:flex;gap:8px;justify-content:flex-end} .armix-audio-dialog .armix-device-note{color:#a4c4d0;line-height:1.4} + .armix-audio-dialog details{border-top:1px solid #345666;padding-top:8px} + .armix-audio-dialog summary{cursor:pointer;color:#c5e1ed} + .armix-audio-pins{display:grid;grid-template-columns:1fr 1fr;gap:8px; + max-height:135px;overflow:auto;padding:5px 0} + .armix-audio-pins label{display:flex;align-items:center;gap:5px;font-size:11px} `; document.head.appendChild(style); devicePanel=document.createElement("div"); @@ -325,9 +330,13 @@
Reading current audio device…
-
Choose the actual playback destination. - A virtual cable is not necessarily audible through headphones. - Sample rate and buffer use driver defaults until configured in Advanced.
+
The output device above is the real destination. + A virtual cable does not automatically play through headphones.
+
Advanced · rate, buffer and channel pins + + +
+
@@ -339,15 +348,36 @@ if(e.target===devicePanel)devicePanel.hidden=true; }); devicePanel.addEventListener("change",e=>{ + if(!deviceChoice)return; + const pinSide=e.target.dataset.audioPin; + if(pinSide==="input"||pinSide==="output"){ + const index=Number(e.target.dataset.pinIndex); + const key=pinSide==="input"?"inputPins":"outputPins"; + if(!Number.isInteger(index)||!Array.isArray(deviceChoice[key]))return; + const next=new Set(deviceChoice[key]); + if(e.target.checked)next.add(index);else next.delete(index); + deviceChoice[key]=[...next].sort((a,b)=>a-b); + renderDevicePanel();return; + } const field=e.target.dataset.audioField; - if(!deviceChoice||!field)return; + if(!field)return; if(field==="backend"){ deviceChoice.backend=e.target.value; const t=deviceInventory?.types?.find(x=>x.name===deviceChoice.backend); deviceChoice.capture=t?.inputs?.[0]||""; deviceChoice.playback=t?.separate?t?.outputs?.[0]||"":deviceChoice.capture; - }else if(field==="capture")deviceChoice.capture=e.target.value; - else if(field==="playback")deviceChoice.playback=e.target.value; + deviceChoice.inputPins=null;deviceChoice.outputPins=null; + deviceChoice.rate=0;deviceChoice.buffer=0; + }else if(field==="capture"){ + deviceChoice.capture=e.target.value; + const t=deviceInventory?.types?.find(x=>x.name===deviceChoice.backend); + if(t&&!t.separate)deviceChoice.playback=e.target.value; + deviceChoice.inputPins=null;deviceChoice.outputPins=null; + }else if(field==="playback"){ + deviceChoice.playback=e.target.value; + deviceChoice.inputPins=null;deviceChoice.outputPins=null; + }else if(field==="rate")deviceChoice.rate=Number(e.target.value)||0; + else if(field==="buffer")deviceChoice.buffer=Number(e.target.value)||0; renderDevicePanel(); }); devicePanel.querySelector("[data-audio-apply]").onclick=()=>{ @@ -387,12 +417,54 @@ const capture=active.captureDevice||selected?.inputs?.[0]||""; deviceChoice={backend:backendName,capture, playback:active.playbackDevice|| - (selected?.separate?selected?.outputs?.[0]:capture)||""}; + (selected?.separate?selected?.outputs?.[0]:capture)||"", + inputPins:Array.isArray(active.enabledInputs)?active.enabledInputs.slice():null, + outputPins:Array.isArray(active.enabledOutputs)?active.enabledOutputs.slice():null, + rate:0,buffer:0}; } const t=types.find(x=>x.name===deviceChoice.backend); fillAudioSelect("backend",types.map(x=>x.name),deviceChoice.backend); fillAudioSelect("capture",t?.inputs||[],deviceChoice.capture); fillAudioSelect("playback",t?.outputs||[],deviceChoice.playback); + const same=active.open&&active.backend===deviceChoice.backend&& + active.captureDevice===deviceChoice.capture&& + active.playbackDevice===deviceChoice.playback; + const rates=same?active.rates||[]:[]; + const buffers=same?active.buffers||[]:[]; + fillAudioSelect("rate",["0",...rates.map(String)],String(deviceChoice.rate||0)); + 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;} + const pins=document.querySelector(".armix-audio-dialog [data-audio-pins]"); + if(pins){ + pins.replaceChildren(); + if(same){ + const container=document.createElement("div"); + container.className="armix-audio-pins"; + for(const [side,names,key,enabled] of [ + ["input",active.inputNames,"inputPins",active.enabledInputs], + ["output",active.outputNames,"outputPins",active.enabledOutputs]]){ + const group=document.createElement("div"); + const title=document.createElement("strong"); + title.textContent=side==="input"?"Capture pins":"Playback pins"; + group.appendChild(title); + (names||[]).forEach((name,index)=>{ + const label=document.createElement("label"); + const control=document.createElement("input"); + control.type="checkbox";control.dataset.audioPin=side; + control.dataset.pinIndex=String(index); + control.checked=(deviceChoice[key]||enabled||[]).includes(index); + control.disabled=deviceBusy; + label.append(control,document.createTextNode(String(name))); + group.appendChild(label); + }); + container.appendChild(group); + } + pins.appendChild(container); + }else pins.textContent="Apply this device first to inspect its real enabled pins."; + } const activeText=devicePanel.querySelector("[data-audio-active]"); if(activeText && !deviceBusy)activeText.textContent=active.open? "ACTIVE · "+active.backend+" · "+active.captureDevice+ @@ -414,9 +486,10 @@ backend.emitEvent("arMixAction",{action:"audioDeviceApply", requestId,expectedDeviceGeneration:Number(a.deviceGeneration), config:{backend:c.backend,captureDevice:c.capture, - playbackDevice:c.playback,sampleRate:0,bufferSize:0, - enabledInputs:same?a.enabledInputs:[], - enabledOutputs:same?a.enabledOutputs:[]}}); + playbackDevice:c.playback,sampleRate:same?c.rate:0, + bufferSize:same?c.buffer:0, + enabledInputs:same?c.inputPins:[], + enabledOutputs:same?c.outputPins:[]}}); } if(connected){ backend.addEventListener("arMixAudioDeviceInventory",inventory=>{ From 06fa5a6183edbb56b10ae61f21195a0060afacad Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 15:08:28 +0700 Subject: [PATCH 003/219] test(native): prove CH05 first hardware source and reject unenabled physical pin in native snapshot --- tests/approved_native_v8_projection_test.cpp | 31 ++++++++++++++++++++ 1 file changed, 31 insertions(+) diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 335593c5a..e20952262 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -368,6 +368,37 @@ static void firstSoundRouteAdmissionRegression() { assert(publishVerifiedFirstSoundState(snapshot,live)); m4=snapshot.getProperty("legacyM4",{}); assert(static_cast(m4.getProperty("routeAccepted",false))); + // First hardware choice may target CH05 (not hardcoded CH01). All ten + // rows must project from native accepted data, never demo INPUT 1. + juce::Array rows; + for(int i=0;i<10;++i) { + auto row=std::make_unique(); + row->setProperty("mode",i==4?"MONO":"NONE"); + row->setProperty("left",i==4?0:-1); + row->setProperty("right",-1); + row->setProperty("main",true); + rows.add(juce::var(row.release())); + } + auto accepted=std::make_unique(); + accepted->setProperty("channels",juce::var(rows)); + live.getProperty("dryRoutingLab",{}).getDynamicObject()->setProperty( + "acceptedRoute",juce::var(accepted.release())); + assert(publishVerifiedFirstSoundState(snapshot,live)); + m4=snapshot.getProperty("legacyM4",{}); + const auto physicalRows=m4.getProperty("channels",{}); + assert(physicalRows.isArray()); + assert(physicalRows.getArray()->size()==10); + assert(physicalRows.getArray()->getReference(4).getProperty("mode",{}).toString()=="MONO"); + assert(static_cast(physicalRows.getArray()->getReference(4).getProperty("left",-1))==0); + // Disabled hardware input is never presented as accepted physical PCM. + auto badPins=juce::JSON::parse(juce::JSON::toString(live,false)); + badPins.getProperty("dryRoutingLab",{}).getProperty("acceptedRoute",{}) + .getProperty("channels",{}).getArray()->getReference(4) + .getDynamicObject()->setProperty("left",7); + assert(publishVerifiedFirstSoundState(snapshot,badPins)); + assert(snapshot.getProperty("legacyM4",{}).getProperty("channels",{}).getArray()->isEmpty()); + // Restore valid accepted rows for the stale epoch/fail-closed matrix. + assert(publishVerifiedFirstSoundState(snapshot,live)); auto reject=[&](const juce::var& degraded) { auto fresh=juce::JSON::parse(juce::JSON::toString(snapshot,false)); assert(!publishVerifiedFirstSoundState(fresh,degraded)); From 2ef354877ef69b0e8c829e85c12e8fea145ca3d1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 15:09:21 +0700 Subject: [PATCH 004/219] fix(device UX): retain true accepted/rejected driver readback message instead of overwriting with stale active status --- web/approved-native-bridge.js | 18 ++++++++++-------- 1 file changed, 10 insertions(+), 8 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 9a27db614..fa79c0a69 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -294,7 +294,7 @@ // 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,pendingDeviceMute=false,deviceChoice=null; + deviceRequest=0,pendingDeviceMute=false,deviceChoice=null,deviceResult=""; function openNativeAudioIO(){ if(!devicePanel){ const style=document.createElement("style"); @@ -349,6 +349,7 @@ }); devicePanel.addEventListener("change",e=>{ if(!deviceChoice)return; + deviceResult=""; const pinSide=e.target.dataset.audioPin; if(pinSide==="input"||pinSide==="output"){ const index=Number(e.target.dataset.pinIndex); @@ -395,6 +396,7 @@ } devicePanel.hidden=false; const active=devicePanel.querySelector("[data-audio-active]"); + deviceResult=""; if(active)active.textContent="Reading verified audio devices…"; backend.emitEvent("arMixAction",{action:"audioDeviceInventory"}); } @@ -466,10 +468,10 @@ }else pins.textContent="Apply this device first to inspect its real enabled pins."; } const activeText=devicePanel.querySelector("[data-audio-active]"); - if(activeText && !deviceBusy)activeText.textContent=active.open? + if(activeText && !deviceBusy)activeText.textContent=deviceResult||(active.open? "ACTIVE · "+active.backend+" · "+active.captureDevice+ " → "+active.playbackDevice+" · "+active.rate+" Hz / "+active.buffer+" samples": - "No verified audio device. Select a supported input and output."; + "No verified audio device. Select a supported input and output."); devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| !deviceChoice.backend||!deviceChoice.capture||!deviceChoice.playback; } @@ -502,8 +504,7 @@ if(!devicePanel||ack?.requestId!==devicePanel.dataset.pendingRequest)return; deviceBusy=false; if(ack.active)deviceInventory.active=ack.active; - const note=devicePanel.querySelector("[data-audio-active]"); - if(note)note.textContent=ack.ok? + deviceResult=ack.ok? "Device verified · choose a hardware input on any mixer channel.": "Device rejected · "+(ack.error||"driver readback failed"); deviceChoice=null; @@ -686,9 +687,10 @@ if(pendingDeviceMute){ pendingDeviceMute=false; if(ack?.ok===true && ack?.armed===false)sendDeviceApply(); - else if(devicePanel) - devicePanel.querySelector("[data-audio-active]").textContent= - "Device change rejected: existing output could not be muted."; + else if(devicePanel){ + deviceResult="Device change rejected: existing output could not be muted."; + devicePanel.querySelector("[data-audio-active]").textContent=deviceResult; + } return; } if(ack?.ok===true){ From 86b4526e1cb9ee852ad68a0caf5f92820f04ecf7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 15:59:45 +0700 Subject: [PATCH 005/219] Repair approved /preview/ native DAW routing UX: correlated MUTE/Apply safety and lost-ACK recovery Keep one /preview/ UI and existing per-channel hardware IN route. Show actual virtual playback endpoint, hide legacy Patch/Arm behind unified UX, retain explicit advanced JUCE recovery. Correlate output mute request IDs and recover missing input ACK without touching RT DSP. Add contract gate. --- src/Main.cpp | 4 ++ tests/approved_native_m2_contract.test.cjs | 18 ++++++ web/approved-native-bridge.js | 70 ++++++++++++++++------ 3 files changed, 74 insertions(+), 18 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 90d494f60..a24c2d756 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2488,6 +2488,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto ack=std::make_unique(); ack->setProperty("ok",fault.isEmpty()); ack->setProperty("armed",engine_.isMonitorEnabled()); + // Optional request identity for safe, ordered device changes. + // No new audio-thread state and backward-compatible with MUTE. + ack->setProperty("requestId", + args.getProperty("requestId",juce::var())); ack->setProperty("error",fault); ack->setProperty("deviceEpoch", static_cast(engine_.dryRoutingLabEpoch())); diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f4e860f35..3e0bed379 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -139,6 +139,24 @@ test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, // can be submitted by the native bridge. Only the native injected source. assert.doesNotMatch(bridge,/channelOptions\(t,'input'\)/); }); +test("single /preview/ GUI: channel IN, actual OUT and correlated device safety ACK",()=>{ + const pages=read("scripts/build_pages.py"); + const builder=read("scripts/build_approved_native_gui.py"); + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/Main.cpp"); + assert.match(pages,/buttons_dest=dst\/'preview'/); + assert.match(builder,/public = destination \/ "preview"/); + assert.match(bridge,/source:"\/preview\/ approved compiled Pages GUI"/); + assert.match(bridge,/field==="input"/); + assert.match(bridge,/nativeUiSourcePending=null;[\s\S]*?response timed out/); + assert.match(bridge,/row\?\.main===true/); + assert.match(bridge,/pendingDeviceMute=\{requestId,epoch:String\(hardware\.device\.epoch\)\}/); + assert.match(bridge,/ack\?\.requestId!==pendingDeviceMute\.requestId/); + assert.match(bridge,/VIRTUAL \/ NO SPEAKERS/); + assert.match(bridge,/Advanced driver recovery/); + assert.match(native,/ack->setProperty\("requestId",[\s\S]*?args\.getProperty\("requestId",juce::var\(\)\)/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); test("strict producer rejects JS Number identities, invalid hardware pins and fake LIVE",()=>{ const cases=[ s=>{s.device.epoch=69;}, diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index fa79c0a69..d342833d3 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -242,8 +242,11 @@ const deviceOpen=Boolean(d?.backend && d.sampleRate>0 && d.enabledOutputs.length>=2); const label=document.getElementById("transport"); + const playback=String(d?.playbackDevice||"unknown output"); + const virtualOut=/VB-Audio Virtual Cable|CABLE Input/i.test(playback); const transport=!deviceOpen?"Audio device not ready": - (d.outputArmed?"Monitoring":"Output muted")+" · "+(d.playbackDevice||"unknown output"); + (d.outputArmed?"MONITOR ON":"MONITOR OFF")+" · OUT "+playback+ + (virtualOut?" · VIRTUAL / NO SPEAKERS":""); if(label && label.textContent!==transport)label.textContent=transport; const warning=document.querySelector?.(".status-bar .warning"); const warningText=!deviceOpen?"NO VERIFIED AUDIO DEVICE": @@ -294,7 +297,7 @@ // 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,pendingDeviceMute=false,deviceChoice=null,deviceResult=""; + deviceRequest=0,pendingDeviceMute=null,deviceChoice=null,deviceResult=""; function openNativeAudioIO(){ if(!devicePanel){ const style=document.createElement("style"); @@ -382,14 +385,24 @@ renderDevicePanel(); }); devicePanel.querySelector("[data-audio-apply]").onclick=()=>{ - if(deviceBusy||!deviceChoice||!deviceInventory?.active)return; + if(deviceBusy||pendingDeviceMute||!deviceChoice||!deviceInventory?.active)return; const draft=deviceChoice,active=deviceInventory.active; if(!draft.backend||!draft.capture||!draft.playback)return; if(hardware?.device?.outputArmed){ - pendingDeviceMute=true; + // Correlate one deliberate MUTE to this Apply. An unrelated ACK + // must never authorize a hardware switch. + const requestId="device-mute-"+(++deviceRequest); + pendingDeviceMute={requestId,epoch:String(hardware.device.epoch)}; + devicePanel.querySelector("[data-audio-apply]").disabled=true; devicePanel.querySelector("[data-audio-active]").textContent= "Muting current output before changing driver…"; - backend.emitEvent("arMixAction",{action:"monitor",value:false}); + backend.emitEvent("arMixAction",{action:"monitor",value:false,requestId}); + window.setTimeout(()=>{ + if(pendingDeviceMute?.requestId!==requestId)return; + pendingDeviceMute=null; + deviceResult="Driver change cancelled: no verified MUTE acknowledgement."; + renderDevicePanel(); + },8000); }else sendDeviceApply(); }; document.body.appendChild(devicePanel); @@ -473,7 +486,8 @@ " → "+active.playbackDevice+" · "+active.rate+" Hz / "+active.buffer+" samples": "No verified audio device. Select a supported input and output."); devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| - !deviceChoice.backend||!deviceChoice.capture||!deviceChoice.playback; + !!pendingDeviceMute||!deviceChoice.backend||!deviceChoice.capture|| + !deviceChoice.playback; } function sendDeviceApply(){ if(!deviceChoice||!deviceInventory?.active)return; @@ -521,8 +535,8 @@ if(tag==="button")el.type="button"; return el; }; - const caption=item("span","more-tools-caption","REAL AUDIO · FIRST SOUND"); - const setup=item("button","tool","Audio Setup"); + const caption=item("span","more-tools-caption","AUDIO / SAFETY"); + const setup=item("button","tool","Audio I/O"); setup.addEventListener("click",()=>{ // Reuse the EXISTING custom driver/endpoint pane. The stock JUCE // selector is reserved for explicitly requested advanced recovery. @@ -569,11 +583,18 @@ }); hardwareNote=item("span","more-tools-caption","Device not initialized"); hardwareNote.style.whiteSpace="normal"; - // Legacy developer-first staging is no longer a user-facing workflow. - // IN is on every mixer strip; emergency MUTE stays accessible here. - caption.textContent="AUDIO / SAFETY"; + // Everyday I/O remains in the one approved /preview/ mixer. Keep the + // raw JUCE selector as an explicitly advanced recovery tool only. inputSelect.hidden=true;routeBtn.hidden=true;armBtn.hidden=true; - menu.append(caption,setup,inputSelect,routeBtn,armBtn,muteBtn,hardwareNote); + const advanced=document.createElement("details"); + advanced.className="arNativeAdvancedRecovery"; + const summary=item("summary","more-tools-caption","Advanced driver recovery"); + const driver=item("button","tool","Open JUCE driver recovery"); + driver.addEventListener("click",()=>{ + backend.emitEvent("arMixAction",{action:"audioSetup"}); + }); + advanced.append(summary,driver); + menu.append(caption,setup,muteBtn,hardwareNote,advanced); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. const toolbar=document.querySelector(".command-bar"); @@ -661,7 +682,8 @@ // Native publisher + engine own the accepted graph; refresh the // UI only from a subsequent authoritative snapshot. controller.subscribe(); - if(p.autoListen && hardware?.device?.epoch===String(p.epoch)) { + if(p.autoListen && row?.main===true && + hardware?.device?.epoch===String(p.epoch)) { // Selecting the first physical INPUT is user intent to monitor, // no second ARM button. The C++ liveOutputArmFault gate still // refuses invalid outputs and never opens an unrelated device. @@ -685,11 +707,15 @@ }); backend.addEventListener("arMixAudioArmAck", ack=>{ if(pendingDeviceMute){ - pendingDeviceMute=false; - if(ack?.ok===true && ack?.armed===false)sendDeviceApply(); + // Reject any stale/unrelated ACK and any device epoch change. + if(ack?.requestId!==pendingDeviceMute.requestId)return; + const epochMatches=String(ack?.deviceEpoch)===pendingDeviceMute.epoch; + pendingDeviceMute=null; + if(ack?.ok===true && ack?.armed===false && epochMatches) + sendDeviceApply(); else if(devicePanel){ - deviceResult="Device change rejected: existing output could not be muted."; - devicePanel.querySelector("[data-audio-active]").textContent=deviceResult; + deviceResult="Device change rejected: MUTE or audio epoch not verified."; + renderDevicePanel(); } return; } @@ -738,6 +764,14 @@ backend.emitEvent("arMixAction",{action:"routingSourceSwitch", requestId,channel,mode:choice.mode,left:choice.left,right:choice.right, deviceEpoch:ep,revision:rev}); + // An absent ACK cannot freeze further source changes indefinitely. + // Timeout belongs to WebView control logic, not the realtime callback. + window.setTimeout(()=>{ + if(nativeUiSourcePending?.requestId!==requestId)return; + nativeUiSourcePending=null; + status("CH "+(channel+1)+" INPUT · response timed out; unchanged"); + controller.subscribe(); + },8000); status("CH "+(channel+1)+" INPUT · verifying physical routing"); return true; } @@ -845,7 +879,7 @@ }); window.__ARMIX_NATIVE_M2__ = nativeHooks; const descriptor = Object.freeze({ - source:"site/preview-v2 + site/preview-buttons", + source:"/preview/ approved compiled Pages GUI", pagesRoute:"/preview/", nativeTransport:connected, get acceptedGraphConnected(){return flags.acceptedGraphConnected;}, From 00fea7df095a87d294e1fd69d47e98e34de1dd06 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:00:32 +0700 Subject: [PATCH 006/219] Update First Sound regression to new one-panel Audio I/O operator wording --- tests/approved_native_m2_contract.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 3e0bed379..39a729062 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -475,7 +475,7 @@ test("native Windows operator can explicitly patch first physical input, arm and const js=read("web/approved-native-bridge.js"); const main=read("src/Main.cpp"); const engine=read("src/LiveAudioEngine.h"); - assert.match(js,/REAL AUDIO · FIRST SOUND/); + assert.match(js,/AUDIO \/ SAFETY/); assert.match(js,/function openNativeAudioIO\(\)/); assert.match(js,/action:"audioDeviceInventory"/); assert.match(js,/action:"audioDeviceApply"/); From 51995eaeb6e8825a0c323eca401d33f59c56a59b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:16:56 +0700 Subject: [PATCH 007/219] Allow unqualified exact-SHA Windows hardware test ZIP for approved /preview/ DAW First Sound PR Reuse the existing native build, packaging and verification. Upload one clearly marked nonrelease candidate without opening another workflow or changing RT DSP. --- .github/workflows/p1-windows.yml | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index d3976eef7..195b73707 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -139,33 +139,33 @@ jobs: - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT - if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' }} + if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} shell: pwsh run: | & ./scripts/package_native_windows.ps1 -BuildDir build -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Stage ONLY legally approved and host-qualified Factory VST3 bundles - if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' }} + if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} shell: pwsh run: | python scripts/factoryfx_release_bundle.py stage --lock config/factoryfx-approved-releases.json --output dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Independently verify release ZIP and embedded GUI/engine before upload - if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' }} + if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} shell: pwsh run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } # P0 PR #414 is the ONLY additional FAT candidate: physical mouse/GPU # proof requires its exact Windows EXE, never a stable release. - # Ordinary engine PRs compile/CTest without wasting package/ZIP work. + # Permit the one #418 First Sound candidate only for exact-SHA hardware FAT.\n # Ordinary engine PRs compile/CTest without wasting package/ZIP work. # Release-integration PRs and main/manual runs package and verify, but never silently publish a stable release. # This single M4 FAT branch is explicitly allowed to upload an # UNQUALIFIED experimental ZIP for real physical hardware testing. - uses: actions/upload-artifact@v4 - if: ${{ github.event_name != 'pull_request' || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' }} + if: ${{ github.event_name != 'pull_request' || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} with: - name: ${{ github.event_name == 'pull_request' && github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' && 'ArSonMix-P0-EXPERIMENTAL-Pointer-Latency-FAT-Windows-x64' || github.event_name == 'pull_request' && 'ArSonMix-M4-EXPERIMENTAL-Hardware-FAT-Windows-x64' || 'ArSonMix-GUI10CH-P012-Verified-Hardware-FAT-Windows-x64' }} + name: ${{ github.event_name == 'pull_request' && github.head_ref == 'integration/daw-direct-hardware-input-20261105' && 'ArSonMix-P0-DAW-First-Sound-UNQUALIFIED-Windows-x64' || github.event_name == 'pull_request' && github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' && 'ArSonMix-P0-EXPERIMENTAL-Pointer-Latency-FAT-Windows-x64' || github.event_name == 'pull_request' && 'ArSonMix-M4-EXPERIMENTAL-Hardware-FAT-Windows-x64' || 'ArSonMix-GUI10CH-P012-Verified-Hardware-FAT-Windows-x64' }} path: dist/ if-no-files-found: error retention-days: 14 From 3d633f9c3b45bb22b40ea26b371894b32238c4ff Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:20:15 +0700 Subject: [PATCH 008/219] First Sound hardware safety: block known same VB-Cable feedback and non-admitted auto-monitor Keep the approved /preview/ one-click source routing, but do not unmute unless real ChannelId PCM control authority is admitted. Native liveOutputArmFault rejects an identifiable VB-Cable capture/output self-loop, independently of JS. Add regression contracts. No RT callback changes. --- src/LiveAudioEngine.h | 19 ++++++++++++++++ tests/approved_native_m2_contract.test.cjs | 13 +++++++++++ web/approved-native-bridge.js | 25 ++++++++++++++++------ 3 files changed, 51 insertions(+), 6 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 20bc4039e..a864556e1 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -295,12 +295,31 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // FAST1: control-thread output arm preflight; physical MUTE always works. // No auto-arm on device reopen, no RT allocation or driver reconfiguration. + // Names are only an extra conservative policy for one identifiable + // VB-Cable *self loop*. Never guess that an arbitrary virtual endpoint + // equals another physical card; the native output gate remains primary. + static bool knownVirtualCableFeedbackPair(const juce::String& capture, + const juce::String& playback) noexcept + { + const auto in=capture.toLowerCase(),out=playback.toLowerCase(); + return (in.contains("vb-audio") || out.contains("vb-audio")) && + in.contains("cable output") && out.contains("cable input"); + } + juce::String liveOutputArmFault() { auto* device=deviceManager_.getCurrentAudioDevice(); if (!device || !device->isOpen() || !directFence_.permitted() || independent_.active()) return "Select a verified DIRECT ASIO/Windows Audio device first."; + // Do not turn on a known VB-Cable -> same VB-Cable feedback loop, + // even if JS or an external host sends a monitor request. CONTROL + // thread only; no DSP callback cost, no implicit hardware redirect. + juce::AudioDeviceManager::AudioDeviceSetup currentSetup; + deviceManager_.getAudioDeviceSetup(currentSetup); + if (knownVirtualCableFeedbackPair(currentSetup.inputDeviceName, + currentSetup.outputDeviceName)) + return "MONITOR OFF: VB-Cable capture/playback self-loop. Choose a physical output or separate virtual cable."; if (routeReconfiguring_.load(std::memory_order_acquire) || handoff_.busy() || !dryRoutingLab_.active() || !dryRoutingLab_.ready() || !dryRoutingLab_.hasExplicitRoute()) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 39a729062..b5136342b 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -139,6 +139,19 @@ test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, // can be submitted by the native bridge. Only the native injected source. assert.doesNotMatch(bridge,/channelOptions\(t,'input'\)/); }); +test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ + const engine=read("src/LiveAudioEngine.h"); + const bridge=read("web/approved-native-bridge.js"); + assert.match(engine,/knownVirtualCableFeedbackPair/); + assert.match(engine,/in\.contains\("cable output"\) && out\.contains\("cable input"\)/); + assert.match(engine,/currentSetup\.inputDeviceName/); + assert.match(engine,/currentSetup\.outputDeviceName/); + assert.match(engine,/MONITOR OFF: VB-Cable capture\/playback self-loop/); + assert.match(bridge,/const virtualCableFeedbackPair=/); + assert.match(bridge,/next\.nativeChannelIdPcmActive===true/); + assert.match(bridge,/if\(firstListen && !virtualCableFeedbackPair\(\)\)/); + assert.match(bridge,/VB-Cable feedback loop; select physical playback/); +}); test("single /preview/ GUI: channel IN, actual OUT and correlated device safety ACK",()=>{ const pages=read("scripts/build_pages.py"); const builder=read("scripts/build_approved_native_gui.py"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index d342833d3..77dcda986 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -231,6 +231,12 @@ scope.render?.(); } + const virtualCableFeedbackPair=()=>{ + const capture=String(hardware?.device?.captureDevice||"").toLowerCase(); + const playback=String(hardware?.device?.playbackDevice||"").toLowerCase(); + return (capture.includes("vb-audio")||playback.includes("vb-audio")) && + capture.includes("cable output") && playback.includes("cable input"); + }; const deviceReady=()=>!!(hardware?.device?.backend && hardware.device.sampleRate>0 && hardware.device.enabledInputs.length>0 && @@ -682,15 +688,22 @@ // Native publisher + engine own the accepted graph; refresh the // UI only from a subsequent authoritative snapshot. controller.subscribe(); - if(p.autoListen && row?.main===true && - hardware?.device?.epoch===String(p.epoch)) { - // Selecting the first physical INPUT is user intent to monitor, - // no second ARM button. The C++ liveOutputArmFault gate still - // refuses invalid outputs and never opens an unrelated device. + const firstListen=p.autoListen && row?.main===true && + next.nativeChannelIdPcmActive===true && + hardware?.device?.epoch===String(p.epoch); + // Never arm physical audio when the GUI still lacks admitted PCM + // controls, or when capture and playback feed the *same* VB Cable. + // Native C++ enforces the feedback policy a second time. + if(firstListen && !virtualCableFeedbackPair()) { backend.emitEvent("arMixAction",{action:"monitor",value:true, expectedEpoch:p.epoch,expectedRevision:Number(next.revision)}); } - status("CH "+(p.channel+1)+" native input accepted"); + if(firstListen && virtualCableFeedbackPair()) + status("MONITOR OFF · VB-Cable feedback loop; select physical playback"); + else if(p.autoListen && !firstListen) + status("CH "+(p.channel+1)+" routed · PCM controls not yet admitted; MONITOR OFF"); + else + status("CH "+(p.channel+1)+" native input accepted"); } else { status("NATIVE INPUT REJECTED · "+(ack?.error||"stale routing")); controller.subscribe(); From 3e099fdca0cc5c625ffef2c3fe3c3098eacfbaab Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:39:43 +0700 Subject: [PATCH 009/219] Reconcile real G0/M4 controls and first-class output route with approved mixer Expose verified 10-strip native M4 control/PCM readback when ChannelId graph not admitted; accept bounded epoch/revision-gated fader/mute/pan/solo and master actions with correlated ACK. Add true MAIN/NONE output routing to existing M4 compile owner. Support IN=None as verified native source-clear, avoiding misleading demo-only choices. All work stays off RT callback. --- integration/ApprovedNativeRuntimeSnapshot.h | 41 ++++++++++ src/Main.cpp | 88 +++++++++++++++++++++ src/NativeVerifiedSourcePatch.h | 17 ++-- 3 files changed, 139 insertions(+), 7 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 77014352a..51b7b4990 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -124,6 +124,47 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, } } firstSound->setProperty("channels",juce::var(verifiedChannels)); + // Native M4 remains the real 10-channel callback before ChannelId + // admission, including a stable source patch under armed monitoring. + // Publish only verified PCM controls and measured per-channel peaks. + // Never infer controls from the Pages reference model. + if(physicalReady && boolIs(route,"hasAcceptedRoute",true) && + !boolIs(route,"nativeChannelIdPcmActive",true) && + verifiedChannels.size()==10) { + const auto controls=route.getProperty("channelControls",{}); + const auto levelsL=route.getProperty("channelPeaksL",{}); + const auto levelsR=route.getProperty("channelPeaksR",{}); + const auto* ctl=controls.getArray(); + const auto* l=levelsL.getArray(); + const auto* r=levelsR.getArray(); + bool valid=ctl && l && r && ctl->size()==10 && + l->size()==10 && r->size()==10; + for(int i=0;valid && i<10;++i) { + const auto row=ctl->getReference(i); + double db=0.,pan=0.,peakL=0.,peakR=0.; + valid=row.isObject() && + nativeV8Number(row.getProperty("db",{}),db) && + nativeV8Number(row.getProperty("pan",{}),pan) && + nativeV8Number(l->getReference(i),peakL) && + nativeV8Number(r->getReference(i),peakR) && + db>=-60.01 && db<=10.01 && + pan>=-100.01 && pan<=100.01 && + peakL>=0. && peakR>=0. && + row.getProperty("mute",{}).isBool() && + row.getProperty("solo",{}).isBool(); + } + if(valid) { + firstSound->setProperty("channelControls",controls); + firstSound->setProperty("channelPeaksL",levelsL); + firstSound->setProperty("channelPeaksR",levelsR); + double masterDb=0.; + if(nativeV8Number(live.getProperty("masterDb",{}),masterDb) && + masterDb>=-60.01 && masterDb<=10.01) + firstSound->setProperty("masterDb",masterDb); + const auto masterMute=live.getProperty("masterMute",{}); + if(masterMute.isBool())firstSound->setProperty("masterMute",masterMute); + } + } // Do not write the route to the graph or change native capability flags. snapshot.getDynamicObject()->setProperty("legacyM4",juce::var(firstSound.release())); return physicalReady; diff --git a/src/Main.cpp b/src/Main.cpp index a24c2d756..364209e43 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1454,6 +1454,94 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // M1 RT source switch on an existing physical channel. Unlike // structural routingDryApply, it does not unpatch outputs, rebuild // VST3s, or restart the device; input PCM fades inside one graph. + // F0: independently acknowledged existing M4 PCM controls during + // G0, before ChannelId admission. Do not send GUI demo parameters + // or mutate a second DSP. One control-thread atomic update only. + if(action=="routingM4Control"){ + const auto requestId=args.getProperty("requestId",juce::var()).toString(); + const int channel=static_cast(args.getProperty("channel",-1)); + const auto name=args.getProperty("parameter",juce::var()).toString(); + const auto val=args.getProperty("controlValue",juce::var()); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const auto state=engine_.status(); + const auto route=state.getProperty("dryRoutingLab",{}); + const auto currentEp=route.getProperty("epoch",juce::var()); + const auto currentRv=route.getProperty("revision",juce::var()); + const bool tokenOk=(ep.isInt()||ep.isInt64()) && + (rv.isInt()||rv.isInt64()) && + static_cast(ep)>0 && + static_cast(ep)==static_cast(currentEp) && + static_cast(rv)==static_cast(currentRv); + const bool ready=tokenOk && requestId.startsWith("m4-") && + requestId.length()<=48 && + !nativeShowBusy_ && !studioBackupBusy_ && + static_cast(route.getProperty("hasAcceptedRoute",false)) && + !static_cast(route.getProperty("nativeChannelIdPcmActive",false)) && + !static_cast(route.getProperty("topologyFault",true)) && + engine_.directRouteAuthorized() && !engine_.independentClockActive(); + const bool boolean=(name=="mute"||name=="solo"||name=="masterMute"); + const double numeric=boolean?0.:static_cast(val); + const bool typeOk=boolean?val.isBool():(val.isDouble()||val.isInt()); + const bool master=(channel==-1 && + (name=="masterGain"||name=="masterMute")); + const bool lane=(channel>=0 && channel=-100.&&numeric<=100.): + (numeric>=-60.&&numeric<=10.)); + bool applied=ready && typeOk && (master||lane) && + (boolean||std::isfinite(numeric)) && range; + if(applied && lane) + applied=engine_.setDryRoutingLabParameter(channel, + static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + name,val.isBool()?(bool(val)?1.f:0.f): + static_cast(numeric)); + else if(applied && name=="masterGain") + engine_.setMasterGainDb(static_cast(numeric)); + else if(applied && name=="masterMute") + engine_.setMasterMuted(bool(val)); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("ok",applied); + ack->setProperty("error",applied?juce::String(): + juce::String("Stale G0 route, invalid parameter or PCM authority changed")); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixM4ControlAck", + juce::var(ack.release())); + // ACK is not PCM proof; the bridge requires a LATER snapshot. + return; + } + // A visible /preview/ channel OUT changes this same installed M4 + // topology. Only actual MAIN / NONE semantics are supported here. + if(action=="routingChannelPatch"){ + const int requestId=static_cast(args.getProperty("requestId",0)); + const int channel=static_cast(args.getProperty("channel",-1)); + const auto target=args.getProperty("target",juce::var()).toString(); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + juce::String error="OUT: stale identity, unsupported destination or busy Show"; + if(requestId>0 && channel>=0 && channel(static_cast(ep)), + static_cast(static_cast(rv)), + "SET_PRIMARY_OUT",target); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("channel",channel); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixChannelPatchAck",juce::var(ack.release())); + if(error.isNotEmpty())emitNotice(error,true); + return; + } if(action=="routingSourceSwitch"){ const int requestId=static_cast(args.getProperty("requestId",0)); const int channel=static_cast(args.getProperty("channel",-1)); diff --git a/src/NativeVerifiedSourcePatch.h b/src/NativeVerifiedSourcePatch.h index ca9927d87..b92bd5c80 100644 --- a/src/NativeVerifiedSourcePatch.h +++ b/src/NativeVerifiedSourcePatch.h @@ -23,9 +23,12 @@ struct NativeVerifiedSourcePatch final { actualRevision>static_cast(std::numeric_limits::max()) || !accepted.isObject() || channel<0 || channel>=10) return "SOURCE: stale device epoch or invalid native channel"; - if(mode!="MONO"&&mode!="STEREO") - return "SOURCE: MONO or STEREO mode required"; - if(physicalLeft<0 || enabledPhysicalPorts.empty()) + if(mode!="NONE"&&mode!="MONO"&&mode!="STEREO") + return "SOURCE: NONE, MONO or STEREO mode required"; + const bool clearing=mode=="NONE"; + if(clearing && (physicalLeft!=-1||physicalRight!=-1)) + return "SOURCE: clearing input cannot supply physical pins"; + if(!clearing && (physicalLeft<0 || enabledPhysicalPorts.empty())) return "SOURCE: select an enabled physical capture pin"; if(static_cast(accepted.getProperty("deviceEpoch",juce::var(-1))) != static_cast(actualEpoch)) @@ -35,8 +38,8 @@ struct NativeVerifiedSourcePatch final { if(port==physicalLeft)validLeft=true; if(port==physicalRight)validRight=true; } - if(!validLeft || (mode=="STEREO" && - (!validRight || physicalLeft==physicalRight))) + if(!clearing && (!validLeft || (mode=="STEREO" && + (!validRight || physicalLeft==physicalRight)))) return "SOURCE: STEREO requires two distinct active physical pins; MONO accepts one"; // JUCE var assignment shares the underlying DynamicObject. Deep // clone before touching a row, or failed prepare would silently @@ -62,11 +65,11 @@ struct NativeVerifiedSourcePatch final { const auto width=row->getProperty("channelFormat").toString(); if(width!="MONO" && width!="STEREO") return "SOURCE: native processing format missing or invalid"; - row->setProperty("sourceKind","PHYSICAL"); + row->setProperty("sourceKind",clearing?"NONE":"PHYSICAL"); row->setProperty("sourceFormat",mode); } row->setProperty("mode",mode); - row->setProperty("left",physicalLeft); + row->setProperty("left",clearing?-1:physicalLeft); row->setProperty("right",mode=="STEREO"?physicalRight:-1); // The existing M4 producer handles revision/epoch publication and // fails back to its prior accepted graph on any bad plugin/routing. From b39fe17ad03533be299110b18a3f06225a2aee04 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:42:46 +0700 Subject: [PATCH 010/219] Make /preview/ actual M4 PCM controls and OUT native with low-churn readback Bind stable hardware ordinals through UI reorder, render M4 controls only when changed, cache real PCM meter fills, ACK fader/mute/pan/solo and MAIN, route OUT to installed M4 native graph rather than public demo, keep explicit MONITOR button and selective first-route listen. Limit options to supported route and driver outputs. No DSP callbacks or JS audio. --- scripts/build_approved_native_gui.py | 4 +- tests/approved_native_m2_contract.test.cjs | 25 +++ web/approved-native-bridge.js | 236 ++++++++++++++++++++- 3 files changed, 255 insertions(+), 10 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 0c4fa7111..125292a5f 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -62,7 +62,9 @@ def accepted_pages_html() -> str: ("const channelOptions=(t,type)=>{\n", "const channelOptions=(t,type)=>{\n" " if(type==='input'&&window.__JUCE__?.backend)\n" - " return window.__ARMIX_NATIVE_M2__?.inputChoices?.(t)||['None'];\n"), + " return window.__ARMIX_NATIVE_M2__?.inputChoices?.(t)||['None'];\n" + " if(type==='output'&&window.__JUCE__?.backend)\n" + " return window.__ARMIX_NATIVE_M2__?.outputChoices?.(t)||[t.output];\n"), ("function wireGraphCommit(ops,{record=true}={}){\n", "function wireGraphCommit(ops,{record=true}={}){\n" " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.consumeWire?.(ops);return false;}\n"), diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index b5136342b..f6e8ebf83 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -139,6 +139,31 @@ test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, // can be submitted by the native bridge. Only the native injected source. assert.doesNotMatch(bridge,/channelOptions\(t,'input'\)/); }); +test("DAW G0 native M4 controls, source clear, OUT & monitoring are real",()=>{ + const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/Main.cpp"); + const source=read("src/NativeVerifiedSourcePatch.h"); + const builder=read("scripts/build_approved_native_gui.py"); + assert.match(producer,/firstSound->setProperty\("channelControls",controls\)/); + assert.match(producer,/firstSound->setProperty\("channelPeaksL",levelsL\)/); + assert.match(bridge,/function paintM4Fallback\(next\)/); + assert.match(bridge,/function sendM4Control\(parameter,t,value\)/); + assert.match(bridge,/action:"routingM4Control"/); + assert.match(bridge,/action:"routingChannelPatch"/); + assert.match(bridge,/const channel=m4Index\(t\)/); + assert.match(bridge,/data-native-monitor/); + assert.match(bridge,/const firstListen=p.autoListen/); + assert.match(bridge,/next\.nativeChannelIdPcmActive===true \|\|/); + assert.match(native,/if\(action=="routingM4Control"\)/); + assert.match(native,/engine_\.setDryRoutingLabParameter\(channel,/); + assert.match(native,/if\(action=="routingChannelPatch"\)/); + assert.match(native,/engine_\.repatchDryRoutingLabChannel\(channel,/); + assert.match(source,/if\(mode!="NONE"&&mode!="MONO"&&mode!="STEREO"\)/); + assert.match(source,/row->setProperty\("sourceKind",clearing\?"NONE":"PHYSICAL"\)/); + assert.match(builder,/type==='output'/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 77dcda986..9e259f897 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -207,7 +207,97 @@ x.left===row.left && x.right===row.right); return exact?.label||"None"; }; - let lastM4UiSignature="",nativeUiSourcePending=null; + // 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)? + scope.tracks.filter(t=>t.kind==="audio").slice(0,10).map(t=>t.id):[]; + const m4Index=t=>t?.kind==="audio"?m4TrackIds.indexOf(t.id):-1; + let lastM4UiSignature="",lastM4Controls="",nativeUiSourcePending=null; + let pendingOutputPatch=null,m4RequestSerial=0,outputSerial=7000; + const m4Meters=new Map(); + const m4Verified=()=>{ + const m=legacy(),d=hardware?.device; + return !flags.acceptedGraphConnected && m?.active===true && + m.routeAccepted===true && Array.isArray(m.channelControls) && + m.channelControls.length===10 && m.channels?.length===10 && + safeNativeCounter(d?.epoch)!==null && + safeNativeCounter(m.routingRevision)!==null; + }; + function sendM4Control(parameter,t,value) { + if(!m4Verified() || (typeof value!=="boolean"&&!Number.isFinite(value))) + return false; + const channel=t?.kind==="master"?-1:m4Index(t); + if(channel<0 && t?.kind!=="master")return false; + const ep=safeNativeCounter(hardware.device.epoch), + rev=safeNativeCounter(legacy().routingRevision); + if(ep===null||rev===null)return false; + const requestId="m4-"+(++m4RequestSerial); + backend.emitEvent("arMixAction",{action:"routingM4Control", + requestId,channel,parameter,controlValue:value,deviceEpoch:ep, + revision:rev}); + window.setTimeout(()=>{ + if(requestId!==lastM4Request)return; + lastM4Request=""; + status("M4 control response timed out; verifying actual native readback"); + controller?.subscribe(); + },8000); + lastM4Request=requestId; + return true; + } + let lastM4Request=""; + function paintM4Fallback(next) { + if(!m4Verified()||!Array.isArray(scope?.tracks))return; + const m=next.raw.legacyM4,ctl=m.channelControls; + const controlSignature=JSON.stringify([next.device.epoch, + m.routingRevision,ctl,m.masterDb,m.masterMute]); + if(controlSignature!==lastM4Controls) { + lastM4Controls=controlSignature; + let changed=false; + for(let i=0;i<10;i++){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]),c=ctl[i]; + if(!t||!c||!Number.isFinite(c.db)||!Number.isFinite(c.pan)|| + typeof c.mute!=="boolean"||typeof c.solo!=="boolean")return; + if(Math.abs(t.level-c.db)>.015){t.level=c.db;changed=true;} + if(Math.abs(t.pan-c.pan)>.015){t.pan=c.pan;changed=true;} + if(t.mute!==c.mute){t.mute=c.mute;changed=true;} + if(t.solo!==c.solo){t.solo=c.solo;changed=true;} + } + if(scope.master && Number.isFinite(m.masterDb) && + Math.abs(scope.master.level-m.masterDb)>.015){ + scope.master.level=m.masterDb;changed=true; + } + if(scope.master && typeof m.masterMute==="boolean" && + scope.master.mute!==m.masterMute){ + scope.master.mute=m.masterMute;changed=true; + } + if(changed){m4Meters.clear();scope.render?.();} + } + // Only measured JUCE callback peaks are painted. Cache actual live DOM + // fills to avoid repeated selector searches for every timer/signal tick. + if(!Array.isArray(m.channelPeaksL)||!Array.isArray(m.channelPeaksR)|| + !scope?.displayMeterDbfs)return; + const now=performance.now(); + for(let i=0;i<10;i++){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); + if(!t)continue; + let entry=m4Meters.get(t.id); + if(!entry?.root?.isConnected){ + const root=document.querySelector('.strip[data-id="'+t.id+'"]'); + if(!root)continue; + entry={root,left:root.querySelector(".meter-fill.left"), + right:root.querySelector(".meter-fill.right")}; + m4Meters.set(t.id,entry); + } + for(const side of ["left","right"]){ + const peak=side==="left"?m.channelPeaksL[i]:m.channelPeaksR[i]; + if(!Number.isFinite(peak)||peak<0)continue; + const fill=entry[side];if(!fill)continue; + scope.displayMeterDbfs(fill,peak===0?-90: + Math.max(-90,Math.min(6,20*Math.log10(peak))), + now,"native-m4:"+i+":"+side); + } + } + } function refreshRealM4Inputs(next){ if(!scope?.tracks || next?.admitted || !Array.isArray(scope.tracks) || scope.tracks.length<10) return; @@ -219,15 +309,15 @@ if(signature===lastM4UiSignature)return; lastM4UiSignature=signature; for(let i=0;i<10;++i){ - const t=scope.tracks[i]; + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); if(t?.kind!=="audio")continue; const row=Array.isArray(rows)&&rows.length===10?rows[i]:null; t.input=inputLabelFor(row); if(row && typeof row.main==="boolean") t.output=row.main?"Master":"SOURCE ONLY (No Main)"; } - // One existing canonical mixer renderer, updated only when the actual - // hardware topology/route changes, never on periodic PCM meter frames. + // One canonical renderer, only on a real routing/topology change. + m4Meters.clear(); scope.render?.(); } @@ -250,6 +340,19 @@ const label=document.getElementById("transport"); const playback=String(d?.playbackDevice||"unknown output"); const virtualOut=/VB-Audio Virtual Cable|CABLE Input/i.test(playback); + const monitorButton=document.querySelector?.("[data-native-monitor]"); + if(monitorButton){ + monitorButton.textContent=d?.outputArmed?"MONITOR OFF":"MONITOR ON"; + monitorButton.title=d?.outputArmed? + "Mute actual MAIN output immediately":"Listen through verified MAIN hardware output"; + monitorButton.disabled=!d?.outputArmed && !deviceReady(); + monitorButton.dataset.armed=String(!!d?.outputArmed); + } + if(scope?.master && deviceOpen && + scope.master.output!==playback){ + scope.master.output=playback; + if(!next?.admitted)scope.render?.(); + } const transport=!deviceOpen?"Audio device not ready": (d.outputArmed?"MONITOR ON":"MONITOR OFF")+" · OUT "+playback+ (virtualOut?" · VIRTUAL / NO SPEAKERS":""); @@ -610,19 +713,40 @@ io.title="Select ASIO/WASAPI driver and capture/playback device"; io.addEventListener("click",openNativeAudioIO); toolbar.insertBefore(io,document.getElementById("moreTools")); + const monitor=item("button","tool","MONITOR ON"); + monitor.dataset.nativeMonitor="true"; + monitor.addEventListener("click",()=>{ + const armed=hardware?.device?.outputArmed===true; + if(!armed && (!deviceReady()||legacy()?.routeAccepted!==true || + virtualCableFeedbackPair())){ + status("MONITOR OFF · select real input and safe playback device"); + return; + } + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(!armed&&(ep===null||rev===null))return; + backend.emitEvent("arMixAction",{action:"monitor",value:!armed, + requestId:"manual-monitor-"+(++m4RequestSerial), + ...(armed?{}:{expectedEpoch:ep,expectedRevision:rev})}); + status(armed?"Hardware MUTE requested":"MAIN monitor verifying hardware route"); + }); + toolbar.insertBefore(monitor,io); } updateHardwarePanel(hardware); } function onNativeReadback(next) { updateHardwarePanel(next); + paintM4Fallback(next); const caps=next?.graph?.capabilities; const nativeAdmitted=next.admitted && caps?.callbackOwnsChannelIds===true; if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; lastPaintedSignature=""; stopDemo(); - status("NATIVE G0 · PATCH CH1/ARM tersedia pada device terverifikasi; kontrol ChannelId/WIRE menunggu PCM native."); + status(m4Verified()? + "NATIVE M4 · real PCM faders and meters · ChannelId buses not yet admitted": + "NATIVE G0 · choose real hardware IN on any channel"); return; } // Control readback may change at the SAME structural graph revision. @@ -689,7 +813,8 @@ // UI only from a subsequent authoritative snapshot. controller.subscribe(); const firstListen=p.autoListen && row?.main===true && - next.nativeChannelIdPcmActive===true && + (next.nativeChannelIdPcmActive===true || + (Array.isArray(next.channelControls)&&next.channelControls.length===10)) && hardware?.device?.epoch===String(p.epoch); // Never arm physical audio when the GUI still lacks admitted PCM // controls, or when capture and playback feed the *same* VB Cable. @@ -718,6 +843,24 @@ }else status("NATIVE PATCH REJECTED: "+(ack?.error||"stale physical route")); updateHardwarePanel(hardware); }); + backend.addEventListener("arMixM4ControlAck",ack=>{ + if(ack?.requestId===lastM4Request)lastM4Request=""; + if(ack?.ok!==true) + status("NATIVE M4 REJECTED · "+(ack?.error||"stale graph")); + controller.subscribe(); // accepted producer snapshot is authoritative + }); + backend.addEventListener("arMixChannelPatchAck",ack=>{ + if(!pendingOutputPatch||ack?.requestId!==pendingOutputPatch.requestId)return; + const p=pendingOutputPatch; + pendingOutputPatch=null; + const row=ack?.state?.acceptedRoute?.channels?.[p.channel]; + if(ack?.ok===true && Number(ack.state?.epoch)===p.epoch && + row?.main===(p.target==="MAIN")) + status("CH "+(p.channel+1)+" OUT accepted; verifying native readback"); + else status("CH "+(p.channel+1)+" OUT rejected · "+ + (ack?.error||"stale route")); + controller.subscribe(); + }); backend.addEventListener("arMixAudioArmAck", ack=>{ if(pendingDeviceMute){ // Reject any stale/unrelated ACK and any device epoch change. @@ -745,6 +888,18 @@ if(t?.kind!=="audio")return ["None"]; return inputChoicesFor().map(x=>x.label); }, + outputChoices(t) { + if(t?.kind==="master") + return [String(hardware?.device?.playbackDevice||t.output||"Choose audio output")]; + if(t?.kind==="audio"){ + // M4 accepts MAIN or source-only. Bus routing is via native WIRE, + // never pretend the demo's other destinations have native PCM. + const options=["Master","SOURCE ONLY (No Main)"]; + if(t.output && !options.includes(t.output))options.push(t.output); + return options; + } + return [t?.output||"None"]; + }, consumeField(event) { if (!connected)return false; const el=event.target,field=el?.dataset?.field; @@ -756,7 +911,7 @@ // ChannelId admission. A physical mixer strip can receive ANY active // source, including the very first source in an unpatched session. if(event.type!=="change")return true; - const channel=scope?.tracks?.findIndex?.(x=>x.id===t.id)??-1; + const channel=m4Index(t); const choice=inputChoicesFor().find(x=>x.label===el.value); const ep=safeNativeCounter(hardware?.device?.epoch); const rev=safeNativeCounter(legacy()?.routingRevision); @@ -788,7 +943,52 @@ status("CH "+(channel+1)+" INPUT · verifying physical routing"); return true; } + if(field==="output"){ + if(event.type!=="change")return true; + if(t.kind==="master"){ + el.value=t.output;openNativeAudioIO();return true; + } + const channel=m4Index(t),target=el.value==="Master"?"MAIN": + el.value==="SOURCE ONLY (No Main)"?"NONE":null; + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(channel<0||target===null||ep===null||rev===null || + pendingOutputPatch||!deviceReady()){ + status("OUT requires a native MAIN/source-only route; unchanged"); + el.value=t.output;return true; + } + if(el.value===t.output)return true; + const requestId=++outputSerial; + pendingOutputPatch={requestId,channel,target,epoch:ep}; + el.value=t.output; + backend.emitEvent("arMixAction",{action:"routingChannelPatch", + requestId,channel,target,deviceEpoch:ep,revision:rev}); + window.setTimeout(()=>{ + if(pendingOutputPatch?.requestId!==requestId)return; + pendingOutputPatch=null; + status("OUT response timed out; refreshing accepted native route"); + controller.subscribe(); + },8000); + return true; + } if (!flags.acceptedGraphConnected) { + if(m4Verified()){ + if(t.kind==="master" && field==="level"){ + if(event.type==="change" && Number.isFinite(Number(el.value))) + sendM4Control("masterGain",t,Number(el.value)); + return true; + } + if(m4Index(t)>=0 && (field==="level"||field==="pan")){ + if(event.type!=="change")return true; + const numeric=Number(el.value); + const value=field==="pan"&& + !el.dataset.panKeyboard&&!el.dataset.panAltPointer&& + Math.abs(numeric)<=12?0:numeric; + if(!sendM4Control(field==="level"?"faderDb":"pan",t,value)) + status("G0 native control rejected; restoring accepted readback"); + return true; + } + } if (field==="level")el.value=String(t.level); else if (field==="pan")el.value=String(t.pan); status("NATIVE: ChannelId PCM not admitted; control unchanged"); @@ -831,6 +1031,16 @@ if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action)) return !["wireExpand","wireSource","wireRoute"].includes(action); if (action==="mute"||action==="solo") { + if(m4Verified() && t.kind==="master" && action==="mute"){ + if(!sendM4Control("masterMute",t,!t.mute)) + status("Native MAIN mute rejected"); + return true; + } + if(m4Verified()&&m4Index(t)>=0){ + if(!sendM4Control(action,t,!t[action])) + status("Native M4 mute/solo rejected"); + return true; + } const key=action==="mute"?"SET_MUTE":"SET_SOLO"; intent(key,t,{value:!t[action],enabled:!t[action]});return true; } @@ -883,8 +1093,14 @@ consumeUndo() {if (!connected)return false;status("NATIVE: WIRE undo requires accepted native transaction");return true;}, consumeDoubleClick(event,t) { if (!connected)return false; - if (event.target.classList.contains("fader"))intent("SET_FADER",t,{valueDb:0}); - else if(event.target.classList.contains("center-pan"))intent("SET_PAN",t,{value:0}); + if (event.target.classList.contains("fader")){ + if(m4Verified())sendM4Control(t?.kind==="master"?"masterGain":"faderDb",t,0); + else intent("SET_FADER",t,{valueDb:0}); + } + else if(event.target.classList.contains("center-pan")){ + if(m4Verified())sendM4Control("pan",t,0); + else intent("SET_PAN",t,{value:0}); + } else status("NATIVE: identity editor unavailable until native ACK contract"); return true; }, @@ -908,6 +1124,8 @@ // Presentation-only bank/selection remains available. document.addEventListener("pointerdown",event=>{ if (flags.acceptedGraphConnected) return; + const t=scope?.findTrack?.(event.target); + if(m4Verified() && (t?.kind==="audio"||t?.kind==="master"))return; if (!event.target.closest?.(".fader-box,.center-pan")) return; event.preventDefault();event.stopImmediatePropagation(); status("NATIVE G0: physical gain/pan unavailable until engine graph admission"); From ba269342f2fc501d729827c7fe97e47df08e1a4c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:44:06 +0700 Subject: [PATCH 011/219] Add real C++ decoder regression: /preview/ IN=None disconnects PCM without mutating accepted stereo width --- tests/native_dry_route_command_test.cpp | 28 +++++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp index 4b8d3239f..b9f6f14b2 100644 --- a/tests/native_dry_route_command_test.cpp +++ b/tests/native_dry_route_command_test.cpp @@ -1,6 +1,7 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/NativeDryRouteCommand.h" #include "../engine/core/PreparedMixerBlock.h" +#include "../src/NativeVerifiedSourcePatch.h" #if defined(NDEBUG) #undef NDEBUG #endif @@ -123,6 +124,33 @@ int main(){ } NativeDryRouteCommand v2; assert(NativeDryRouteCommand::decode(typed,v2,error)); + // /preview/ IN=None disconnects real hardware without changing + // channel processing width or other accepted channels. + typed.getDynamicObject()->setProperty("deviceEpoch",juce::int64(91)); + typed.getDynamicObject()->setProperty("revision",juce::int64(7)); + juce::var sourceCleared, rejectedClear; + const auto activePins=std::span(ports.data(),ports.size()); + assert(NativeVerifiedSourcePatch::prepare( + typed,0,"NONE",-1,-1,activePins,91,7,sourceCleared).isEmpty()); + const auto cleared=sourceCleared.getProperty("channels",{}) + .getArray()->getReference(0); + assert(cleared.getProperty("mode",{}).toString()=="NONE"); + assert(cleared.getProperty("sourceKind",{}).toString()=="NONE"); + assert(cleared.getProperty("sourceFormat",{}).toString()=="NONE"); + assert(cleared.getProperty("channelFormat",{}).toString()=="STEREO"); + assert(static_cast(cleared.getProperty("left",-2))==-1); + assert(static_cast(cleared.getProperty("right",-2))==-1); + assert(typed.getProperty("channels",{}).getArray()->getReference(0) + .getProperty("sourceKind",{}).toString()=="PHYSICAL"); + NativeDryRouteCommand disconnectedPlan; + assert(NativeDryRouteCommand::decode(sourceCleared,disconnectedPlan,error)); + assert(disconnectedPlan.channels.stripsAndMaster.strips[0].source + ==SourceMode::disconnected); + assert(!NativeVerifiedSourcePatch::prepare( + typed,0,"NONE",2,-1,activePins,91,7,rejectedClear).isEmpty()); + assert(!NativeVerifiedSourcePatch::prepare( + typed,0,"NONE",-1,-1,activePins,90,7,rejectedClear).isEmpty()); + assert(v2.channels.stripsAndMaster.strips[0].source==SourceMode::mono); assert(v2.channels.formats[0]==ChannelFormat::stereo); assert(v2.channels.stripsAndMaster.strips[1].source==SourceMode::disconnected); From 9d43f73019812e8964c9d87fe28a9d323df5608d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:46:14 +0700 Subject: [PATCH 012/219] Preserve stable /preview/ 10-channel hardware identities across M4 to ChannelId and back Never regenerate view IDs on native admission if the established physical input strips are already present; preserve accepted OUT readback and fail closed on duplicate/missing hardware channel IDs. --- web/approved-native-bridge.js | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 9e259f897..4a813197c 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -63,11 +63,15 @@ !["faderDb","pan","mute","solo"].every(k => Object.hasOwn(ch.controls,k)))) return false; const previous = new Map(scope.tracks.concat(scope.master).map(t=>[t.id,t])); const nextTracks = [], localByNative = new Map(), nextNativeByUi = new Map(); - let nextMaster = null; + let nextMaster = null, inputOrdinal=0; for (const [index,ch] of accepted.channels.entries()) { const kind = ch.role==="MAIN"?"master":ch.role==="GROUP"?"bus": ch.role==="FX_RETURN"?"fx":"audio"; - const savedId = uiByNativeId.get(ch.id); + // Preserve approved CH01..CH10 DOM/model identities across M4 G0 + // -> native ChannelId admission -> any later G0 fallback. A new + // temporary track ID would silently move hardware to another strip. + const m4Id=ch.role==="INPUT"?m4TrackIds[inputOrdinal++]:undefined; + const savedId = uiByNativeId.get(ch.id) ?? m4Id; const t = savedId !== undefined && previous.has(savedId) ? previous.get(savedId) : scope.make(ch.name,kind,scope.colors[index%scope.colors.length]||"#568ead"); if (savedId !== undefined) t.id = savedId; @@ -88,6 +92,9 @@ r=/^in:(\d+)$/.exec(src.portIdRight||""); t.input=l?inputLabelFor({mode:src.sourceFormat==="STEREO"?"STEREO":"MONO", left:Number(l[1]),right:r?Number(r[1]):-1}):"None"; + const out=accepted.channels.find(dest=>dest.id===ch.primaryOutId); + t.output=out?.role==="MAIN"?"Master": + (out?.name||"SOURCE ONLY (No Main)"); } t.selected=previous.get(t.id)?.selected || false; if (Array.isArray(ch.inserts)) { @@ -217,7 +224,9 @@ const m4Meters=new Map(); const m4Verified=()=>{ const m=legacy(),d=hardware?.device; - return !flags.acceptedGraphConnected && m?.active===true && + return m4TrackIds.length===10 && + new Set(m4TrackIds).size===10 && + !flags.acceptedGraphConnected && m?.active===true && m.routeAccepted===true && Array.isArray(m.channelControls) && m.channelControls.length===10 && m.channels?.length===10 && safeNativeCounter(d?.epoch)!==null && From 12b8d7173f1e22122060209b9cb57104b3072727 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:48:01 +0700 Subject: [PATCH 013/219] Update IN binding contract to assert stable native M4 identity across GUI reorder --- tests/approved_native_m2_contract.test.cjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f6e8ebf83..e9e31f9f4 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -124,7 +124,10 @@ test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, assert.match(bridge,/inputChoices\(t\)/); assert.match(bridge,/hardware\.device\.enabledInputs\.includes\(p\.port\)/); assert.match(bridge,/field==="input"/); - assert.match(bridge,/scope\?\.tracks\?\.findIndex/); + // Reordering /preview/ strips must NOT change the real hardware lane. + assert.match(bridge,/const channel=m4Index\\(t\\)/); + assert.match(bridge,/const m4TrackIds=Array\\.isArray\\(scope\\?\\.tracks\\)/); + assert.match(bridge,/const savedId = uiByNativeId\\.get\\(ch\\.id\\) \\?\\? m4Id/); assert.match(bridge,/action:"routingSourceSwitch"/); assert.match(bridge,/row\?\.left===p\.choice\.left/); assert.match(bridge,/expectedEpoch:p\.epoch,expectedRevision:Number\(next\.revision\)/); From 6950bd482a312d27131077d69e5233483d91f365 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 16:48:27 +0700 Subject: [PATCH 014/219] Use valid JavaScript regex escapes for stable hardware-lane contract assertions --- tests/approved_native_m2_contract.test.cjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index e9e31f9f4..91f71ff87 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -125,9 +125,9 @@ test("P0 DAW approved Windows GUI directly binds every IN to current JUCE ports, assert.match(bridge,/hardware\.device\.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\\)/); - assert.match(bridge,/const m4TrackIds=Array\\.isArray\\(scope\\?\\.tracks\\)/); - assert.match(bridge,/const savedId = uiByNativeId\\.get\\(ch\\.id\\) \\?\\? m4Id/); + assert.match(bridge,/const channel=m4Index\(t\)/); + assert.match(bridge,/const m4TrackIds=Array\.isArray\(scope\?\.tracks\)/); + assert.match(bridge,/const savedId = uiByNativeId\.get\(ch\.id\) \?\? m4Id/); assert.match(bridge,/action:"routingSourceSwitch"/); assert.match(bridge,/row\?\.left===p\.choice\.left/); assert.match(bridge,/expectedEpoch:p\.epoch,expectedRevision:Number\(next\.revision\)/); From 3c2d2519979ed170cff6552a13a6dd3854bd7d26 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 17:49:54 +0700 Subject: [PATCH 015/219] Test source clear correctly: reject dangling live SEND, accept NONE only when sends disconnected Preserve fail-closed native audio routing. The prior fixture wrongly expected decode to accept a disconnected CH1 while it still sends PRE/POST PCM into two BUS channels. --- tests/native_dry_route_command_test.cpp | 14 +++++++++++++- 1 file changed, 13 insertions(+), 1 deletion(-) diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp index b9f6f14b2..5ef6083cb 100644 --- a/tests/native_dry_route_command_test.cpp +++ b/tests/native_dry_route_command_test.cpp @@ -143,7 +143,19 @@ int main(){ assert(typed.getProperty("channels",{}).getArray()->getReference(0) .getProperty("sourceKind",{}).toString()=="PHYSICAL"); NativeDryRouteCommand disconnectedPlan; - assert(NativeDryRouteCommand::decode(sourceCleared,disconnectedPlan,error)); + // CH1 still owns two PRE/POST sends to BUS channels. Clearing its + // hardware source while those sends remain must be rejected, not + // silently create a dangling audio path. + assert(!NativeDryRouteCommand::decode(sourceCleared,disconnectedPlan,error)); + assert(error.containsIgnoreCase("Enable a sender")); + // After the operator explicitly disconnects those sends, the very + // same accepted NONE source must compile to physical silence. + auto disconnectedNoSends=juce::JSON::parse( + juce::JSON::toString(sourceCleared,false)); + disconnectedNoSends.getDynamicObject()->setProperty("sends", + juce::var(juce::Array{})); + assert(NativeDryRouteCommand::decode(disconnectedNoSends, + disconnectedPlan,error)); assert(disconnectedPlan.channels.stripsAndMaster.strips[0].source ==SourceMode::disconnected); assert(!NativeVerifiedSourcePatch::prepare( From ff3efb2c8d03ea5691821b8c889ab3afc72b97ad Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 18:34:56 +0700 Subject: [PATCH 016/219] P0 First Sound: preserve BUS lane readback without erasing verified physical inputs --- integration/ApprovedNativeRuntimeSnapshot.h | 12 ++++++++--- tests/approved_native_v8_projection_test.cpp | 21 ++++++++++++++++++++ web/approved-native-bridge.js | 9 ++++++++- 3 files changed, 38 insertions(+), 4 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 51b7b4990..817ec4df6 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -98,18 +98,24 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, const auto left=item.getProperty("left",juce::var()); const auto right=item.getProperty("right",juce::var()); const auto main=item.getProperty("main",{}); - if((mode!="NONE" && mode!="MONO" && mode!="STEREO") || + // BUS is a real accepted, internally-fed M4 lane. Discarding + // all 10 readbacks because ONE lane is BUS would hide live + // physical microphone inputs on otherwise verified channels. + // Preserve BUS identity without claiming a hardware pin. + if((mode!="NONE" && mode!="MONO" && + mode!="STEREO" && mode!="BUS") || !(left.isInt()||left.isInt64()) || !(right.isInt()||right.isInt64()) || !main.isBool()) { valid=false;break; } const int l=static_cast(left),r=static_cast(right); - if((mode=="NONE"&&(l!=-1||r!=-1)) || + if(((mode=="NONE"||mode=="BUS")&&(l!=-1||r!=-1)) || (mode=="MONO"&&(r!=-1||l<0)) || (mode=="STEREO"&&(l<0||r<0||l==r))) { valid=false;break; } - if(mode!="NONE"&&(!inputs.getArray()->contains(l)|| + if((mode=="MONO"||mode=="STEREO")&& + (!inputs.getArray()->contains(l)|| (mode=="STEREO"&&!inputs.getArray()->contains(r)))) { valid=false;break; } diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index e20952262..28281eae5 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -390,6 +390,27 @@ static void firstSoundRouteAdmissionRegression() { assert(physicalRows.getArray()->size()==10); assert(physicalRows.getArray()->getReference(4).getProperty("mode",{}).toString()=="MONO"); assert(static_cast(physicalRows.getArray()->getReference(4).getProperty("left",-1))==0); + // One internal BUS must NOT invalidate the ten-lane native projection + // or erase physical CH05 input/controls, which are still accepted PCM. + auto withBus=juce::JSON::parse(juce::JSON::toString(live,false)); + withBus.getProperty("dryRoutingLab",{}) + .getProperty("acceptedRoute",{}).getProperty("channels",{}) + .getArray()->getReference(2).getDynamicObject()->setProperty("mode","BUS"); + assert(publishVerifiedFirstSoundState(snapshot,withBus)); + auto busReadback=snapshot.getProperty("legacyM4",{}).getProperty("channels",{}); + assert(busReadback.isArray()&&busReadback.getArray()->size()==10); + assert(busReadback[2].getProperty("mode","").toString()=="BUS"); + assert(static_cast(busReadback[2].getProperty("left",0))==-1); + assert(busReadback[4].getProperty("mode","").toString()=="MONO"); + assert(static_cast(busReadback[4].getProperty("left",-1))==0); + auto invalidBus=juce::JSON::parse(juce::JSON::toString(withBus,false)); + invalidBus.getProperty("dryRoutingLab",{}) + .getProperty("acceptedRoute",{}).getProperty("channels",{}) + .getArray()->getReference(2).getDynamicObject()->setProperty("left",7); + assert(publishVerifiedFirstSoundState(snapshot,invalidBus)); + assert(snapshot.getProperty("legacyM4",{}) + .getProperty("channels",{}).getArray()->isEmpty()); + assert(publishVerifiedFirstSoundState(snapshot,live)); // Disabled hardware input is never presented as accepted physical PCM. auto badPins=juce::JSON::parse(juce::JSON::toString(live,false)); badPins.getProperty("dryRoutingLab",{}).getProperty("acceptedRoute",{}) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 4a813197c..7a7764497 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -194,6 +194,8 @@ 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)):[]; + // BUS is verified engine state, not an available hardware input choice. + const INTERNAL_BUS="Internal BUS (read-only)"; const monoLabel=p=>"Mono · "+p.label+" [IN "+(p.port+1)+"]"; const stereoLabel=(a,b)=>"Stereo · IN "+(a.port+1)+" + "+(b.port+1); const inputChoicesFor=()=>{ @@ -209,6 +211,7 @@ }; const inputLabelFor=row=>{ 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); @@ -895,7 +898,11 @@ enabled:connected, inputChoices(t) { if(t?.kind!=="audio")return ["None"]; - return inputChoicesFor().map(x=>x.label); + const choices=inputChoicesFor().map(x=>x.label); + // The native BUS lane is selectable only for display: never invent a + // hardware pin or promote the internal BUS to a writable physical IN. + if(t.input===INTERNAL_BUS)choices.push(INTERNAL_BUS); + return choices; }, outputChoices(t) { if(t?.kind==="master") From c1a5071bbb8f30ac825dff900bdf557466e2b825 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 18:49:43 +0700 Subject: [PATCH 017/219] P0: guard live structural source/OUT updates and preserve native PCM on rejected publish --- src/LiveAudioEngine.h | 79 +++++++++++++++++-------- src/LiveDryRoutingLab.h | 28 ++++++++- src/NativeTopologyEditSafety.h | 22 +++++++ tests/native_dry_route_command_test.cpp | 17 ++++++ 4 files changed, 118 insertions(+), 28 deletions(-) create mode 100644 src/NativeTopologyEditSafety.h diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a864556e1..715da4c10 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -7,6 +7,7 @@ #include "VstBusLayout.h" #include "LiveGraphHandoff.h" #include "LiveDryRoutingLab.h" +#include "NativeTopologyEditSafety.h" #include "../engine/dsp/NativeMasterLoudness.h" #include "DiagnosticTone.h" #include "../engine/device/JuceIndependentClockDevice.h" @@ -1116,6 +1117,39 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback setOutputMuted(true); // never expose CH1 unexpectedly on STOP dryRoutingLab_.disable(); } + // Structural source/OUT changes recompile ONE existing native PCM + // publisher. Suspend physical monitoring internally (never ask the user + // to click MUTE/ARM), perform the edit, then re-admit the ChannelId graph + // while disarmed. If admission rejects, the accepted M4 renderer remains + // the only safe fallback in this SAME JUCE callback. + // All control-thread only. A running STREAM forbids structural edits; + // it must never consume a half-switched main graph. + template + juce::String applyGuardedDryTopology(std::uint64_t expectedEpoch, + int frames,Edit&& edit) { + if(secondaryOutput_.armed()) + return "STOP STREAM before a structural INPUT/OUT change"; + const bool wasMonitoring=isMonitorEnabled(); + if(wasMonitoring)setOutputMuted(true); + juce::String error; + try { error=edit(); } + catch(const std::exception& ex) { + error="NATIVE TOPOLOGY: preparation failed: "+juce::String(ex.what()); + } + catch(...) { error="NATIVE TOPOLOGY: preparation failed"; } + // This is a physical renderer admission, not an extra browser mixer, + // new DSP graph or auto-arm. It must complete before output resumes. + if(error.isEmpty() && expectedEpoch==dryRoutingLab_.epoch() && + dryRoutingLab_.hasExplicitRoute()) + (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( + graphOwned_->count,frames,true,currentOriginalCh1Lease()); + // A failed edit may restore the PREVIOUS valid audible route; device + // or graph faults, an unpatched last source, or STREAM never auto-arm. + if(wasMonitoring && expectedEpoch==dryRoutingLab_.epoch() && + !secondaryOutput_.armed() && liveOutputArmFault().isEmpty()) + setMonitorEnabled(true); + return error; + } juce::String switchDryRoutingLabSource(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& mode, int left,int right) { @@ -1127,24 +1161,22 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "SOURCE SWITCH: live DIRECT device or graph unavailable"; auto* device=deviceManager_.getCurrentAudioDevice(); if(!device)return "SOURCE: active DIRECT audio device unavailable"; - // True first-input SOURCE selection is a control-prepared native graph - // transaction, not a browser-side APPLY or alternate callback. A - // single verified mono capture pin is a supported source. try { const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - const auto oldRevision=dryRoutingLab_.revision(); - const auto changed=dryRoutingLab_.repatchPhysicalSource( - strip,epoch,revision,mode,left,right, - directFence_.permitted(),independent_.active(), - graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); - // Same-format SOURCE is an atomic live parameter on BOTH kernels: - // do not rebuild VST3/PCM or interrupt the 64-sample crossfade. - if(changed.isEmpty() && allOutputsDisarmed() && - oldRevision!=dryRoutingLab_.revision()) - (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( - graphOwned_->count,frames,true, - currentOriginalCh1Lease()); - return changed; + const bool structural=dryRoutingLab_.sourceNeedsPreparedGraph(strip,mode); + if(!armix::mixer::NativeTopologyEditSafety::mayEdit( + structural,secondaryOutput_.armed())) + return "SOURCE: STOP STREAM before changing source format"; + const auto edit=[&]{ + return dryRoutingLab_.repatchPhysicalSource( + strip,epoch,revision,mode,left,right, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + }; + // Existing same-format physical pin changes remain live, atomic + // and 64-sample crossfaded; no unnecessary mute or recompile. + if(!structural)return edit(); + return applyGuardedDryTopology(epoch,frames,edit); } catch(const std::exception& ex) { return "SOURCE: native prepare failed; prior audio kept: " + juce::String(ex.what()); } catch(...) { @@ -1168,15 +1200,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!device)return "CHANNEL PATCH: no active native audio interface"; try { const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - const auto changed=dryRoutingLab_.repatchChannelStructure( - strip,epoch,revision,operation,value, - directFence_.permitted(),independent_.active(), - graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); - if(changed.isEmpty() && allOutputsDisarmed()) - (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( - graphOwned_->count,frames,true, - currentOriginalCh1Lease()); - return changed; + return applyGuardedDryTopology(epoch,frames,[&] { + return dryRoutingLab_.repatchChannelStructure( + strip,epoch,revision,operation,value, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + }); } catch(...) { return "CHANNEL PATCH: native preparation failed; previous mix preserved"; } diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 82f5ea88b..a686d4201 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -8,6 +8,7 @@ #include "VstBusLayout.h" #include "../engine/core/NativeDryRouteCommand.h" #include "NativeVerifiedSourcePatch.h" +#include "NativeTopologyEditSafety.h" #include "../engine/device/JuceActivePortSnapshot.h" #include "../engine/core/RealtimeRoutePublisher.h" #include "../engine/core/RealtimeRenderPermit.h" @@ -420,8 +421,16 @@ class LiveDryRoutingLab final { return "Audio device changed before routing publication"; // New M4 routing must not render against an older ChannelId graph. // Output must remain disarmed throughout structural native APPLY. - channelIdPcmEpoch_.store(0,std::memory_order_release); + const auto previousPcmEpoch=channelIdPcmEpoch_.exchange( + 0,std::memory_order_acq_rel); const auto result=publisher_.publish(std::move(next),expectedRevision,epochAtPublish); + // A rejected publication did NOT replace the callback graph. Keep + // the previous admitted native PCM authority rather than silently + // falling back to potentially stale M4 controls on this device. + if(result!=Publisher::Result::applied && + previousPcmEpoch==epochAtPublish && + deviceEpoch_.load(std::memory_order_acquire)==epochAtPublish) + channelIdPcmEpoch_.store(previousPcmEpoch,std::memory_order_release); switch(result) { case Publisher::Result::applied: publishedEpoch_.store(currentEpoch,std::memory_order_release); @@ -511,8 +520,10 @@ class LiveDryRoutingLab final { if(!nativePublisher_.setPhysicalSource( expectedEpoch,nativeAccepted_.pcmRevision,id, callbackLeft,mode=="STEREO"?callbackRight:-1, - mode=="STEREO"))rejectedNativeMirror(); - else { + mode=="STEREO")) { + rejectedNativeMirror(); + return "SOURCE SWITCH: native PCM rejected mirror; refresh/recover routing"; + } else { // Physical SOURCE changes are LIVE atomic controls. Persist // the actual callback ordinals for the NEXT Group/FX Return // structural compile rather than reusing stale APPLY pins. @@ -532,6 +543,17 @@ class LiveDryRoutingLab final { return {}; } + // CONTROL-only classification for the operator's direct IN dropdown. + // Fail conservatively to the guarded path for an absent/invalid template. + bool sourceNeedsPreparedGraph(int strip,const juce::String& mode) const { + if(!sourceTemplate_.isObject() || !hasExplicitRoute())return true; + const auto channels=sourceTemplate_.getProperty("channels",juce::var()); + const auto* rows=channels.getArray(); + if(!rows||rows->size()!=count||strip<0||strip>=count)return true; + return armix::mixer::NativeTopologyEditSafety::structuralSource( + true,rows->getReference(strip).getProperty("mode",{}).toString()==mode); + } + // A source changing from NONE to MONO/STEREO needs a new prepared // topology. A source changing physical pin within the same format uses // the existing zero-heap atomic source switch above. Both cases are diff --git a/src/NativeTopologyEditSafety.h b/src/NativeTopologyEditSafety.h new file mode 100644 index 000000000..8c046033b --- /dev/null +++ b/src/NativeTopologyEditSafety.h @@ -0,0 +1,22 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +// P0 First Sound: CONTROL-thread source/OUT transaction policy. +// No realtime callback, locks, dynamic allocation or new DSP ownership. +namespace armix::mixer { +struct NativeTopologyEditSafety final { + static constexpr bool structuralSource(bool hasAcceptedRoute, + bool sameFormat) noexcept { + return !hasAcceptedRoute || !sameFormat; + } + static constexpr bool mayEdit(bool structural, bool streamArmed) noexcept { + // An atomic physical pin switch does not replace a PCM graph. + return !structural || !streamArmed; + } + static constexpr bool mayRestoreMonitor(bool previouslyArmed, + bool sameDeviceEpoch, + bool outputArmSafe, + bool streamArmed) noexcept { + return previouslyArmed && sameDeviceEpoch && outputArmSafe && !streamArmed; + } +}; +} // namespace armix::mixer diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp index 5ef6083cb..9bc58bd6b 100644 --- a/tests/native_dry_route_command_test.cpp +++ b/tests/native_dry_route_command_test.cpp @@ -2,6 +2,7 @@ #include "../engine/core/NativeDryRouteCommand.h" #include "../engine/core/PreparedMixerBlock.h" #include "../src/NativeVerifiedSourcePatch.h" +#include "../src/NativeTopologyEditSafety.h" #if defined(NDEBUG) #undef NDEBUG #endif @@ -11,6 +12,22 @@ using namespace armix::mixer; static bool near(float a,float b){return std::abs(a-b)<0.00001f;} int main(){ + // P0 First Sound: live same-format pin moves must remain atomic even + // during MAIN/STREAM, but a structural change cannot publish while + // STREAM is consuming the old graph. Physical re-arm is never implicit + // after a device epoch change or unsafe / unpatched output. + using Guard=NativeTopologyEditSafety; + static_assert(!Guard::structuralSource(true,true)); + static_assert( Guard::structuralSource(true,false)); + static_assert( Guard::structuralSource(false,true)); + assert(Guard::mayEdit(false,true)); + assert(Guard::mayEdit(true,false)); + assert(!Guard::mayEdit(true,true)); + assert(Guard::mayRestoreMonitor(true,true,true,false)); + assert(!Guard::mayRestoreMonitor(true,false,true,false)); + assert(!Guard::mayRestoreMonitor(true,true,false,false)); + assert(!Guard::mayRestoreMonitor(true,true,true,true)); + assert(!Guard::mayRestoreMonitor(false,true,true,false)); juce::String json=R"({"channels":[)"; for(int i=0;i Date: Thu, 5 Nov 2026 18:56:04 +0700 Subject: [PATCH 018/219] P0: reconcile accepted native fader/mute state into structural M4 fallback --- src/LiveAudioEngine.h | 7 +++-- src/LiveDryRoutingLab.h | 37 ++++++++++++++++++++++--- src/NativeTopologyEditSafety.h | 11 ++++++++ tests/native_dry_route_command_test.cpp | 10 +++++++ 4 files changed, 59 insertions(+), 6 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 715da4c10..303c4a821 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1145,8 +1145,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback graphOwned_->count,frames,true,currentOriginalCh1Lease()); // A failed edit may restore the PREVIOUS valid audible route; device // or graph faults, an unpatched last source, or STREAM never auto-arm. - if(wasMonitoring && expectedEpoch==dryRoutingLab_.epoch() && - !secondaryOutput_.armed() && liveOutputArmFault().isEmpty()) + const bool sameEpoch=expectedEpoch==dryRoutingLab_.epoch(); + if(wasMonitoring && sameEpoch && + armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + wasMonitoring,sameEpoch,liveOutputArmFault().isEmpty(), + secondaryOutput_.armed())) setMonitorEnabled(true); return error; } diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index a686d4201..52ac679bd 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -452,6 +452,12 @@ class LiveDryRoutingLab final { // enter ANY channel/master vendor DSP or produce sound. userPatched_.store(explicitSelection,std::memory_order_release); channelEdits_=proposed; // control thread SSOT for this route revision + // The freshly accepted M4 graph now owns these exact controls. + // Dirty native-only gestures have been captured into the new + // graph or superseded by a deliberate explicit APPLY. + // Otherwise re-admission would reject forever after one fader + // gesture and disable all fallback live controls. + nativeControlDirty_=false; for(int i=0;isize()!=count) return "CHANNEL PATCH: malformed native topology"; + // ChannelId gestures are authoritative once admitted. M4's saved + // channelEdits_ may be older; copy ACTUAL accepted roster controls + // into the recompiled M4 fallback so a SOURCE/OUT edit never changes + // a singer's last fader, pan, mute or solo setting. + const bool nativeControls=channelIdPhysicalPcmActive(); + if(nativeControls && (nativeStructureLive_ || + nativeAccepted_.deviceEpoch!=expectedEpoch)) + return "CHANNEL PATCH: incompatible native roster"; for(int i=0;igetReference(i).getDynamicObject(); if(!row)return "CHANNEL PATCH: missing native channel"; const auto& c=channelEdits_[i]; - row->setProperty("gain",static_cast(c.linear)); - row->setProperty("pan",static_cast(c.pan)); - row->setProperty("mute",c.mute); - row->setProperty("solo",c.solo); + const auto* accepted=nativeControls + ?nativeAccepted_.graph.roster.find(nativeAccepted_.graph.ids.inputs[i]) + :nullptr; + if(nativeControls && (!accepted || + accepted->role!=armix::mixer::ChannelRole::input)) + return "CHANNEL PATCH: admitted input roster is stale"; + const armix::mixer::NativeTopologyEditSafety::MixSnapshot legacy{ + c.linear,c.pan,c.mute,c.solo}; + const armix::mixer::NativeTopologyEditSafety::MixSnapshot native{ + accepted?accepted->faderLinear:c.linear, + accepted?accepted->pan:c.pan, + accepted?accepted->mute:c.mute, + accepted?accepted->solo:c.solo}; + const auto preserved=armix::mixer::NativeTopologyEditSafety::preserveAcceptedMix( + legacy,native,nativeControls); + row->setProperty("gain",static_cast(preserved.linear)); + row->setProperty("pan",static_cast(preserved.pan)); + row->setProperty("mute",preserved.mute); + row->setProperty("solo",preserved.solo); } if(expectedEpoch!=epoch()||expectedRevision!=revision()|| !registryValid_.load(std::memory_order_acquire)) diff --git a/src/NativeTopologyEditSafety.h b/src/NativeTopologyEditSafety.h index 8c046033b..3e0acfaee 100644 --- a/src/NativeTopologyEditSafety.h +++ b/src/NativeTopologyEditSafety.h @@ -4,6 +4,17 @@ // No realtime callback, locks, dynamic allocation or new DSP ownership. namespace armix::mixer { struct NativeTopologyEditSafety final { + struct MixSnapshot final { + float linear=1.f, pan=0.f; + bool mute=false, solo=false; + }; + // Before replacing an admitted ChannelId graph, copy its ACTUAL live + // fader/pan/mute/solo into the next M4 topology. A native gesture must + // never silently revert to an earlier fallback mixer value. + static constexpr MixSnapshot preserveAcceptedMix( + MixSnapshot legacy,MixSnapshot native,bool channelIdOwnsPcm) noexcept { + return channelIdOwnsPcm?native:legacy; + } static constexpr bool structuralSource(bool hasAcceptedRoute, bool sameFormat) noexcept { return !hasAcceptedRoute || !sameFormat; diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp index 9bc58bd6b..dbc1852d5 100644 --- a/tests/native_dry_route_command_test.cpp +++ b/tests/native_dry_route_command_test.cpp @@ -28,6 +28,16 @@ int main(){ assert(!Guard::mayRestoreMonitor(true,true,false,false)); assert(!Guard::mayRestoreMonitor(true,true,true,true)); assert(!Guard::mayRestoreMonitor(false,true,true,false)); + constexpr Guard::MixSnapshot oldM4{0.25f,-0.25f,false,false}; + constexpr Guard::MixSnapshot acceptedNative{0.75f,0.5f,true,true}; + constexpr auto migrated=Guard::preserveAcceptedMix( + oldM4,acceptedNative,true); + static_assert(migrated.linear==0.75f && migrated.pan==0.5f && + migrated.mute && migrated.solo); + constexpr auto legacyOnly=Guard::preserveAcceptedMix( + oldM4,acceptedNative,false); + static_assert(legacyOnly.linear==0.25f && legacyOnly.pan==-0.25f && + !legacyOnly.mute && !legacyOnly.solo); juce::String json=R"({"channels":[)"; for(int i=0;i Date: Thu, 5 Nov 2026 19:45:56 +0700 Subject: [PATCH 019/219] P0: unify live 10-channel PCM control and restore native per-channel VST3 insertion Expose verified PCM faders on original ten channels while ChannelId owns the same JUCE callback; reject dynamic BUS structural conflicts. Add catalog-keyed native insert transaction to existing M4 prepared graph with safe mute, rollback and true fxInstances readback. No DSP processor in JS, no alternate audio engine or callback. --- integration/ApprovedNativeRuntimeSnapshot.h | 11 ++++- src/LiveAudioEngine.h | 28 ++++++++++++ src/LiveDryRoutingLab.h | 32 +++++++++++++ src/Main.cpp | 50 ++++++++++++++++++++- 4 files changed, 119 insertions(+), 2 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 817ec4df6..18878f2d9 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -135,7 +135,7 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, // Publish only verified PCM controls and measured per-channel peaks. // Never infer controls from the Pages reference model. if(physicalReady && boolIs(route,"hasAcceptedRoute",true) && - !boolIs(route,"nativeChannelIdPcmActive",true) && + !boolIs(route,"nativeBusStructural",true) && verifiedChannels.size()==10) { const auto controls=route.getProperty("channelControls",{}); const auto levelsL=route.getProperty("channelPeaksL",{}); @@ -171,6 +171,15 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, if(masterMute.isBool())firstSound->setProperty("masterMute",masterMute); } } + // Real routed FX instance IDs and catalog keys are read only from the + // installed publisher. A browser cannot insert forged plugin identities. + if(physicalReady && boolIs(route,"hasAcceptedRoute",true)) { + const auto fx=route.getProperty("fxInstances",{}); + if(auto* rows=fx.getArray();rows && rows->size()==14) + firstSound->setProperty("fxInstances",fx); + } + firstSound->setProperty("nativeBusStructural", + route.getProperty("nativeBusStructural",false)); // Do not write the route to the graph or change native capability flags. snapshot.getDynamicObject()->setProperty("legacyM4",juce::var(firstSound.release())); return physicalReady; diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 303c4a821..92f37dfed 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1213,6 +1213,34 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "CHANNEL PATCH: native preparation failed; previous mix preserved"; } } + + // Existing single-callback native FX rack. Internally mute for a + // structural vendor prepare, then restore monitoring only on verified + // same-device/safe routing. The operator never needs an Arm/Patch wizard. + juce::String insertDryRoutingLabFx(int lane,int slot, + std::uint64_t epoch,std::uint64_t revision, + const LiveDryRoutingLab::FxSelection& chosen) { + if(independent_.active()||handoff_.busy()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + !directFence_.permitted()||savedDirectSetup_||savedLiveSetup_|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal) + return "FX INSERT: native direct graph or device unavailable"; + if(secondaryOutput_.armed()) + return "FX INSERT: stop the secondary stream before changing VST topology"; + for(int i=0;icount;++i) + if(graphOwned_->slots[i].latency!=0) + return "FX INSERT: CH1 latent VST3 needs PDC before routed inserts"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device)return "FX INSERT: select an actual audio device"; + const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + return applyGuardedDryTopology(epoch,frames,[&] { + return dryRoutingLab_.insertCatalogFx(lane,slot,epoch,revision, + chosen,directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(), + frames); + }); + } bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, float value) noexcept { diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 52ac679bd..1a6a3ef02 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -479,6 +479,38 @@ class LiveDryRoutingLab final { } } + + // Native /preview/ FX picker: append one catalog-verified stereo VST3 to + // the SAME accepted ten-channel/4AUX renderer. This is a prepared graph + // transaction on JUCE CONTROL, never a JS plugin or RT instantiation. + juce::String insertCatalogFx(int lane,int slot, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + const FxSelection& chosen,bool directPermitted, + bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + if(lane<0||lane>=fxSlots||slot<0||slot>=maxFxPerLane|| + chosen.id.isEmpty()||chosen.path.isEmpty()||chosen.name.isEmpty()|| + !ready()||!hasExplicitRoute()||nativeStructureLive_|| + topologyFault_.load(std::memory_order_acquire)|| + !registryValid_.load(std::memory_order_acquire)|| + expectedEpoch!=epoch()||expectedRevision!=revision()|| + !sourceTemplate_.isObject()) + return "FX INSERT: stale routing/ChannelId authority or unsupported lane"; + if(acceptedFxSelections_[lane][slot].id.isNotEmpty()) + return "FX INSERT: this slot already has a native VST3"; + if(slot>0&&acceptedFxSelections_[lane][slot-1].id.isEmpty()) + return "FX INSERT: use the first empty insert position"; + auto command=juce::JSON::parse( + juce::JSON::toString(sourceTemplate_,false)); + if(!command.isObject()) + return "FX INSERT: accepted source template cannot be cloned"; + auto next=acceptedFxSelections_; + next[lane][slot]=chosen; + return apply(command,directPermitted,independentClock,occupiedCh1Fx, + next,formats,sampleRate,deviceFrames,true); + } + // M1 direct-source parameter: only same-format physical→physical // input on an ALREADY scheduled channel. Route DAG, VST3 lease, FX // identity and hardware output ownership are immutable. Epoch/revision diff --git a/src/Main.cpp b/src/Main.cpp index 364209e43..4ebf7adb6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1457,6 +1457,54 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // F0: independently acknowledged existing M4 PCM controls during // G0, before ChannelId admission. Do not send GUI demo parameters // or mutate a second DSP. One control-thread atomic update only. + + // Route the approved channel FX picker to the SAME prepared M4 + // graph as physical IN/OUT. ID resolves exclusively in the JUCE + // catalog; browser paths/names are never trusted as plugin identity. + if(action=="routingFxInsert"){ + const auto requestId=args.getProperty("requestId",{}).toString(); + const int lane=static_cast(args.getProperty("channel",-1)); + const int position=static_cast(args.getProperty("slot",-1)); + const auto id=args.getProperty("id",{}).toString(); + const auto ep=args.getProperty("deviceEpoch",{}); + const auto rv=args.getProperty("revision",{}); + const auto status=engine_.status().getProperty("dryRoutingLab",{}); + const auto actualEp=status.getProperty("epoch",{}); + const auto actualRev=status.getProperty("revision",{}); + const auto* plugin=catalog_.find(id); + juce::String error="FX INSERT: invalid/stale device, channel, slot or catalog"; + const bool tokens=(ep.isInt()||ep.isInt64())&& + (rv.isInt()||rv.isInt64())&& + static_cast(ep)>0 && + static_cast(ep)==static_cast(actualEp)&& + static_cast(rv)==static_cast(actualRev); + if(requestId.startsWith("fx-")&&requestId.length()<=48 && + tokens && lane>=0&&lane=0&&position(status.getProperty("hasAcceptedRoute",false))) { + const LiveDryRoutingLab::FxSelection selection{ + plugin->key(),plugin->path,plugin->name,plugin->uid}; + error=engine_.insertDryRoutingLabFx(lane,position, + static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + selection); + } + auto reply=std::make_unique(); + reply->setProperty("requestId",requestId); + reply->setProperty("ok",error.isEmpty()); + reply->setProperty("error",error); + reply->setProperty("channel",lane); + reply->setProperty("slot",position); + reply->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixRoutingFxInsertAck",juce::var(reply.release())); + if(error.isNotEmpty())emitNotice(error,true); + else diagnostics_.record("NATIVE_ROUTED_FX_INSERT", + "CH "+juce::String(lane+1)+" slot "+juce::String(position+1)); + return; + } if(action=="routingM4Control"){ const auto requestId=args.getProperty("requestId",juce::var()).toString(); const int channel=static_cast(args.getProperty("channel",-1)); @@ -1477,7 +1525,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr requestId.length()<=48 && !nativeShowBusy_ && !studioBackupBusy_ && static_cast(route.getProperty("hasAcceptedRoute",false)) && - !static_cast(route.getProperty("nativeChannelIdPcmActive",false)) && + !static_cast(route.getProperty("nativeBusStructural",false)) && !static_cast(route.getProperty("topologyFault",true)) && engine_.directRouteAuthorized() && !engine_.independentClockActive(); const bool boolean=(name=="mute"||name=="solo"||name=="masterMute"); From 0ad7d233939150d9ff895d288d832c4091ba3822 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 19:49:32 +0700 Subject: [PATCH 020/219] Bind native approved GUI to single live M4/ChannelId authority; preserve focus and picker Expose the approved /preview/ FX picker, direct fader visuals and native catalog through its existing lexical model. Stop whole-mixer redraw on native 12 Hz scalar readback, preserve active hardware selectors and pointer capture, throttle native realtime fader control events. Structural graph updates still replace the accepted projection only when identities/FX topology actually change. --- scripts/build_approved_native_gui.py | 15 +++ web/approved-native-bridge.js | 165 ++++++++++++++++++++++++--- 2 files changed, 163 insertions(+), 17 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 125292a5f..c018d8c1d 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -74,6 +74,12 @@ def accepted_pages_html() -> str: ("function handleField(event){\n", "function handleField(event){\n" " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.consumeField?.(event);return;}\n"), + # Native-only: the SAME original quick picker/manager owns the UI. + # Only insertion leaves the demo reducer and goes to JUCE's actual VST3 + # graph; never mark a browser insert as loaded. + ("function insertCatalogPlugin(id){\n", + "function insertCatalogPlugin(id){\n" + " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.insertPlugin?.(id,activeFxTarget);return;}\n"), (" if(a==='wireExpand'){document.querySelector('.section-rail", " if(window.__JUCE__?.backend&&!window.__ARMIX_NATIVE_M2__?.enabled)return;\n" " if(window.__ARMIX_NATIVE_M2__?.consumeAction?.(t,a,btn))return;\n" @@ -143,6 +149,15 @@ def accepted_pages_html() -> str: "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" " make,render,findTrack,displayMeterDbfs,\n" + " refreshStrip,syncFaderVisual,openFastPicker,openPluginBrowser,\n" + " get activeFaderId(){return faderGesture?Number(faderGesture.input.closest('.strip')?.dataset.id):-1;},\n" + " setNativeCatalog(rows){\n" + " pluginCatalog=rows.filter(x=>x&&typeof x.id==='string'&&typeof x.name==='string').map(x=>({\n" + " id:x.id,name:x.name,vendor:x.vendor||'Unknown',category:x.category||'Utility',\n" + " format:'VST3',status:'ready',latencySamples:null,\n" + " favorite:!!x.favorite,hidden:false}));\n" + " renderPluginCatalog();renderFastPicker();return pluginCatalog.length;\n" + " },\n" " colors:COLORS,wireGraph:ArSonWireGraph,\n" " allocateWireId(){return nextWireId++;},\n" " installGraph(channels,main,edges){\n" diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 7a7764497..31f1aeffd 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -16,7 +16,8 @@ const uiByNativeId = new Map(); // EXACT uint64 string -> local view-only ordinal const wireByUiId = new Map(); // view-only EdgeId -> EXACT decimal-string native EdgeId const uiByWireId = new Map(); - let lastPaintedSignature = "", lastNativeError = "NATIVE_NOT_SUBSCRIBED"; + let lastPaintedSignature = "",lastNativeTopologySignature = "", + lastNativeError = "NATIVE_NOT_SUBSCRIBED"; // B-stage: attached-node-only meter caches; a structural render invalidates // them atomically. Never retain detached WebView2 strips or stale channel IDs. const meterElements = new Map(); @@ -140,6 +141,43 @@ scope.installGraph(nextTracks,nextMaster,edges); return true; } + function projectNativeGraphWithoutFocusLoss(next) { + const structure=JSON.stringify([ + next.graph.channels.map(ch=>[ch.id,ch.role,ch.name, + ch.processingFormat,ch.source,ch.primaryOutId,ch.inserts]), + next.graph.edges]); + if(structure!==lastNativeTopologySignature){ + if(!projection(next))return false; + lastNativeTopologySignature=structure; + return true; + } + // Immutable graph topology is identical: update actual scalar controls + // only. Never detach the active HTML select or the captured fader pointer. + for(const ch of next.graph.channels){ + const id=uiByNativeId.get(ch.id); + const t=id===scope?.master?.id?scope.master: + scope?.tracks?.find(x=>x.id===id); + if(!t||!ch.controls)continue; + const c=ch.controls; + const db=c.faderDb,pan=c.pan*100; + const faderChanged=Number.isFinite(db)&&Math.abs(t.level-db)>.015; + const switchChanged=t.mute!==c.mute||t.solo!==c.solo; + if(faderChanged)t.level=db; + if(Number.isFinite(pan))t.pan=pan; + t.mute=c.mute;t.solo=c.solo; + if(switchChanged){ + scope.refreshStrip?.(t); + meterElements.delete(t.id); + }else if(faderChanged&&scope.activeFaderId!==t.id) + scope.syncFaderVisual?.(t); + const root=document.querySelector('.strip[data-id="'+t.id+'"]'); + const knob=root?.querySelector('.center-pan'); + if(knob&&scope.activeFaderId!==t.id&& + document.activeElement!==knob && Number.isFinite(pan)) + knob.value=String(pan); + } + return true; + } // Native telemetry owns the physical meter. When no measured per-channel // samples are published, leave the meter dark; never use Pages sine demo. function paintNativeMeters(next) { @@ -223,18 +261,81 @@ scope.tracks.filter(t=>t.kind==="audio").slice(0,10).map(t=>t.id):[]; const m4Index=t=>t?.kind==="audio"?m4TrackIds.indexOf(t.id):-1; let lastM4UiSignature="",lastM4Controls="",nativeUiSourcePending=null; - let pendingOutputPatch=null,m4RequestSerial=0,outputSerial=7000; + let lastM4PortSignature="",pendingOutputPatch=null,m4RequestSerial=0,outputSerial=7000; + const pendingSourceQueue=new Map(); + let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); + let pendingNativeControl=new Map(),lastNativeControlSent=new Map(); const m4Meters=new Map(); const m4Verified=()=>{ const m=legacy(),d=hardware?.device; return m4TrackIds.length===10 && new Set(m4TrackIds).size===10 && - !flags.acceptedGraphConnected && m?.active===true && - m.routeAccepted===true && Array.isArray(m.channelControls) && + m?.active===true && m.routeAccepted===true && + m.nativeBusStructural!==true && + Array.isArray(m.channelControls) && m.channelControls.length===10 && m.channels?.length===10 && safeNativeCounter(d?.epoch)!==null && safeNativeCounter(m.routingRevision)!==null; }; + + // One verified control path for original 10 channels and MAIN, whether + // the callback currently renders M4 or its admitted ChannelId mirror. + // Browser holds only transient gesture feedback; engine remains SSOT. + const controlKey=(parameter,t)=>parameter+":"+(t?.kind==="master"?"main":m4Index(t)); + function streamFaderControl(parameter,t,value,final){ + if(!m4Verified())return false; + const key=controlKey(parameter,t),now=performance.now(); + const last=lastNativeControlSent.get(key)||0; + if(!final&&now-last<30){ + pendingNativeControl.set(key,{parameter,t,value}); + return true; + } + pendingNativeControl.delete(key); + lastNativeControlSent.set(key,now); + return sendM4Control(parameter,t,value); + } + // A quiet trailing flush guarantees final PCM value, even if the pointer + // stops between two 30ms live-control ticks or a keyboard commits instantly. + let nativeControlFlushQueued=false; + function queueLiveControlFlush(){ + if(nativeControlFlushQueued)return; + nativeControlFlushQueued=true; + window.setTimeout(()=>{ + nativeControlFlushQueued=false; + for(const [key,edit] of pendingNativeControl) { + pendingNativeControl.delete(key); + lastNativeControlSent.set(key,performance.now()); + sendM4Control(edit.parameter,edit.t,edit.value); + } + },32); + } + function previewFaderWithoutModelMutation(t,db){ + if(!Number.isFinite(db)||!t)return; + scope?.syncFaderVisual?.({...t,level:db}); + } + function paintM4FxInstances(m) { + if(!Array.isArray(m?.fxInstances)||!scope?.tracks)return; + for(let lane=0;lane<10;lane++){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[lane]); + const rows=m.fxInstances[lane]; + if(!t||!Array.isArray(rows))continue; + let change=false; + for(let slot=0;slot<8;slot++){ + const live=rows[slot],entry=nativeCatalog.get(live?.catalogId); + const name=live?(entry?.name||"VST3 Loaded"):"None"; + if(t.fx[slot]!==name || t.slotBypass[slot]!==Boolean(live?.bypassed) || + (t.fxInsertIds?.[slot]?.id||null)!==(live?.instanceId||null)){ + t.fx[slot]=name; + t.slotBypass[slot]=Boolean(live?.bypassed); + if(!Array.isArray(t.fxInsertIds))t.fxInsertIds=Array(8).fill(null); + t.fxInsertIds[slot]=live?{id:live.instanceId,name}:null; + change=true; + } + } + if(change && scope.activeFaderId!==t.id) + scope.refreshStrip?.(t); + } + } function sendM4Control(parameter,t,value) { if(!m4Verified() || (typeof value!=="boolean"&&!Number.isFinite(value))) return false; @@ -260,29 +361,41 @@ function paintM4Fallback(next) { if(!m4Verified()||!Array.isArray(scope?.tracks))return; const m=next.raw.legacyM4,ctl=m.channelControls; + paintM4FxInstances(m); const controlSignature=JSON.stringify([next.device.epoch, m.routingRevision,ctl,m.masterDb,m.masterMute]); if(controlSignature!==lastM4Controls) { lastM4Controls=controlSignature; - let changed=false; for(let i=0;i<10;i++){ const t=scope.tracks.find(x=>x.id===m4TrackIds[i]),c=ctl[i]; if(!t||!c||!Number.isFinite(c.db)||!Number.isFinite(c.pan)|| typeof c.mute!=="boolean"||typeof c.solo!=="boolean")return; - if(Math.abs(t.level-c.db)>.015){t.level=c.db;changed=true;} - if(Math.abs(t.pan-c.pan)>.015){t.pan=c.pan;changed=true;} - if(t.mute!==c.mute){t.mute=c.mute;changed=true;} - if(t.solo!==c.solo){t.solo=c.solo;changed=true;} + const oldDb=t.level; + const switchChanged=t.mute!==c.mute||t.solo!==c.solo; + t.level=c.db;t.pan=c.pan;t.mute=c.mute;t.solo=c.solo; + if(switchChanged && scope.activeFaderId!==t.id){ + scope.refreshStrip?.(t); + m4Meters.delete(t.id); + }else if(Math.abs(oldDb-c.db)>.015 && + scope.activeFaderId!==t.id) + scope.syncFaderVisual?.(t); + const panKnob=document.querySelector( + '.strip[data-id="'+t.id+'"] .center-pan'); + if(panKnob && document.activeElement!==panKnob) + panKnob.value=String(c.pan); } if(scope.master && Number.isFinite(m.masterDb) && Math.abs(scope.master.level-m.masterDb)>.015){ - scope.master.level=m.masterDb;changed=true; + scope.master.level=m.masterDb; + if(scope.activeFaderId!==scope.master.id) + scope.syncFaderVisual?.(scope.master); } if(scope.master && typeof m.masterMute==="boolean" && scope.master.mute!==m.masterMute){ - scope.master.mute=m.masterMute;changed=true; + scope.master.mute=m.masterMute; + if(scope.activeFaderId!==scope.master.id) + scope.refreshStrip?.(scope.master); } - if(changed){m4Meters.clear();scope.render?.();} } // Only measured JUCE callback peaks are painted. Cache actual live DOM // fills to avoid repeated selector searches for every timer/signal tick. @@ -328,9 +441,27 @@ if(row && typeof row.main==="boolean") t.output=row.main?"Master":"SOURCE ONLY (No Main)"; } - // One canonical renderer, only on a real routing/topology change. - m4Meters.clear(); - scope.render?.(); + // A source ACK changes only affected fields; never replace the whole + // mixer while another select is open or another fader is being dragged. + const ports=JSON.stringify([next?.device?.epoch, + next?.device?.enabledInputs,next?.device?.inputEndpoints]); + if(ports!==lastM4PortSignature){ + lastM4PortSignature=ports; + if(scope.activeFaderId<0 && + !document.activeElement?.matches?.('.strip select')) + scope.render?.(); // refresh all hardware choices ONLY after device setup + }else{ + for(let i=0;i<10;++i){ + const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); + if(!t)continue; + const root=document.querySelector('.strip[data-id="'+t.id+'"]'); + for(const field of ["input","output"]){ + const element=root?.querySelector('select[data-field="'+field+'"]'); + if(element && document.activeElement!==element && + element.value!==t[field])element.value=t[field]; + } + } + } } const virtualCableFeedbackPair=()=>{ @@ -754,7 +885,7 @@ const nativeAdmitted=next.admitted && caps?.callbackOwnsChannelIds===true; if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; - lastPaintedSignature=""; + lastPaintedSignature="";lastNativeTopologySignature=""; stopDemo(); status(m4Verified()? "NATIVE M4 · real PCM faders and meters · ChannelId buses not yet admitted": @@ -770,7 +901,7 @@ paintNativeMeters(next); return; } - if (!projection(next)) { + if (!projectNativeGraphWithoutFocusLoss(next)) { flags.acceptedGraphConnected=false;flags.productionCallbackLive=false; stopDemo();status("NATIVE READBACK INVALID · existing GUI controls unchanged"); return; From 13c9944a9b8272c6403c95e64a76ab72df74034b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 19:51:46 +0700 Subject: [PATCH 021/219] P0: DAW live fader at 30 Hz, queued physical IN changes and functional native FX picker/catalog Every original-10/master physical control streams to one JUCE native parameter path while dragging, but final change flushes exact value. Queue independent channel source choices instead of rejecting every selector during a pending ACK. Close AUDIO I/O only after verified active device ACK and show compact toast. Wire approved Plugin Manager/F8/FX picker to real JUCE catalog, native scan/chooser and independently acknowledged routed FX insertion. --- web/approved-native-bridge.js | 220 ++++++++++++++++++++++++++-------- 1 file changed, 171 insertions(+), 49 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 31f1aeffd..4148da832 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -550,6 +550,23 @@ // replaces the 740x590 default JUCE dialog for normal operator setup. let devicePanel=null,deviceInventory=null,deviceBusy=false, deviceRequest=0,pendingDeviceMute=null,deviceChoice=null,deviceResult=""; + let toastTimer=0; + function nativeToast(message){ + let element=document.getElementById("armixNativeToast"); + if(!element){ + element=document.createElement("div"); + element.id="armixNativeToast"; + element.setAttribute("role","status"); + element.style.cssText="position:fixed;right:16px;bottom:36px;z-index:99999;"+ + "max-width:min(390px,88vw);padding:9px 13px;border:1px solid #426f7e;"+ + "border-radius:6px;background:#123240;color:#dff8fd;"+ + "font:12px system-ui,sans-serif;box-shadow:0 9px 28px #0008"; + document.body.appendChild(element); + } + element.textContent=message;element.hidden=false; + window.clearTimeout(toastTimer); + toastTimer=window.setTimeout(()=>{element.hidden=true;},3400); + } function openNativeAudioIO(){ if(!devicePanel){ const style=document.createElement("style"); @@ -770,11 +787,25 @@ if(!devicePanel||ack?.requestId!==devicePanel.dataset.pendingRequest)return; deviceBusy=false; if(ack.active)deviceInventory.active=ack.active; - deviceResult=ack.ok? - "Device verified · choose a hardware input on any mixer channel.": - "Device rejected · "+(ack.error||"driver readback failed"); + const accepted=ack.ok===true&&ack.state==="ACCEPTED_MUTED" && + ack.active?.open===true && ack.active?.authorized===true && + Array.isArray(ack.active.enabledInputs) && + ack.active.enabledInputs.length>0 && + Array.isArray(ack.active.enabledOutputs) && + ack.active.enabledOutputs.length>=2; + deviceResult=accepted? + "Audio device ready · choose an IN on any channel": + "Device rejected · "+(ack.error||"native hardware readback failed"); deviceChoice=null; - renderDevicePanel(); + if(accepted){ + devicePanel.hidden=true; + status("AUDIO ACTIVE · "+ack.active.backend+" · "+ + ack.active.rate+" Hz / "+ack.active.buffer+ + " samples · MONITOR muted until a real IN is selected"); + nativeToast("Audio device connected · "+ack.active.backend+ + " · "+ack.active.rate+" Hz · choose channel IN"); + controller?.subscribe(); + }else renderDevicePanel(); }); } @@ -878,9 +909,38 @@ updateHardwarePanel(hardware); } + // One control-thread routing transaction at a time, but NEVER lock other + // dropdowns or lose their choices. Latest choice wins per channel. + function dispatchQueuedSource(){ + if(nativeUiSourcePending||pendingSourceQueue.size===0)return; + if(!deviceReady()){pendingSourceQueue.clear();return;} + const [channel,choice]=pendingSourceQueue.entries().next().value; + pendingSourceQueue.delete(channel); + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(ep===null||rev===null)return; + const requestId=++sourceSerial; + nativeUiSourcePending={requestId,channel,choice,epoch:ep,revision:rev, + autoListen:legacy()?.routeAccepted!==true && + hardware?.device?.outputArmed!==true}; + backend.emitEvent("arMixAction",{action:"routingSourceSwitch", + requestId,channel,mode:choice.mode,left:choice.left,right:choice.right, + deviceEpoch:ep,revision:rev}); + window.setTimeout(()=>{ + if(nativeUiSourcePending?.requestId!==requestId)return; + nativeUiSourcePending=null; + status("CH "+(channel+1)+" INPUT timeout · native state preserved"); + controller.subscribe(); + },8000); + } function onNativeReadback(next) { updateHardwarePanel(next); paintM4Fallback(next); + // A second channel's IN can be selected while the first transaction is + // in flight. Always dispatch its latest choice with a FRESH native route + // revision, not stale tokens captured before the previous ACK. + if(!nativeUiSourcePending && pendingSourceQueue.size) + window.queueMicrotask(()=>dispatchQueuedSource()); const caps=next?.graph?.capabilities; const nativeAdmitted=next.admitted && caps?.callbackOwnsChannelIds===true; if (!nativeAdmitted) { @@ -924,8 +984,9 @@ lastNativeError=state.lastError; // Native REJECTED / STALE / timeout must roll back a temporary fader // cap and every input value; no optimistic GUI state survives. - if (!state.pending && flags.acceptedGraphConnected && scope?.render) { - scope.render(); + if (!state.pending && flags.acceptedGraphConnected && + scope.activeFaderId<0){ + controller.subscribe(); // restore from native, never redraw active selects if(state.current)paintNativeMeters(state.current); } } @@ -1004,6 +1065,36 @@ (ack?.error||"stale route")); controller.subscribe(); }); + backend.addEventListener("arMixRoutingFxInsertAck",ack=>{ + if(!pendingFxInsert||ack?.requestId!==pendingFxInsert.requestId)return; + const p=pendingFxInsert;pendingFxInsert=null; + const actual=ack?.state?.fxInstances?.[p.channel]?.[p.slot]; + if(ack?.ok===true && actual?.catalogId===p.id && + typeof actual?.instanceId==="string"&&actual.instanceId.length){ + status("CH "+(p.channel+1)+" FX loaded · verified native VST3"); + scope?.setNativeCatalog?.([...nativeCatalog.values()]); + controller.subscribe(); + }else { + status("FX INSERT REJECTED · "+(ack?.error||"native readback mismatch")); + controller.subscribe(); + } + }); + backend.addEventListener("arMixCatalog",catalog=>{ + if(!Array.isArray(catalog?.items))return; + nativeCatalog=new Map(catalog.items.filter(p=> + p&&typeof p.id==="string"&&p.id.length>0&& + typeof p.name==="string"&&p.name.length>0).map(p=>[p.id,p])); + scope?.setNativeCatalog?.([...nativeCatalog.values()]); + if(hardware?.raw?.legacyM4)paintM4FxInstances(hardware.raw.legacyM4); + const count=document.getElementById("pluginCount"); + if(count)count.title="Verified JUCE native VST3 catalog"; + }); + backend.addEventListener("arMixScanProgress",progress=>{ + const statusEl=document.getElementById("pluginScanStatus"); + if(statusEl)statusEl.textContent=progress?.active? + "Scanning real VST3… "+(progress.done||0)+"/"+(progress.total||"…"): + "Native VST3 scan finished; results from JUCE catalog"; + }); backend.addEventListener("arMixAudioArmAck", ack=>{ if(pendingDeviceMute){ // Reject any stale/unrelated ACK and any device epoch change. @@ -1062,32 +1153,21 @@ const choice=inputChoicesFor().find(x=>x.label===el.value); const ep=safeNativeCounter(hardware?.device?.epoch); const rev=safeNativeCounter(legacy()?.routingRevision); - if(channel<0||channel>=10||!choice||!deviceReady() || - ep===null||rev===null||pendingSourceId!==0 || - nativeUiSourcePending){ - status("NATIVE INPUT REJECTED · device/source changed or busy"); + if(channel<0||channel>=10||!choice||!deviceReady()|| + ep===null||rev===null){ + status("INPUT REJECTED · refresh verified hardware pins"); + el.value=t.input;return true; + } + if(choice.label===t.input&&!pendingSourceQueue.has(channel)){ el.value=t.input;return true; } - if(el.value===t.input)return true; - const first=legacy()?.routeAccepted!==true; - const requestId=++sourceSerial; - nativeUiSourcePending={requestId,channel,choice,epoch:ep, - revision:rev,autoListen:first&&!hardware.device.outputArmed}; - // Keep the visible IN at its last accepted value until native ACK - // and a fresh verified revision arrive. No optimistic demo routing. + pendingSourceQueue.set(channel,choice); + // No browser demo optimistic patch. The selector stays operable for + // every channel during a previous JUCE routing transaction. el.value=t.input; - backend.emitEvent("arMixAction",{action:"routingSourceSwitch", - requestId,channel,mode:choice.mode,left:choice.left,right:choice.right, - deviceEpoch:ep,revision:rev}); - // An absent ACK cannot freeze further source changes indefinitely. - // Timeout belongs to WebView control logic, not the realtime callback. - window.setTimeout(()=>{ - if(nativeUiSourcePending?.requestId!==requestId)return; - nativeUiSourcePending=null; - status("CH "+(channel+1)+" INPUT · response timed out; unchanged"); - controller.subscribe(); - },8000); - status("CH "+(channel+1)+" INPUT · verifying physical routing"); + if(nativeUiSourcePending) + status("CH "+(channel+1)+" input queued behind native route ACK"); + else dispatchQueuedSource(); return true; } if(field==="output"){ @@ -1118,27 +1198,28 @@ },8000); return true; } + // ONE realtime PCM control for original ten channels and MAIN, + // regardless of whether the admitted ChannelId callback or M4 renders. + // <=33 commands/s/control while dragging; always flush on release. + if((field==="level"||field==="pan") && m4Verified() && + (m4Index(t)>=0||t.kind==="master")){ + const numeric=Number(el.value); + if(!Number.isFinite(numeric))return true; + const normalized=field==="pan" && + !el.dataset.panKeyboard && !el.dataset.panAltPointer && + Math.abs(numeric)<=12 ? 0:numeric; + const key=field==="level"? + (t.kind==="master"?"masterGain":"faderDb"):"pan"; + if(field==="level")previewFaderWithoutModelMutation(t,numeric); + if(streamFaderControl(key,t,normalized,event.type==="change")) + queueLiveControlFlush(); + else status("LIVE PCM control rejected; checking route identity"); + return true; + } if (!flags.acceptedGraphConnected) { - if(m4Verified()){ - if(t.kind==="master" && field==="level"){ - if(event.type==="change" && Number.isFinite(Number(el.value))) - sendM4Control("masterGain",t,Number(el.value)); - return true; - } - if(m4Index(t)>=0 && (field==="level"||field==="pan")){ - if(event.type!=="change")return true; - const numeric=Number(el.value); - const value=field==="pan"&& - !el.dataset.panKeyboard&&!el.dataset.panAltPointer&& - Math.abs(numeric)<=12?0:numeric; - if(!sendM4Control(field==="level"?"faderDb":"pan",t,value)) - status("G0 native control rejected; restoring accepted readback"); - return true; - } - } if (field==="level")el.value=String(t.level); else if (field==="pan")el.value=String(t.pan); - status("NATIVE: ChannelId PCM not admitted; control unchanged"); + status("LIVE PCM control unavailable · selected route not admitted"); return true; } // During a native pointer drag move the approved fader *cap* only. @@ -1177,6 +1258,10 @@ // Selection, WIRE inspection and section presentation are UI-only. if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action)) return !["wireExpand","wireSource","wireRoute"].includes(action); + if(action==="openPlugin"){ + scope?.openFastPicker?.(t,Number(btn?.dataset.slot),btn); + return true; + } if (action==="mute"||action==="solo") { if(m4Verified() && t.kind==="master" && action==="mute"){ if(!sendM4Control("masterMute",t,!t.mute)) @@ -1238,6 +1323,34 @@ return true; }, consumeUndo() {if (!connected)return false;status("NATIVE: WIRE undo requires accepted native transaction");return true;}, + insertPlugin(id,target){ + if(pendingFxInsert){status("FX INSERT · wait for previous native ACK");return true;} + const plugin=nativeCatalog.get(id); + const track=scope?.tracks?.find(x=>x.id===target?.channelId); + const channel=m4Index(track),slot=Number(target?.slot); + const ep=safeNativeCounter(hardware?.device?.epoch); + const rev=safeNativeCounter(legacy()?.routingRevision); + const existing=legacy()?.fxInstances?.[channel]||[]; + if(!plugin||!m4Verified()||channel<0|| + !Number.isInteger(slot)||slot<0||slot>=8 || + ep===null||rev===null||existing[slot] || + (slot>0&&!existing[slot-1])){ + status("FX INSERT REJECTED · choose an empty consecutive slot on a native CH with verified route/catalog"); + return true; + } + const requestId="fx-"+(++fxRequestSerial); + pendingFxInsert={requestId,id,channel,slot}; + backend.emitEvent("arMixAction",{action:"routingFxInsert", + requestId,id,channel,slot,deviceEpoch:ep,revision:rev}); + status("CH "+(channel+1)+" · preparing real VST3, awaiting native ACK"); + window.setTimeout(()=>{ + if(pendingFxInsert?.requestId!==requestId)return; + pendingFxInsert=null; + status("FX INSERT timeout; accepted routing preserved"); + controller.subscribe(); + },15000); + return true; + }, consumeDoubleClick(event,t) { if (!connected)return false; if (event.target.classList.contains("fader")){ @@ -1280,16 +1393,25 @@ // Reference-only buttons outside strips must not mutate fake Show/FX state. document.addEventListener("click",event=>{ const target=event.target.closest?.( - "#preview,#addTrack,#addBus,#addFx,#reset,#saveScene,#recallScene,#sceneSafe,#group,#ungroup,#copy,#paste,#clearCue,#pluginsButton,#pluginScan,#pluginImport,#pluginAddPath"); + "#preview,#addTrack,#addBus,#addFx,#reset,#saveScene,#recallScene,#sceneSafe,#group,#ungroup,#copy,#paste,#clearCue,#pluginScan,#pluginImport,#pluginAddPath"); if(!target)return; event.preventDefault();event.stopImmediatePropagation(); - status("NATIVE: "+target.id+" requires real engine admission and readback"); + const action=target.id==="pluginScan"?"scanVst3": + target.id==="pluginImport"?"importVst3": + target.id==="pluginAddPath"?"addScanFolder":null; + if(action){ + backend.emitEvent("arMixAction",{action}); + status("PLUGIN MANAGER · "+action+" requested from native JUCE"); + return; + } + status("NATIVE: "+target.id+" requires admitted engine operation"); },true); // Native fader is committed exactly once INSIDE the original GUI's // finishFaderPointer via build_approved_native_gui.py hook. A later // window.pointerup listener would run after that handler clears the gesture. const ready=()=>{ installFirstSoundMenu(); + scope?.setNativeCatalog?.([]); // no synthetic/demo VST3 in Windows host updateHardwarePanel(null); stopDemo(); status("NATIVE: subscribed · waiting for true device and accepted ChannelId graph"); From 6f561bd1b575b856c33d38a7a41accb79bc72ab1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 19:54:08 +0700 Subject: [PATCH 022/219] Restore accepted visual controls on REJECTED without replacing an actively open hardware select --- web/approved-native-bridge.js | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 4148da832..97b3498b7 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -986,7 +986,12 @@ // cap and every input value; no optimistic GUI state survives. if (!state.pending && flags.acceptedGraphConnected && scope.activeFaderId<0){ - controller.subscribe(); // restore from native, never redraw active selects + // A rejected edit MUST restore the visual model immediately, + // but never unmount an open hardware selector. This also keeps + // existing native transaction rollback semantics testable. + if(!document.activeElement?.matches?.(".strip select")) + scope.render?.(); + controller.subscribe(); if(state.current)paintNativeMeters(state.current); } } From f2974b6408fe959eda8ae580ad092ac49069c20d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 19:55:24 +0700 Subject: [PATCH 023/219] Treat absent native pointer introspection as idle, preserving REJECTED graph rollback in minimal WebView stubs --- web/approved-native-bridge.js | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 97b3498b7..e6dc77f83 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -447,7 +447,7 @@ next?.device?.enabledInputs,next?.device?.inputEndpoints]); if(ports!==lastM4PortSignature){ lastM4PortSignature=ports; - if(scope.activeFaderId<0 && + if((scope.activeFaderId??-1)<0 && !document.activeElement?.matches?.('.strip select')) scope.render?.(); // refresh all hardware choices ONLY after device setup }else{ @@ -985,7 +985,7 @@ // Native REJECTED / STALE / timeout must roll back a temporary fader // cap and every input value; no optimistic GUI state survives. if (!state.pending && flags.acceptedGraphConnected && - scope.activeFaderId<0){ + (scope.activeFaderId??-1)<0){ // A rejected edit MUST restore the visual model immediately, // but never unmount an open hardware selector. This also keeps // existing native transaction rollback semantics testable. From 392430ac74eb5a40e33f805f5b76fbc902e4c9f9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 20:01:02 +0700 Subject: [PATCH 024/219] P0: project actual hardware MAIN fader/mute on admitted ChannelId PCM --- integration/ApprovedNativeRuntimeSnapshot.h | 22 ++++++++++++++++++++ tests/approved_native_v8_projection_test.cpp | 18 ++++++++++++++++ 2 files changed, 40 insertions(+) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 18878f2d9..9f5bc4640 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -233,6 +233,28 @@ inline bool projectInstalledNativeChannelIdGraph( // comes from the verified installed ENGINE status above, not the caller. if (!projectApprovedNativeV8(snapshot,bus,true)) return false; + // ChannelId owns channel PCM, but the physical MAIN gain/mute is + // applied by the single LiveAudioEngine host after that render. The + // generic ChannelId roster's default MAIN fader is not this physical + // gain. Publish the real host readback, or the visible master will + // snap back to 0 dB after every accepted native scalar snapshot. + double physicalMasterDb=0.; + const auto physicalMasterMute=live.getProperty("masterMute",{}); + if(nativeV8Number(live.getProperty("masterDb",{}),physicalMasterDb) && + physicalMasterDb>=-60.01 && physicalMasterDb<=10.01 && + physicalMasterMute.isBool()) { + const auto installedGraph=snapshot.getProperty("graph",{}); + const auto channels=installedGraph.getProperty("channels",{}); + if(auto* rows=channels.getArray()) + for(auto& row:*rows) + if(row.getProperty("role",{}).toString()=="MAIN") { + const auto controls=row.getProperty("controls",{}); + if(auto* obj=controls.getDynamicObject()) { + obj->setProperty("faderDb",physicalMasterDb); + obj->setProperty("mute",physicalMasterMute); + } + } + } // Advertise only controls provided by the currently installed and // positively admitted native callback (never inferred from a JSON shape // or the browser). Both the native and public capability are required by diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 28281eae5..8972fd81d 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -260,6 +260,11 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { "nativeChannelIdPcmActive":true,"epoch":91}})JSON"); live.getProperty("dryRoutingLab",{}).getDynamicObject() ->setProperty("nativeBus",rawBus); + // The physical master is post-ChannelId host PCM, not the generic + // roster's default 0 dB. Keep its accepted gain and mute across native + // projection, even when the source input fader changes independently. + live.getDynamicObject()->setProperty("masterDb",-13.5); + live.getDynamicObject()->setProperty("masterMute",true); auto fail=[&](const juce::var& candidate) { auto before=juce::JSON::toString(snap,false); assert(!projectInstalledNativeChannelIdGraph(snap,candidate)); @@ -290,6 +295,19 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { fail(deny); assert(synchronizeApprovedRouteDeviceEpoch(snap,live)); assert(projectInstalledNativeChannelIdGraph(snap,live)); + const auto projectedRows=snap.getProperty("graph",{}).getProperty("channels",{}); + const auto* projected=projectedRows.getArray(); + assert(projected && projected->size()==2); + bool physicalMasterFound=false; + for(const auto& row:*projected) + if(row.getProperty("role",{}).toString()=="MAIN") { + const auto ctl=row.getProperty("controls",{}); + assert(std::abs(static_cast(ctl.getProperty("faderDb",{})) + -(-13.5))<0.00001); + assert(static_cast(ctl.getProperty("mute",false))); + physicalMasterFound=true; + } + assert(physicalMasterFound); // Real restart: lab routing epoch counts STOP+START, unlike M2 // deviceStartCount. This G0-to-native authority switch must advance. auto disconnected=canonicalSnapshot(); From 9b6ba6e82bfed0536440728f2509144aaae6b2fa Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 20:03:46 +0700 Subject: [PATCH 025/219] P0: route real WIRE-to-MAIN through validated OUT transaction and close verified VST3 picker --- scripts/build_approved_native_gui.py | 3 + tests/approved_native_m2_contract.test.cjs | 16 +++++ web/approved-native-bridge.js | 71 ++++++++++++++++------ 3 files changed, 71 insertions(+), 19 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index c018d8c1d..e94cc9657 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -156,8 +156,11 @@ def accepted_pages_html() -> str: " id:x.id,name:x.name,vendor:x.vendor||'Unknown',category:x.category||'Utility',\n" " format:'VST3',status:'ready',latencySamples:null,\n" " favorite:!!x.favorite,hidden:false}));\n" + " const label=document.querySelector('.plugin-disclaimer');\n" + " if(label)label.textContent='NATIVE JUCE VST3 · only verified scanned catalog entries are insertable';\n" " renderPluginCatalog();renderFastPicker();return pluginCatalog.length;\n" " },\n" + " closeNativePicker(){setFastPicker(false);},\n" " colors:COLORS,wireGraph:ArSonWireGraph,\n" " allocateWireId(){return nextWireId++;},\n" " installGraph(channels,main,edges){\n" diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 91f71ff87..306560678 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -167,6 +167,22 @@ test("DAW G0 native M4 controls, source clear, OUT & monitoring are real",()=>{ assert.match(builder,/type==='output'/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); +test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const builder=read("scripts/build_approved_native_gui.py"); + const native=read("src/Main.cpp"); + assert.match(bridge,/function requestPrimaryOut\(t,target\)/); + assert.match(bridge,/const isMainConnect=/); + assert.match(bridge,/const isMainRemove=/); + assert.match(bridge,/current\.graph\.edges\.some/); + assert.match(bridge,/if\(requestPrimaryOut\(t,target\)\)/); + assert.match(native,/action=="routingChannelPatch"/); + assert.match(native,/engine_\.repatchDryRoutingLabChannel\(channel,/); + assert.match(bridge,/scope\?\.closeNativePicker\?\.\(\)/); + assert.match(builder,/closeNativePicker\(\)\{setFastPicker\(false\);\}/); + assert.match(builder,/NATIVE JUCE VST3/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index e6dc77f83..483db4805 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -263,6 +263,27 @@ let lastM4UiSignature="",lastM4Controls="",nativeUiSourcePending=null; let lastM4PortSignature="",pendingOutputPatch=null,m4RequestSerial=0,outputSerial=7000; const pendingSourceQueue=new Map(); + // One request/ACK/readback path for BOTH the ordinary OUT select and the + // hardware-like OUT→MAIN WIRE jack. No browser graph mutation on click. + function requestPrimaryOut(t,target){ + const channel=m4Index(t); + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(!m4Verified()||channel<0||channel>=10|| + (target!=="MAIN"&&target!=="NONE")||ep===null||rev===null|| + pendingOutputPatch||!deviceReady())return false; + const requestId=++outputSerial; + pendingOutputPatch={requestId,channel,target,epoch:ep}; + backend.emitEvent("arMixAction",{action:"routingChannelPatch", + requestId,channel,target,deviceEpoch:ep,revision:rev}); + window.setTimeout(()=>{ + if(pendingOutputPatch?.requestId!==requestId)return; + pendingOutputPatch=null; + status("CH "+(channel+1)+" OUT timed out · restoring verified native route"); + controller?.subscribe(); + },8000); + return true; + } let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); let pendingNativeControl=new Map(),lastNativeControlSent=new Map(); const m4Meters=new Map(); @@ -1077,6 +1098,7 @@ if(ack?.ok===true && actual?.catalogId===p.id && typeof actual?.instanceId==="string"&&actual.instanceId.length){ status("CH "+(p.channel+1)+" FX loaded · verified native VST3"); + scope?.closeNativePicker?.(); scope?.setNativeCatalog?.([...nativeCatalog.values()]); controller.subscribe(); }else { @@ -1180,27 +1202,13 @@ if(t.kind==="master"){ el.value=t.output;openNativeAudioIO();return true; } - const channel=m4Index(t),target=el.value==="Master"?"MAIN": + const target=el.value==="Master"?"MAIN": el.value==="SOURCE ONLY (No Main)"?"NONE":null; - const ep=safeNativeCounter(hardware?.device?.epoch), - rev=safeNativeCounter(legacy()?.routingRevision); - if(channel<0||target===null||ep===null||rev===null || - pendingOutputPatch||!deviceReady()){ - status("OUT requires a native MAIN/source-only route; unchanged"); - el.value=t.output;return true; - } - if(el.value===t.output)return true; - const requestId=++outputSerial; - pendingOutputPatch={requestId,channel,target,epoch:ep}; + // No optimistic GUI state. Both this menu and the WIRE jack use + // the same ID/epoch-guarded, acknowledged native route transaction. + if(el.value!==t.output && !requestPrimaryOut(t,target)) + status("OUT unavailable · verify device, MAIN route and pending edit"); el.value=t.output; - backend.emitEvent("arMixAction",{action:"routingChannelPatch", - requestId,channel,target,deviceEpoch:ep,revision:rev}); - window.setTimeout(()=>{ - if(pendingOutputPatch?.requestId!==requestId)return; - pendingOutputPatch=null; - status("OUT response timed out; refreshing accepted native route"); - controller.subscribe(); - },8000); return true; } // ONE realtime PCM control for original ten channels and MAIN, @@ -1286,6 +1294,31 @@ consumeWire(ops) { if (!connected)return false; const current=controller?.state().current; + // P0 first-sound WIRE to MAIN is the very same native M4 PRIMARY_OUT + // transaction as the ordinary OUT drop-down. Do not reject a real + // physical CH→MAIN connection merely because P1 dynamic BUS/WIRE + // transaction capability has not been admitted yet. + if(Array.isArray(ops)&&ops.length===1){ + const op=ops[0]; + const t=scope?.tracks?.find(x=>x.id===op.sourceId); + const sourceId=t?nativeByUiId.get(t.id):null; + const isMainConnect=(op.type==="CONNECT"||op.type==="ROUTE_ONLY") && + op.destId===scope?.master?.id; + const edgeId=uiByWireId.get(op.edgeId); + const isMainRemove=op.type==="REMOVE" && sourceId && + current?.admitted===true && + current.graph.edges.some(e=>e.enabled&&e.edgeId===edgeId&& + e.from===sourceId&&e.to===current.graph.mainChannelId); + if(t&&m4Index(t)>=0&&(isMainConnect||isMainRemove)){ + const target=isMainRemove?"NONE":"MAIN"; + if(requestPrimaryOut(t,target)) + status("CH "+(m4Index(t)+1)+" WIRE → "+ + (target==="MAIN"?"MAIN":"SOURCE ONLY")+ + " · awaiting actual native ACK"); + else status("WIRE MAIN unavailable · routing unchanged"); + return true; // original Pages reducer never simulates native PCM + } + } if (!flags.acceptedGraphConnected || !current?.admitted || !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION")) { status("NATIVE: WIRE transaction not admitted; graph unchanged");return true; From 254190c132d639013e3b741db48f0a29c58902ad Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:21:21 +0700 Subject: [PATCH 026/219] P0: reversible DAW fader travel curve and typed native M/ST patch --- integration/ApprovedNativeRuntimeSnapshot.h | 3 +++ site/preview-v2/index.html | 30 ++++++++++++++++++--- src/Main.cpp | 12 ++++++--- 3 files changed, 37 insertions(+), 8 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 9f5bc4640..2150abc57 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -124,6 +124,9 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, verified->setProperty("left",l); verified->setProperty("right",r); verified->setProperty("main",main); + const auto format=item.getProperty("channelFormat",{}).toString(); + if(format=="MONO"||format=="STEREO") + verified->setProperty("channelFormat",format); verifiedChannels.add(juce::var(verified.release())); } if(!valid)verifiedChannels.clear(); diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 7be436edb..573578760 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -601,7 +601,29 @@ const METER_DBFS_MIN=-60, METER_DBFS_MAX=0; function rangePct(v,min,max){return Math.max(0,Math.min(100,100*(Number(v)-min)/(max-min)));} function scaleTopPct(db,min,max){return 100-rangePct(db,min,max);} -function faderPercent(value,isSend){return rangePct(value,-60,isSend?6:10);} +// Console DAW taper: 0 dB at 77% travel, finer control near unity. +// Pure display geometry only; DSP still receives exact gain in dB. +const FADER_TAPER=Object.freeze([ + [-60,0],[-48,15],[-36,27],[-24,39],[-12,54],[-6,65],[0,77],[6,92],[10,100] +]); +function faderPercent(value,isSend){ + if(isSend)return rangePct(value,-60,6); + const db=Math.max(-60,Math.min(10,Number(value))); + for(let i=1;i({frame:meterFrame,gain:tracks[0]?.level??0,running:preview}) }); function sectionFader(t){ @@ -673,7 +695,7 @@ }).join(''); const gainScale=gainTicks.map(v=>{ const major=v!==-6; - return ''+(major?(v>0?'+'+v:v):'')+''; + return ''+(major?(v>0?'+'+v:v):'')+''; }).join(''); return '
'+(isSend?'SEND ':'')+formatDb(value)+' dB
' +'
' @@ -1818,7 +1840,7 @@ if(!travel||travel.height<=0)return; const max=Number(input.max)||10,min=Number(input.min)||-60; const frac=Math.max(0,Math.min(1,(ev.clientY-travel.top)/travel.height)); - const gain=Math.round((max-(max-min)*frac)*10)/10; + const gain=Math.round(faderDbFromTravelPercent(100*(1-frac),max===6)*10)/10; input.value=String(gain); handleField({target:input,type:'input',altKey:!!ev.altKey}); } diff --git a/src/Main.cpp b/src/Main.cpp index 4ebf7adb6..ab50f5aa6 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1567,18 +1567,22 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const int requestId=static_cast(args.getProperty("requestId",0)); const int channel=static_cast(args.getProperty("channel",-1)); const auto target=args.getProperty("target",juce::var()).toString(); + const auto operation=args.getProperty("operation","SET_PRIMARY_OUT").toString(); const auto ep=args.getProperty("deviceEpoch",juce::var()); const auto rv=args.getProperty("revision",juce::var()); - juce::String error="OUT: stale identity, unsupported destination or busy Show"; + juce::String error="CHANNEL PATCH: stale identity, unsupported format/output or busy Show"; + const bool allowed=(operation=="SET_PRIMARY_OUT" && + (target=="MAIN"||target=="NONE")) || + (operation=="SET_PROCESSING_FORMAT" && + (target=="MONO"||target=="STEREO")); if(requestId>0 && channel>=0 && channel(static_cast(ep)), static_cast(static_cast(rv)), - "SET_PRIMARY_OUT",target); + operation,target); auto ack=std::make_unique(); ack->setProperty("requestId",requestId); ack->setProperty("channel",channel); From b30880bf395cbb80f9b3dfd802f2b0adad6020dd Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:22:42 +0700 Subject: [PATCH 027/219] P0: native per-channel format, PAN center latch/readout, and actionable FX error --- tests/approved_native_m2_contract.test.cjs | 20 ++++ web/approved-native-bridge.js | 114 +++++++++++++++++++-- 2 files changed, 124 insertions(+), 10 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 306560678..52374b392 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -183,6 +183,26 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(builder,/NATIVE JUCE VST3/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); +test("P0 typed mono-stereo, PAN detent, fader geometry & FX failure diagnostics",()=>{ + const page=read("site/preview-v2/index.html"); + const bridge=read("web/approved-native-bridge.js"); + const main=read("src/Main.cpp"); + const snapshot=read("integration/ApprovedNativeRuntimeSnapshot.h"); + assert.match(page,/const FADER_TAPER=Object\.freeze/); + assert.match(page,/function faderDbFromTravelPercent\(percent,isSend\)/); + assert.match(page,/faderDbFromTravelPercent\(100\*\(1-frac\),max===6\)/); + assert.match(bridge,/function previewNativePan\(t,el,event\)/); + assert.match(bridge,/const width=event\.type==="change"\?12:latched\?12:7/); + assert.match(bridge,/readout\.textContent=value===0\?"C"/); + assert.match(bridge,/function requestProcessingFormat\(t\)/); + assert.match(bridge,/operation:"SET_PROCESSING_FORMAT"/); + assert.match(bridge,/if\(action==="format"&&t\?\.kind==="audio"\)/); + assert.match(main,/operation=="SET_PROCESSING_FORMAT"/); + assert.match(main,/operation,target\)/); + assert.match(snapshot,/verified->setProperty\("channelFormat",format\)/); + assert.match(bridge,/backend\.addEventListener\("arMixNotice"/); + assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 483db4805..74e4db7a0 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -263,6 +263,58 @@ let lastM4UiSignature="",lastM4Controls="",nativeUiSourcePending=null; let lastM4PortSignature="",pendingOutputPatch=null,m4RequestSerial=0,outputSerial=7000; const pendingSourceQueue=new Map(); + function requestProcessingFormat(t){ + const channel=m4Index(t); + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(!m4Verified()||channel<0||channel>=10|| + ep===null||rev===null||pendingOutputPatch||nativeUiSourcePending|| + !deviceReady()){ + status("M/ST unavailable · wait for accepted hardware route"); + return false; + } + const target=t.format==="mono"?"STEREO":"MONO"; + const requestId=++outputSerial; + pendingOutputPatch={requestId,channel,target,epoch:ep, + operation:"SET_PROCESSING_FORMAT"}; + backend.emitEvent("arMixAction",{action:"routingChannelPatch", + operation:"SET_PROCESSING_FORMAT",requestId,channel,target, + deviceEpoch:ep,revision:rev}); + status("CH "+(channel+1)+" processing "+target+" · verifying native PCM"); + window.setTimeout(()=>{ + if(pendingOutputPatch?.requestId!==requestId)return; + pendingOutputPatch=null; + status("CH "+(channel+1)+" M/ST timed out · prior format preserved"); + controller?.subscribe(); + },8000); + return true; + } + function previewNativePan(t,el,event){ + let value=Math.max(-100,Math.min(100,Number(el.value))); + if(!Number.isFinite(value))return null; + // Identical center latch to the approved Pages mixer: capture at 7, + // hold until 12, snap on release. No fake demo-model DSP mutation. + const keyboard=el.dataset.panKeyboard==="true"; + const bypass=!!event.altKey||el.dataset.panAltPointer==="true"; + const latched=el.dataset.panDetent==="true"; + const width=event.type==="change"?12:latched?12:7; + if(!keyboard&&!bypass&&Math.abs(value)<=width){value=0;el.value="0";} + el.dataset.panDetent=String(!keyboard&&value===0&&!bypass); + if(event.type==="change")delete el.dataset.panKeyboard; + el.setAttribute?.("aria-valuetext",value===0?"Center": + value<0?"Left "+Math.abs(value):"Right "+value); + const container=el.closest?.(".pan-control"); + if(container){ + const left=Math.min(50,50+value/2),right=Math.max(50,50+value/2); + container.style?.setProperty("--pan-start",left+"%"); + container.style?.setProperty("--pan-end",right+"%"); + container.classList?.toggle("is-centered",value===0); + const readout=container.nextElementSibling; + if(readout)readout.textContent=value===0?"C": + value<0?"L"+Math.abs(value):"R"+value; + } + return value; + } // One request/ACK/readback path for BOTH the ordinary OUT select and the // hardware-like OUT→MAIN WIRE jack. No browser graph mutation on click. function requestPrimaryOut(t,target){ @@ -272,8 +324,14 @@ if(!m4Verified()||channel<0||channel>=10|| (target!=="MAIN"&&target!=="NONE")||ep===null||rev===null|| pendingOutputPatch||!deviceReady())return false; + const accepted=legacy()?.channels?.[channel]; + if(accepted?.main===(target==="MAIN")){ + status("CH "+(channel+1)+" OUT already "+ + (target==="MAIN"?"MAIN":"SOURCE ONLY")+" · native readback"); + controller?.subscribe();return true; // no need to blink audio + } const requestId=++outputSerial; - pendingOutputPatch={requestId,channel,target,epoch:ep}; + pendingOutputPatch={requestId,channel,target,epoch:ep,operation:"SET_PRIMARY_OUT"}; backend.emitEvent("arMixAction",{action:"routingChannelPatch", requestId,channel,target,deviceEpoch:ep,revision:rev}); window.setTimeout(()=>{ @@ -461,6 +519,15 @@ t.input=inputLabelFor(row); if(row && typeof row.main==="boolean") t.output=row.main?"Master":"SOURCE ONLY (No Main)"; + if(row && ["MONO","STEREO"].includes(row.channelFormat)){ + const format=row.channelFormat.toLowerCase(); + if(t.format!==format){ + t.format=format; + if((scope.activeFaderId??-1)!==t.id && + !document.activeElement?.matches?.(".strip select")) + scope.refreshStrip?.(t); + } + } } // A source ACK changes only affected fields; never replace the whole // mixer while another select is open or another fader is being dragged. @@ -1084,11 +1151,20 @@ const p=pendingOutputPatch; pendingOutputPatch=null; const row=ack?.state?.acceptedRoute?.channels?.[p.channel]; - if(ack?.ok===true && Number(ack.state?.epoch)===p.epoch && - row?.main===(p.target==="MAIN")) - status("CH "+(p.channel+1)+" OUT accepted; verifying native readback"); - else status("CH "+(p.channel+1)+" OUT rejected · "+ - (ack?.error||"stale route")); + const accepted=ack?.ok===true && Number(ack.state?.epoch)===p.epoch && + (p.operation==="SET_PROCESSING_FORMAT"? + row?.channelFormat===p.target: + row?.main===(p.target==="MAIN")); + if(accepted) + status("CH "+(p.channel+1)+" "+ + (p.operation==="SET_PROCESSING_FORMAT"?"M/ST ":"OUT ")+p.target+ + " accepted · verifying native PCM"); + else { + status("CH "+(p.channel+1)+" "+ + (p.operation==="SET_PROCESSING_FORMAT"?"M/ST":"OUT")+ + " rejected · "+(ack?.error||"stale route")); + nativeToast(ack?.error||"Native channel route rejected"); + } controller.subscribe(); }); backend.addEventListener("arMixRoutingFxInsertAck",ack=>{ @@ -1102,7 +1178,9 @@ scope?.setNativeCatalog?.([...nativeCatalog.values()]); controller.subscribe(); }else { - status("FX INSERT REJECTED · "+(ack?.error||"native readback mismatch")); + const reason=ack?.error||"native FX instance missing from accepted PCM"; + status("FX INSERT REJECTED · "+reason); + nativeToast(reason); controller.subscribe(); } }); @@ -1122,6 +1200,12 @@ "Scanning real VST3… "+(progress.done||0)+"/"+(progress.total||"…"): "Native VST3 scan finished; results from JUCE catalog"; }); + backend.addEventListener("arMixNotice",notice=>{ + if(notice?.error===true && typeof notice.message==="string"){ + nativeToast(notice.message); // native VST3/driver cause survives 12Hz status repaint + status("JUCE · "+notice.message); + } + }); backend.addEventListener("arMixAudioArmAck", ack=>{ if(pendingDeviceMute){ // Reject any stale/unrelated ACK and any device epoch change. @@ -1218,9 +1302,9 @@ (m4Index(t)>=0||t.kind==="master")){ const numeric=Number(el.value); if(!Number.isFinite(numeric))return true; - const normalized=field==="pan" && - !el.dataset.panKeyboard && !el.dataset.panAltPointer && - Math.abs(numeric)<=12 ? 0:numeric; + const normalized=field==="pan"? + previewNativePan(t,el,event):numeric; + if(normalized===null)return true; const key=field==="level"? (t.kind==="master"?"masterGain":"faderDb"):"pan"; if(field==="level")previewFaderWithoutModelMutation(t,numeric); @@ -1275,6 +1359,16 @@ scope?.openFastPicker?.(t,Number(btn?.dataset.slot),btn); return true; } + if(action==="format"&&t?.kind==="audio"){ + requestProcessingFormat(t);return true; + } + if(action==="cue"){ + // PFL must use a separate physical pre-fader monitor bus; do not + // make a GUI-only toggle or mix a cue into audience MAIN. + nativeToast("PFL requires a separate MONITOR L/R pair; MAIN unchanged"); + status("PFL not armed · independent physical MONITOR output required"); + return true; + } if (action==="mute"||action==="solo") { if(m4Verified() && t.kind==="master" && action==="mute"){ if(!sendM4Control("masterMute",t,!t.mute)) From 937781604585a7edba8bb1306905cd23ddf14e7a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:27:04 +0700 Subject: [PATCH 028/219] P0: isolate DAW fader taper to native-only reversible bundle; preserve Pages V28 checksum --- scripts/build_approved_native_gui.py | 26 +++++++++++++++++++ site/preview-v2/index.html | 30 +++------------------- tests/approved_native_m2_contract.test.cjs | 8 +++--- 3 files changed, 35 insertions(+), 29 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index e94cc9657..2f69cdbdf 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -57,6 +57,32 @@ def accepted_pages_html() -> str: # HTML at native build time. Every anchor must occur exactly once: no silent # breakage if Pages GUI source evolves. No extra layout or simulated PCM. NATIVE_EVENT_HOOKS = ( + # The published /preview/ HTML and its V28 checkpoint are immutable. + # Change ONLY the compiled native WebView's operator fader travel law. + # The DSP gain remains exact dB -> 10^(dB/20), and the mapping is + # invertible at every tick; no new JS audio engine or controller. + ("function faderPercent(value,isSend){return rangePct(value,-60,isSend?6:10);}\n", + "const FADER_TAPER=Object.freeze([[-60,0],[-48,15],[-36,27],[-24,39],[-12,54],[-6,65],[0,77],[6,92],[10,100]]);\n" + "function faderPercent(value,isSend){\n" + " if(isSend)return rangePct(value,-60,6);\n" + " const db=Math.max(-60,Math.min(10,Number(value)));\n" + " for(let i=1;i{\n", diff --git a/site/preview-v2/index.html b/site/preview-v2/index.html index 573578760..7be436edb 100644 --- a/site/preview-v2/index.html +++ b/site/preview-v2/index.html @@ -601,29 +601,7 @@ const METER_DBFS_MIN=-60, METER_DBFS_MAX=0; function rangePct(v,min,max){return Math.max(0,Math.min(100,100*(Number(v)-min)/(max-min)));} function scaleTopPct(db,min,max){return 100-rangePct(db,min,max);} -// Console DAW taper: 0 dB at 77% travel, finer control near unity. -// Pure display geometry only; DSP still receives exact gain in dB. -const FADER_TAPER=Object.freeze([ - [-60,0],[-48,15],[-36,27],[-24,39],[-12,54],[-6,65],[0,77],[6,92],[10,100] -]); -function faderPercent(value,isSend){ - if(isSend)return rangePct(value,-60,6); - const db=Math.max(-60,Math.min(10,Number(value))); - for(let i=1;i({frame:meterFrame,gain:tracks[0]?.level??0,running:preview}) }); function sectionFader(t){ @@ -695,7 +673,7 @@ }).join(''); const gainScale=gainTicks.map(v=>{ const major=v!==-6; - return ''+(major?(v>0?'+'+v:v):'')+''; + return ''+(major?(v>0?'+'+v:v):'')+''; }).join(''); return '
'+(isSend?'SEND ':'')+formatDb(value)+' dB
' +'
' @@ -1840,7 +1818,7 @@ if(!travel||travel.height<=0)return; const max=Number(input.max)||10,min=Number(input.min)||-60; const frac=Math.max(0,Math.min(1,(ev.clientY-travel.top)/travel.height)); - const gain=Math.round(faderDbFromTravelPercent(100*(1-frac),max===6)*10)/10; + const gain=Math.round((max-(max-min)*frac)*10)/10; input.value=String(gain); handleField({target:input,type:'input',altKey:!!ev.altKey}); } diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 52374b392..b1e576cbe 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -188,9 +188,11 @@ test("P0 typed mono-stereo, PAN detent, fader geometry & FX failure diagnostics" const bridge=read("web/approved-native-bridge.js"); const main=read("src/Main.cpp"); const snapshot=read("integration/ApprovedNativeRuntimeSnapshot.h"); - assert.match(page,/const FADER_TAPER=Object\.freeze/); - assert.match(page,/function faderDbFromTravelPercent\(percent,isSend\)/); - assert.match(page,/faderDbFromTravelPercent\(100\*\(1-frac\),max===6\)/); + const nativeBundle=read("scripts/build_approved_native_gui.py"); + assert.match(nativeBundle,/const FADER_TAPER=Object\.freeze/); + assert.match(nativeBundle,/function faderDbFromTravelPercent\(percent,isSend\)/); + assert.match(nativeBundle,/faderDbFromTravelPercent\(100\*\(1-frac\),max===6\)/); + assert.doesNotMatch(page,/FADER_TAPER/, "public Pages reference remains immutable"); assert.match(bridge,/function previewNativePan\(t,el,event\)/); assert.match(bridge,/const width=event\.type==="change"\?12:latched\?12:7/); assert.match(bridge,/readout\.textContent=value===0\?"C"/); From 3ec6500ee54e54ca7c40ce13b592dea7ce9dd6f3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:29:47 +0700 Subject: [PATCH 029/219] =?UTF-8?q?P0:=20fix=20reversed=20WIRE=20EdgeId=20?= =?UTF-8?q?mapping=20for=20real=20CH=E2=86=92MAIN=20disconnect?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- tests/approved_native_m2_contract.test.cjs | 8 ++++++++ web/approved-native-bridge.js | 14 ++++++++++---- 2 files changed, 18 insertions(+), 4 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index b1e576cbe..450ace488 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -205,6 +205,14 @@ test("P0 typed mono-stereo, PAN detent, fader geometry & FX failure diagnostics" assert.match(bridge,/backend\.addEventListener\("arMixNotice"/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); +test("P0 MAIN WIRE unplug uses UI-to-native EdgeId and no fake graph",()=>{ + const adapter=read("web/approved-native-bridge.js"); + assert.match(adapter,/const edgeId=wireByUiId\.get\(op\.edgeId\)/); + assert.doesNotMatch(adapter,/const edgeId=uiByWireId\.get\(op\.edgeId\)/); + assert.match(adapter,/current\.graph\.edges\.some/); + assert.match(adapter,/WIRE BUS\/FX return is not admitted/); + assert.match(adapter,/requestPrimaryOut\(t,target\)/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 74e4db7a0..7c7c1aee8 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1398,7 +1398,10 @@ const sourceId=t?nativeByUiId.get(t.id):null; const isMainConnect=(op.type==="CONNECT"||op.type==="ROUTE_ONLY") && op.destId===scope?.master?.id; - const edgeId=uiByWireId.get(op.edgeId); + // WIRE gesture carries a UI edge id. wireByUiId is UI→native; + // uiByWireId is the inverse. The old inverse lookup always returned + // undefined, so unplugging an existing MAIN wire was impossible. + const edgeId=wireByUiId.get(op.edgeId); const isMainRemove=op.type==="REMOVE" && sourceId && current?.admitted===true && current.graph.edges.some(e=>e.enabled&&e.edgeId===edgeId&& @@ -1408,14 +1411,17 @@ if(requestPrimaryOut(t,target)) status("CH "+(m4Index(t)+1)+" WIRE → "+ (target==="MAIN"?"MAIN":"SOURCE ONLY")+ - " · awaiting actual native ACK"); - else status("WIRE MAIN unavailable · routing unchanged"); + " · native ACK/readback required"); + else nativeToast("WIRE MAIN unavailable · verify channel and routing state"); return true; // original Pages reducer never simulates native PCM } } if (!flags.acceptedGraphConnected || !current?.admitted || !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION")) { - status("NATIVE: WIRE transaction not admitted; graph unchanged");return true; + const reason="WIRE BUS/FX return is not admitted by the installed PCM graph"; + status("NATIVE: "+reason+" · no audio reroute"); + nativeToast(reason); + return true; } const changes=[]; for (const op of ops) { From 94530b9060de506b96df09c9c2ef8eec9d579e49 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:31:29 +0700 Subject: [PATCH 030/219] P0: disambiguate native-only gain ruler hook from existing Pages layout --- scripts/build_approved_native_gui.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 2f69cdbdf..4c7a938ad 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -80,7 +80,7 @@ def accepted_pages_html() -> str: " }return 10;\n" "}\n"), ("scaleTopPct(v,-60,gainMax)", - "(100-faderPercent(v,isSend))"), + "(100.0-faderPercent(v,isSend))"), (" const gain=Math.round((max-(max-min)*frac)*10)/10;\n", " const gain=Math.round(faderDbFromTravelPercent(100*(1-frac),max===6)*10)/10;\n"), # Only the compiled Windows WebView gets verified native driver inputs. From 988abf9cccdeb715646dd5e60164efe928d2ceb6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:34:28 +0700 Subject: [PATCH 031/219] P0: bind loaded VST3 slot power and editor to verified JUCE instance --- src/Main.cpp | 3 + tests/approved_native_m2_contract.test.cjs | 14 ++++ web/approved-native-bridge.js | 78 +++++++++++++++++++++- 3 files changed, 94 insertions(+), 1 deletion(-) diff --git a/src/Main.cpp b/src/Main.cpp index ab50f5aa6..b4e3e722e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1767,6 +1767,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr lane,slot,epoch,revision,token,static_cast(value)); auto ack=std::make_unique(); ack->setProperty("ok",ok); + ack->setProperty("requestId",args.getProperty("requestId",juce::var())); + ack->setProperty("channel",lane); + ack->setProperty("slot",slot); ack->setProperty("error",ok?juce::String(): "FX bypass rejected: route revision, instance or device changed"); ack->setProperty("state",engine_.status().getProperty("dryRoutingLab",{})); diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 450ace488..a9eb00d82 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -213,6 +213,20 @@ test("P0 MAIN WIRE unplug uses UI-to-native EdgeId and no fake graph",()=>{ assert.match(adapter,/WIRE BUS\/FX return is not admitted/); assert.match(adapter,/requestPrimaryOut\(t,target\)/); }); +test("P0 real slot VST3 power and native editor use verified instance tokens",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const main=read("src/Main.cpp"); + assert.match(bridge,/function verifiedFxFor\(t,slot\)/); + assert.match(bridge,/function requestNativeFxPower\(t,slot,bypass\)/); + assert.match(bridge,/if\(action==="slotPower"\)/); + assert.match(bridge,/if\(action==="fxOn"\)/); + assert.match(bridge,/action:"routingFxEditor"/); + assert.match(bridge,/action:"routingFxBypass"/); + assert.match(bridge,/backend\.addEventListener\("arMixRoutingFxBypassAck"/); + assert.match(main,/ack->setProperty\("requestId",args\.getProperty\("requestId",juce::var\(\)\)\)/); + assert.match(main,/action == "routingFxEditor"/); + assert.match(main,/action == "routingFxBypass"/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 7c7c1aee8..95cb9fc41 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -343,6 +343,34 @@ return true; } let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); + const pendingSlotPowers=new Map(); // ACK/readback, never demo FX flags + function verifiedFxFor(t,slot){ + const lane=m4Index(t),live=legacy()?.fxInstances?.[lane]?.[slot]; + return lane>=0 && Number.isInteger(slot) && slot>=0&&slot<8 && + live && typeof live.instanceId==="string" && + live.instanceId && typeof live.catalogId==="string"? + {lane,slot,live}:null; + } + function requestNativeFxPower(t,slot,bypass){ + const picked=verifiedFxFor(t,slot); + if(!picked||!m4Verified())return false; + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + const {lane,live}=picked,requestId="fxpower-"+(++fxRequestSerial); + if(ep===null||rev===null||pendingSlotPowers.has(lane+":"+slot)) + return false; + pendingSlotPowers.set(lane+":"+slot,{requestId,token:live.instanceId,bypass}); + backend.emitEvent("arMixAction",{action:"routingFxBypass", + requestId,channel:lane,slot,instanceId:live.instanceId, + deviceEpoch:ep,revision:rev,value:bypass}); + window.setTimeout(()=>{ + if(pendingSlotPowers.get(lane+":"+slot)?.requestId!==requestId)return; + pendingSlotPowers.delete(lane+":"+slot); + status("FX bypass timed out · restoring real rack state"); + controller?.subscribe(); + },5000); + return true; + } let pendingNativeControl=new Map(),lastNativeControlSent=new Map(); const m4Meters=new Map(); const m4Verified=()=>{ @@ -1167,6 +1195,22 @@ } controller.subscribe(); }); + backend.addEventListener("arMixRoutingFxBypassAck",ack=>{ + const key=(Number(ack?.channel)||0)+":"+Number(ack?.slot); + // Legacy ACKs without channel/requestId can never authorize an + // arbitrary in-flight slot or paint an invented bypass state. + const pending=pendingSlotPowers.get(key); + if(!pending||pending.requestId!==ack?.requestId)return; + pendingSlotPowers.delete(key); + if(ack?.ok!==true) + nativeToast(ack?.error||"Native VST3 bypass rejected"); + controller?.subscribe(); // real FxInstance state owns visual power + }); + backend.addEventListener("arMixRoutingFxEditorAck",ack=>{ + if(ack?.ok!==true) + nativeToast(ack?.error||"VST3 editor could not open"); + else status("Native VST3 editor opened"); + }); backend.addEventListener("arMixRoutingFxInsertAck",ack=>{ if(!pendingFxInsert||ack?.requestId!==pendingFxInsert.requestId)return; const p=pendingFxInsert;pendingFxInsert=null; @@ -1356,7 +1400,39 @@ if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action)) return !["wireExpand","wireSource","wireRoute"].includes(action); if(action==="openPlugin"){ - scope?.openFastPicker?.(t,Number(btn?.dataset.slot),btn); + const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); + if(instance){ + const ep=safeNativeCounter(hardware?.device?.epoch), + rev=safeNativeCounter(legacy()?.routingRevision); + if(ep!==null&&rev!==null) + backend.emitEvent("arMixAction",{action:"routingFxEditor", + channel:instance.lane,slot, + instanceId:instance.live.instanceId,deviceEpoch:ep,revision:rev}); + else nativeToast("VST3 editor · refresh native device and FX instance"); + }else scope?.openFastPicker?.(t,slot,btn); + return true; + } + if(action==="slotPower"){ + const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); + if(!instance||!requestNativeFxPower(t,slot,!instance.live.bypassed)) + nativeToast("FX bypass unavailable · select an accepted VST3 slot"); + return true; + } + if(action==="fxOn"){ + // A rack-wide toggle is a coordinated group of native atomic + // per-instance bypasses, not a purely visual FX Rack power icon. + const lane=m4Index(t),rows=legacy()?.fxInstances?.[lane]||[]; + if(lane<0||!m4Verified()||!rows.length){ + nativeToast("FX rack is empty · choose a VST3 insert first");return true; + } + const off=rows.some(row=>row?.bypassed===false); + let sent=0; + for(let slot=0;slot Date: Thu, 5 Nov 2026 21:36:06 +0700 Subject: [PATCH 032/219] P0: preserve per-instance power across native FX rack header bypass/restore --- tests/approved_native_m2_contract.test.cjs | 3 ++ web/approved-native-bridge.js | 59 ++++++++++++++++++---- 2 files changed, 52 insertions(+), 10 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index a9eb00d82..f4943acec 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -220,6 +220,9 @@ test("P0 real slot VST3 power and native editor use verified instance tokens",() assert.match(bridge,/function requestNativeFxPower\(t,slot,bypass\)/); assert.match(bridge,/if\(action==="slotPower"\)/); assert.match(bridge,/if\(action==="fxOn"\)/); + assert.match(bridge,/const rackSavedBypass=new Map\(\)/); + assert.match(bridge,/saved\.get\(row\.instanceId\)/); + assert.match(bridge,/rackSavedBypass\.set\(lane,original\)/); assert.match(bridge,/action:"routingFxEditor"/); assert.match(bridge,/action:"routingFxBypass"/); assert.match(bridge,/backend\.addEventListener\("arMixRoutingFxBypassAck"/); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 95cb9fc41..9559015e9 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -344,6 +344,9 @@ } let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); const pendingSlotPowers=new Map(); // ACK/readback, never demo FX flags + const rackSavedBypass=new Map(); // lane -> instanceId / original bypass + // The rack header restores exact prior per-insert state, including + // deliberately bypassed plugins; it never blindly turns ALL FX on. function verifiedFxFor(t,slot){ const lane=m4Index(t),live=legacy()?.fxInstances?.[lane]?.[slot]; return lane>=0 && Number.isInteger(slot) && slot>=0&&slot<8 && @@ -427,6 +430,8 @@ const rows=m.fxInstances[lane]; if(!t||!Array.isArray(rows))continue; let change=false; + const headerOff=rackSavedBypass.has(lane); + if(t.fxOn===headerOff){t.fxOn=!headerOff;change=true;} for(let slot=0;slot<8;slot++){ const live=rows[slot],entry=nativeCatalog.get(live?.catalogId); const name=live?(entry?.name||"VST3 Loaded"):"None"; @@ -1413,26 +1418,57 @@ return true; } if(action==="slotPower"){ + const lane=m4Index(t); + if(rackSavedBypass.has(lane)){ + nativeToast("Enable FX rack header before changing individual inserts"); + return true; + } const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); if(!instance||!requestNativeFxPower(t,slot,!instance.live.bypassed)) nativeToast("FX bypass unavailable · select an accepted VST3 slot"); return true; } if(action==="fxOn"){ - // A rack-wide toggle is a coordinated group of native atomic - // per-instance bypasses, not a purely visual FX Rack power icon. const lane=m4Index(t),rows=legacy()?.fxInstances?.[lane]||[]; if(lane<0||!m4Verified()||!rows.length){ nativeToast("FX rack is empty · choose a VST3 insert first");return true; } - const off=rows.some(row=>row?.bypassed===false); - let sent=0; - for(let slot=0;slotkey.startsWith(lane+":"))){ + status("FX rack power · waiting for existing native bypass ACK"); + return true; + } + const saved=rackSavedBypass.get(lane); + if(!saved){ + const original=new Map(rows.filter(x=>x?.instanceId).map(x=> + [x.instanceId,x.bypassed===true])); + rackSavedBypass.set(lane,original); + let applied=0; + for(let slot=0;slotx&&!x.bypassed)){ + rackSavedBypass.delete(lane); + nativeToast("Rack bypass failed · original FX power preserved"); + }else status("CH "+(lane+1)+" FX rack OFF requested · "+ + "individual ON/OFF states saved"); + }else{ + const current=new Set(rows.filter(x=>x?.instanceId).map(x=>x.instanceId)); + if(saved.size!==current.size || [...saved.keys()].some(id=>!current.has(id))){ + nativeToast("FX rack changed · cannot restore stale insert identity"); + return true; + } + let applied=0; + for(let slot=0;slot=8 || ep===null||rev===null||existing[slot] || From 5535201e5226b97089588ea57d402fd457c5699d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:38:41 +0700 Subject: [PATCH 033/219] P0: reject stale/invalid VST3 inserts before muting accepted live audio --- src/LiveAudioEngine.h | 7 +++++ src/LiveDryRoutingLab.h | 33 +++++++++++++++------- tests/approved_native_m2_contract.test.cjs | 9 ++++++ 3 files changed, 39 insertions(+), 10 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 92f37dfed..a621c8718 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1233,6 +1233,13 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "FX INSERT: CH1 latent VST3 needs PDC before routed inserts"; auto* device=deviceManager_.getCurrentAudioDevice(); if(!device)return "FX INSERT: select an actual audio device"; + const auto preflight=dryRoutingLab_.fxInsertPreflight( + lane,slot,epoch,revision,chosen); + if(preflight.isNotEmpty())return preflight; + auto* pluginFormat=formats_.getFormat(0); + if(!pluginFormat || + !pluginFormat->fileMightContainThisPluginType(chosen.path)) + return "FX INSERT: VST3 bundle unavailable or invalid; rescan catalog"; const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); return applyGuardedDryTopology(epoch,frames,[&] { return dryRoutingLab_.insertCatalogFx(lane,slot,epoch,revision, diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 1a6a3ef02..a5d67d6af 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -480,15 +480,13 @@ class LiveDryRoutingLab final { } - // Native /preview/ FX picker: append one catalog-verified stereo VST3 to - // the SAME accepted ten-channel/4AUX renderer. This is a prepared graph - // transaction on JUCE CONTROL, never a JS plugin or RT instantiation. - juce::String insertCatalogFx(int lane,int slot, + // Realtime audio must not briefly MUTE for an FX command guaranteed + // to reject (stale epoch, invalid lane/slot, unsupported native BUS, + // non-contiguous inserts). Validate BEFORE the guarded graph edit. + // CONTROL-only, bounded and read-only: no vendor scan/heap/RT effects. + juce::String fxInsertPreflight(int lane,int slot, std::uint64_t expectedEpoch,std::uint64_t expectedRevision, - const FxSelection& chosen,bool directPermitted, - bool independentClock,int occupiedCh1Fx, - juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) { + const FxSelection& chosen) const { if(lane<0||lane>=fxSlots||slot<0||slot>=maxFxPerLane|| chosen.id.isEmpty()||chosen.path.isEmpty()||chosen.name.isEmpty()|| !ready()||!hasExplicitRoute()||nativeStructureLive_|| @@ -496,11 +494,26 @@ class LiveDryRoutingLab final { !registryValid_.load(std::memory_order_acquire)|| expectedEpoch!=epoch()||expectedRevision!=revision()|| !sourceTemplate_.isObject()) - return "FX INSERT: stale routing/ChannelId authority or unsupported lane"; + return "FX INSERT: stale routing/ChannelId authority or invalid catalog slot"; if(acceptedFxSelections_[lane][slot].id.isNotEmpty()) return "FX INSERT: this slot already has a native VST3"; if(slot>0&&acceptedFxSelections_[lane][slot-1].id.isEmpty()) - return "FX INSERT: use the first empty insert position"; + return "FX INSERT: choose the first empty insert position"; + return {}; + } + + // Native /preview/ FX picker: append one catalog-verified stereo VST3 to + // the SAME accepted ten-channel/4AUX renderer. This is a prepared graph + // transaction on JUCE CONTROL, never a JS plugin or RT instantiation. + juce::String insertCatalogFx(int lane,int slot, + std::uint64_t expectedEpoch,std::uint64_t expectedRevision, + const FxSelection& chosen,bool directPermitted, + bool independentClock,int occupiedCh1Fx, + juce::AudioPluginFormatManager& formats,double sampleRate, + int deviceFrames) { + const auto preflight=fxInsertPreflight( + lane,slot,expectedEpoch,expectedRevision,chosen); + if(preflight.isNotEmpty())return preflight; auto command=juce::JSON::parse( juce::JSON::toString(sourceTemplate_,false)); if(!command.isObject()) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f4943acec..6d0d07d22 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -230,6 +230,15 @@ test("P0 real slot VST3 power and native editor use verified instance tokens",() assert.match(main,/action == "routingFxEditor"/); assert.match(main,/action == "routingFxBypass"/); }); +test("P0 FX command preflight never mutes monitoring for deterministic rejection",()=>{ + const lab=read("src/LiveDryRoutingLab.h"); + const engine=read("src/LiveAudioEngine.h"); + assert.match(lab,/juce::String fxInsertPreflight\(int lane,int slot/); + assert.match(lab,/const auto preflight=fxInsertPreflight\(/); + assert.match(engine,/dryRoutingLab_\.fxInsertPreflight\(/); + assert.match(engine,/pluginFormat->fileMightContainThisPluginType\(chosen\.path\)/); + assert.match(engine,/FX INSERT: VST3 bundle unavailable or invalid/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); From 5e5fed256b9aaeadc2e96efef3ffc3d07b6e73a1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Thu, 5 Nov 2026 21:40:13 +0700 Subject: [PATCH 034/219] P0: keep SOURCE ONLY OUT visibly pending until native ACK/readback --- tests/approved_native_m2_contract.test.cjs | 2 ++ web/approved-native-bridge.js | 30 +++++++++++++++++++--- 2 files changed, 28 insertions(+), 4 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 6d0d07d22..3c690f233 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -208,6 +208,8 @@ test("P0 typed mono-stereo, PAN detent, fader geometry & FX failure diagnostics" test("P0 MAIN WIRE unplug uses UI-to-native EdgeId and no fake graph",()=>{ const adapter=read("web/approved-native-bridge.js"); assert.match(adapter,/const edgeId=wireByUiId\.get\(op\.edgeId\)/); + assert.match(adapter,/menu\.setAttribute\("aria-busy","true"\)/); + assert.match(adapter,/el\.removeAttribute\("aria-busy"\)/); assert.doesNotMatch(adapter,/const edgeId=uiByWireId\.get\(op\.edgeId\)/); assert.match(adapter,/current\.graph\.edges\.some/); assert.match(adapter,/WIRE BUS\/FX return is not admitted/); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 9559015e9..c4a13dbf7 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -332,6 +332,14 @@ } const requestId=++outputSerial; pendingOutputPatch={requestId,channel,target,epoch:ep,operation:"SET_PRIMARY_OUT"}; + const menu=document.querySelector('.strip[data-id="'+t.id+'"] select[data-field="output"]'); + // A draft visibly stays selected while pending, but t.output and + // audio graph remain exclusively the native accepted readback. + if(menu){ + menu.value=target==="MAIN"?"Master":"SOURCE ONLY (No Main)"; + menu.setAttribute("aria-busy","true"); + menu.title="Routing pending · awaiting native ACK and PCM readback"; + } backend.emitEvent("arMixAction",{action:"routingChannelPatch", requestId,channel,target,deviceEpoch:ep,revision:rev}); window.setTimeout(()=>{ @@ -578,6 +586,8 @@ const root=document.querySelector('.strip[data-id="'+t.id+'"]'); for(const field of ["input","output"]){ const element=root?.querySelector('select[data-field="'+field+'"]'); + if(field==="output"&&pendingOutputPatch?.channel===i && + pendingOutputPatch?.operation==="SET_PRIMARY_OUT")continue; if(element && document.activeElement!==element && element.value!==t[field])element.value=t[field]; } @@ -1183,16 +1193,26 @@ if(!pendingOutputPatch||ack?.requestId!==pendingOutputPatch.requestId)return; const p=pendingOutputPatch; pendingOutputPatch=null; + const t=scope?.tracks?.find(x=>m4Index(x)===p.channel); + const el=t?document.querySelector( + '.strip[data-id="'+t.id+'"] select[data-field="output"]'):null; + if(el){ + el.removeAttribute("aria-busy"); + el.title="Primary output · verified native routing"; + } const row=ack?.state?.acceptedRoute?.channels?.[p.channel]; const accepted=ack?.ok===true && Number(ack.state?.epoch)===p.epoch && (p.operation==="SET_PROCESSING_FORMAT"? row?.channelFormat===p.target: row?.main===(p.target==="MAIN")); - if(accepted) + if(accepted) { + if(el&&p.operation==="SET_PRIMARY_OUT") + el.value=p.target==="MAIN"?"Master":"SOURCE ONLY (No Main)"; status("CH "+(p.channel+1)+" "+ (p.operation==="SET_PROCESSING_FORMAT"?"M/ST ":"OUT ")+p.target+ " accepted · verifying native PCM"); - else { + } else { + if(el)el.value=t?.output||"Master"; status("CH "+(p.channel+1)+" "+ (p.operation==="SET_PROCESSING_FORMAT"?"M/ST":"OUT")+ " rejected · "+(ack?.error||"stale route")); @@ -1339,9 +1359,11 @@ el.value==="SOURCE ONLY (No Main)"?"NONE":null; // No optimistic GUI state. Both this menu and the WIRE jack use // the same ID/epoch-guarded, acknowledged native route transaction. - if(el.value!==t.output && !requestPrimaryOut(t,target)) + if(el.value!==t.output && !requestPrimaryOut(t,target)){ + el.value=t.output; status("OUT unavailable · verify device, MAIN route and pending edit"); - el.value=t.output; + } + // No instantaneous snap-back on a valid pending native transaction. return true; } // ONE realtime PCM control for original ten channels and MAIN, From 39f95c009a9b8bab95c1936ae0239ee94857d108 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:01:49 +0700 Subject: [PATCH 035/219] P0: correlate 5-second crackle evidence with Windows RAM pressure and process page faults off RT --- engine/diagnostics/CrackleEvidenceWindow.h | 46 ++++++++++++ src/Main.cpp | 84 ++++++++++++++++++++++ tests/crackle_evidence_window_test.cpp | 31 ++++++++ 3 files changed, 161 insertions(+) diff --git a/engine/diagnostics/CrackleEvidenceWindow.h b/engine/diagnostics/CrackleEvidenceWindow.h index e6d1b23b2..2d8941cc9 100644 --- a/engine/diagnostics/CrackleEvidenceWindow.h +++ b/engine/diagnostics/CrackleEvidenceWindow.h @@ -37,12 +37,26 @@ class CrackleEvidenceWindow final std::uint64_t count = 0; bool available = false; }; + // OS memory measurements are sampled ONLY by the message thread. + // "Page faults" includes soft/minor faults; NOT a hard-fault / disk + // paging counter and never proof of a missed hardware callback. + struct MemoryPressure + { + std::uint32_t systemLoadPercent = 0; + std::uint64_t availablePhysicalMiB = 0; + std::uint64_t processWorkingSetMiB = 0; + std::uint64_t processPrivateCommitMiB = 0; + std::uint64_t processPageFaults = 0; + bool systemAvailable = false; + bool processAvailable = false; + }; struct Sample { std::uint64_t atMs = 0; std::uint64_t deviceGeneration = 0; std::string routeScope; // stable backend, endpoints, mode and output gates std::array counters {}; + MemoryPressure memory {}; bool connected = false; }; struct Delta @@ -60,6 +74,10 @@ class CrackleEvidenceWindow final Reason reason = Reason::insufficientHistory; std::uint64_t elapsedMs = 0; std::array changes {}; + MemoryPressure memoryBefore {}, memoryAtMark {}; + std::uint32_t peakLoadPercent = 0; + bool loadComparable = false; + Delta processPageFaults {}; bool ready() const noexcept { return reason == Reason::ready; } }; @@ -129,6 +147,34 @@ class CrackleEvidenceWindow final } result.reason = Reason::ready; result.elapsedMs = now.atMs - baseline->atMs; + result.memoryBefore = baseline->memory; + result.memoryAtMark = now.memory; + // Pressure and page-fault samples share the exact same validated + // route/generation/time window as the audio timing counters. + if(baseline->memory.systemAvailable && now.memory.systemAvailable) + { + result.loadComparable = true; + result.peakLoadPercent = now.memory.systemLoadPercent; + for(std::size_t i=0; iatMs || + candidate.atMs > now.atMs)continue; + if(!candidate.memory.systemAvailable) { + result.loadComparable=false;break; + } + if(candidate.memory.systemLoadPercent>result.peakLoadPercent) + result.peakLoadPercent=candidate.memory.systemLoadPercent; + } + } + if(baseline->memory.processAvailable && + now.memory.processAvailable && + now.memory.processPageFaults >= baseline->memory.processPageFaults) + result.processPageFaults = { + now.memory.processPageFaults-baseline->memory.processPageFaults, + true + }; for (std::size_t i=0; icounters[i]; diff --git a/src/Main.cpp b/src/Main.cpp index b4e3e722e..136c8b06e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -19,6 +19,11 @@ #include "../engine/diagnostics/CrackleEvidenceWindow.h" #if defined(_WIN32) #include "../engine/device/WasapiCapabilityProbe.h" +#include +#include +#if defined(_MSC_VER) +#pragma comment(lib, "Psapi.lib") +#endif #endif #include "PluginCatalog.h" #include "PortableWorkspace.h" @@ -372,12 +377,45 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return {static_cast(amount), true}; } + // O(1) Windows OS counters at the existing 1 Hz AUDIO_HEALTH poll + // (and explicit Mark Crackle); never inside audioDeviceIOCallback. + // GlobalMemoryStatusEx load is whole-system RAM pressure, NOT process + // usage. PROCESS_MEMORY_COUNTERS_EX PageFaultCount includes SOFT faults; + // a Windows ETW hard-fault trace is needed to prove disk paging. + static armix::diagnostics::CrackleEvidenceWindow::MemoryPressure + readMemoryPressure() noexcept + { + using Memory = armix::diagnostics::CrackleEvidenceWindow::MemoryPressure; + Memory out; +#if defined(_WIN32) + MEMORYSTATUSEX system {}; + system.dwLength = sizeof(system); + if(::GlobalMemoryStatusEx(&system) != FALSE) + { + out.systemAvailable = true; + out.systemLoadPercent = system.dwMemoryLoad; + out.availablePhysicalMiB = system.ullAvailPhys/(1024ull*1024ull); + } + PROCESS_MEMORY_COUNTERS_EX process {}; + if(::GetProcessMemoryInfo(::GetCurrentProcess(), + reinterpret_cast(&process), + static_cast(sizeof(process))) != FALSE) + { + out.processAvailable = true; + out.processWorkingSetMiB = process.WorkingSetSize/(1024ull*1024ull); + out.processPrivateCommitMiB = process.PrivateUsage/(1024ull*1024ull); + out.processPageFaults = process.PageFaultCount; + } +#endif + return out; + } static armix::diagnostics::CrackleEvidenceWindow::Sample makeEvidenceSample ( const juce::var& state) { using Window = armix::diagnostics::CrackleEvidenceWindow; Window::Sample out; out.atMs = monotonicMilliseconds(); + out.memory = readMemoryPressure(); out.connected = bool(state.getProperty("connected", false)); const auto epoch = evidenceCounter(state.getProperty("deviceGeneration", {})); if (!epoch.available) out.connected = false; @@ -440,6 +478,34 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ? juce::String(static_cast(delta.value)) : juce::String("N/A"); } + const auto& before = window.memoryBefore; + const auto& marked = window.memoryAtMark; + report += " | SYSTEM_RAM_LOAD_BEFORE_PCT="; + report += window.ready() && before.systemAvailable + ? juce::String(before.systemLoadPercent):juce::String("N/A"); + report += " | SYSTEM_RAM_LOAD_AT_MARK_PCT="; + report += window.ready() && marked.systemAvailable + ? juce::String(marked.systemLoadPercent):juce::String("N/A"); + report += " | SYSTEM_RAM_LOAD_WINDOW_PEAK_PCT="; + report += window.loadComparable + ? juce::String(window.peakLoadPercent):juce::String("N/A"); + report += " | SYSTEM_AVAILABLE_PHYSICAL_MIB_AT_MARK="; + report += window.ready() && marked.systemAvailable + ? juce::String(static_cast(marked.availablePhysicalMiB)) + : juce::String("N/A"); + report += " | ARSONMIX_WORKING_SET_MIB_AT_MARK="; + report += window.ready() && marked.processAvailable + ? juce::String(static_cast(marked.processWorkingSetMiB)) + : juce::String("N/A"); + report += " | ARSONMIX_PRIVATE_COMMIT_MIB_AT_MARK="; + report += window.ready() && marked.processAvailable + ? juce::String(static_cast(marked.processPrivateCommitMiB)) + : juce::String("N/A"); + report += " | PROCESS_ALL_PAGE_FAULTS_SOFT_OR_HARD_DELTA="; + report += window.processPageFaults.comparable + ? juce::String(static_cast(window.processPageFaults.value)) + : juce::String("N/A"); + report += " | OS_HARD_PAGE_FAULTS=UNAVAILABLE_REQUIRES_ETW"; report += " | CORRELATION_ONLY_NOT_CAUSAL_PROOF"; return report; } @@ -1321,6 +1387,24 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr result << "Logical cores: " << juce::SystemStats::getNumCpus() << " | RAM: " << juce::SystemStats::getMemorySizeInMegabytes() << " MiB\n"; result << "Telemetry: true hardware render underruns UNAVAILABLE; callback time/gap are proxies only.\n"; + const auto memory=readMemoryPressure(); + result << "=== WINDOWS MEMORY PRESSURE (MESSAGE THREAD ONLY) ===\n"; + if(memory.systemAvailable) + result << "System RAM load: " << memory.systemLoadPercent + << "% | Physically available: " + << static_cast(memory.availablePhysicalMiB) + << " MiB\n"; + else result << "System RAM pressure: UNAVAILABLE\n"; + if(memory.processAvailable) + result << "ArSonMix resident working set: " + << static_cast(memory.processWorkingSetMiB) + << " MiB | Private commit: " + << static_cast(memory.processPrivateCommitMiB) + << " MiB | All process page faults (SOFT+HARD): " + << static_cast(memory.processPageFaults) << "\n"; + else result << "ArSonMix process counters: UNAVAILABLE\n"; + result << "70% is NOT an OS or ASIO glitch threshold. These are correlation" + " indicators, not disk hard-fault evidence or a fix for lost audio.\n"; result << "CALLBACK CADENCE: START-to-START estimates use PREVIOUS callback frame count; " "normal variable block sizes are not driver xruns. 1.5x/2.3x flags " "are scheduling heuristics only, not WASAPI/ASIO underrun evidence.\n"; diff --git a/tests/crackle_evidence_window_test.cpp b/tests/crackle_evidence_window_test.cpp index 90dffd479..710ff024b 100644 --- a/tests/crackle_evidence_window_test.cpp +++ b/tests/crackle_evidence_window_test.cpp @@ -38,6 +38,37 @@ int main() check(window.ready() && window.elapsedMs==4500); check(delta(window,E::Counter::renderedCallbacks).comparable); check(delta(window,E::Counter::renderedCallbacks).value==450); + // A known Windows RAM load at a marked glitch is contextual evidence, + // not a DSP change, physical xrun, or source of invented hard faults. + tracker.reset(); + auto memoryBase=sample(1000); + memoryBase.memory={71,2800,440,690,1000,true,true}; + tracker.push(memoryBase); + for(std::uint64_t ms=2000;ms<=4000;ms+=1000) { + auto point=sample(ms); + point.memory={static_cast(ms==3000?78:74), + 2100,460,710,1000+ms/10,true,true}; + tracker.push(point); + } + auto memoryMark=sample(5000); + memoryMark.memory={75,2200,490,740,1450,true,true}; + const auto pressure=tracker.mark(memoryMark); + check(pressure.ready() && pressure.loadComparable); + check(pressure.memoryBefore.systemLoadPercent==71); + check(pressure.memoryAtMark.systemLoadPercent==75); + check(pressure.peakLoadPercent==78); + check(pressure.processPageFaults.comparable); + check(pressure.processPageFaults.value==450); + auto memoryReset=sample(5000); + memoryReset.memory={76,2000,500,760,999,true,true}; + const auto afterReset=tracker.mark(memoryReset); + check(afterReset.ready()&&!afterReset.processPageFaults.comparable); + auto absent=sample(5000); + absent.memory.systemAvailable=false; + check(!tracker.mark(absent).loadComparable); + tracker.reset(); + for(std::uint64_t ms=1000;ms<=6000;ms+=1000) + tracker.push(sample(ms)); check(delta(window,E::Counter::overBudgetCallbacks).comparable); check(delta(window,E::Counter::overBudgetCallbacks).value==0); check(!delta(window,E::Counter::wasapiCaptureDiscontinuities).comparable); From 4b93c2cfab291fa2dbdd325f96446cb20d2cc41e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:03:23 +0700 Subject: [PATCH 036/219] P0: keep pre-glitch RAM pressure accessible in bounded diagnostic history --- src/Main.cpp | 41 ++++++++++++++++++++++++++++++++++++++--- 1 file changed, 38 insertions(+), 3 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 136c8b06e..b98847d26 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -459,10 +459,38 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return out; } - juce::String crackleWindowReport (const juce::var& status) const + static juce::String compactMemoryWindowReport ( + const armix::diagnostics::CrackleEvidenceWindow::Window& window) + { + const auto& before=window.memoryBefore; + const auto& at=window.memoryAtMark; + const auto fmt=[](std::uint64_t value,bool valid) { + return valid ? juce::String(static_cast(value)) + : juce::String("N/A"); + }; + juce::String result="RAM_LOAD_START_PCT="; + result+=fmt(before.systemLoadPercent,window.ready()&&before.systemAvailable); + result+=" | RAM_LOAD_MARK_PCT="; + result+=fmt(at.systemLoadPercent,window.ready()&&at.systemAvailable); + result+=" | RAM_LOAD_PREMARK_PEAK_PCT="; + result+=fmt(window.peakLoadPercent,window.loadComparable); + result+=" | FREE_PHYSICAL_MIB="; + result+=fmt(at.availablePhysicalMiB,window.ready()&&at.systemAvailable); + result+=" | PROCESS_WORKING_SET_MIB="; + result+=fmt(at.processWorkingSetMiB,window.ready()&&at.processAvailable); + result+=" | PROCESS_PRIVATE_COMMIT_MIB="; + result+=fmt(at.processPrivateCommitMiB,window.ready()&&at.processAvailable); + result+=" | ALL_PAGE_FAULTS_DELTA="; + result+=fmt(window.processPageFaults.value, + window.processPageFaults.comparable); + result+=" | HARD_FAULTS=UNAVAILABLE | NOT_CAUSAL_PROOF"; + return result; + } + + juce::String crackleWindowReport ( + const armix::diagnostics::CrackleEvidenceWindow::Window& window) const { using Window = armix::diagnostics::CrackleEvidenceWindow; - const auto window = crackleEvidence_.mark (makeEvidenceSample(status)); juce::String report = "PRE_MARK_EVIDENCE_5S="; report += Window::reasonName(window.reason); report += " | elapsedMs=" + juce::String(static_cast(window.elapsedMs)); @@ -2367,8 +2395,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else if (action == "diagnosticMark") { const auto status = engine_.status(); + const auto window=crackleEvidence_.mark(makeEvidenceSample(status)); diagnostics_.record ("AUDIO_GLITCH_MARK", juce::JSON::toString (status, false)); - diagnostics_.record ("AUDIO_GLITCH_WINDOW", crackleWindowReport (status)); + // The recent/important history intentionally caps each entry + // at 950 characters. Keep MEMORY as a separate compact event + // so a long XRun/cadence report never truncates RAM evidence. + diagnostics_.record ("AUDIO_GLITCH_MEMORY", + compactMemoryWindowReport(window)); + diagnostics_.record ("AUDIO_GLITCH_WINDOW", + crackleWindowReport(window)); emitNotice ("Crackle marker saved with source-labeled pre-mark evidence (up to 5 s)."); } else if (action == "backupStudio") From 1e5bd32a8ef395e4203798a7526c4808cba1b7b0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:04:33 +0700 Subject: [PATCH 037/219] P0: expose memory-aware Mark Crackle and Copy Audio Report in native More menu --- web/approved-native-bridge.js | 26 +++++++++++++++++++++++++- 1 file changed, 25 insertions(+), 1 deletion(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index c4a13dbf7..1f7d6c833 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1008,7 +1008,31 @@ backend.emitEvent("arMixAction",{action:"audioSetup"}); }); advanced.append(summary,driver); - menu.append(caption,setup,muteBtn,hardwareNote,advanced); + // First Sound P0: these are REAL JUCE diagnostic actions, not demo + // toggles. The marker snapshots the 5-second PRE-event counters and + // Windows RAM/process paging context from the existing 1 Hz control + // timer. No sampling or file I/O happens in the ASIO callback. + const healthTitle=item("span","more-tools-caption","AUDIO HEALTH"); + const mark=item("button","tool","Mark Crackle"); + mark.title="Capture 5s before an audible crackle, including Windows memory"; + mark.addEventListener("click",()=>{ + backend.emitEvent("arMixAction",{action:"diagnosticMark"}); + nativeToast("Audio glitch marked · pre-event counters and RAM saved"); + status("Crackle marker sent to JUCE diagnostics"); + }); + const report=item("button","tool","Copy Audio Report"); + report.title="Copy real JUCE timing / driver / memory evidence to clipboard"; + report.addEventListener("click",()=>{ + backend.emitEvent("arMixAction",{action:"copyDiagnosticReport"}); + status("Preparing JUCE audio diagnostic report on control thread"); + }); + backend.addEventListener("arMixDiagnosticReportCopied",ack=>{ + const bytes=Number(ack?.bytes); + if(Number.isFinite(bytes)&&bytes>0) + nativeToast("Audio report copied · paste into engineering chat"); + }); + menu.append(caption,setup,muteBtn,hardwareNote, + healthTitle,mark,report,advanced); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. const toolbar=document.querySelector(".command-bar"); From 1f805bc0421a178ba4b6bc77740114d808b4aa7b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:07:06 +0700 Subject: [PATCH 038/219] P0: validate memory-aware crackle marker without brittle C++ whitespace contract --- tests/p0_diagnostic_contract_test.mjs | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/tests/p0_diagnostic_contract_test.mjs b/tests/p0_diagnostic_contract_test.mjs index 53aa9db6c..3cb8a11a9 100644 --- a/tests/p0_diagnostic_contract_test.mjs +++ b/tests/p0_diagnostic_contract_test.mjs @@ -56,7 +56,13 @@ test('P0 crackle marker records a bounded pre-event source-labeled evidence wind assert.match(host,/timerTicks_ % 12 == 0 && !browser_\.loaded/); assert.match(host,/crackleEvidence_\.push \(makeEvidenceSample \(health\)\)/); assert.doesNotMatch(host,/approvedNativeSnapshot \(health\)/); - assert.match(host,/crackleEvidence_\.mark \(makeEvidenceSample\(status\)\)/); + assert.match(host,/crackleEvidence_\\.mark\\s*\\(\\s*makeEvidenceSample\\(status\\)\\s*\\)/); + assert.match(host,/AUDIO_GLITCH_MEMORY/); + assert.match(host,/compactMemoryWindowReport/); + assert.match(host,/GlobalMemoryStatusEx/); + assert.match(host,/GetProcessMemoryInfo/); + assert.match(evidence,/struct MemoryPressure/); + assert.match(evidence,/peakLoadPercent/); assert.match(host,/if \(timerTicks_ % 12 == 0\)/); assert.match(build,/P0PreMarkerFiveSecondEvidenceWindow/); assert.doesNotMatch(engine,/CrackleEvidenceWindow/); From 7e14ddd0532ee7e9e916f4f54c000eb560367132 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:09:31 +0700 Subject: [PATCH 039/219] P0: fix exact diagnostic marker regression regex escaping --- tests/p0_diagnostic_contract_test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/p0_diagnostic_contract_test.mjs b/tests/p0_diagnostic_contract_test.mjs index 3cb8a11a9..9813362a5 100644 --- a/tests/p0_diagnostic_contract_test.mjs +++ b/tests/p0_diagnostic_contract_test.mjs @@ -56,7 +56,7 @@ test('P0 crackle marker records a bounded pre-event source-labeled evidence wind assert.match(host,/timerTicks_ % 12 == 0 && !browser_\.loaded/); assert.match(host,/crackleEvidence_\.push \(makeEvidenceSample \(health\)\)/); assert.doesNotMatch(host,/approvedNativeSnapshot \(health\)/); - assert.match(host,/crackleEvidence_\\.mark\\s*\\(\\s*makeEvidenceSample\\(status\\)\\s*\\)/); + assert.match(host,/crackleEvidence_\.mark\s*\(\s*makeEvidenceSample\(status\)\s*\)/); assert.match(host,/AUDIO_GLITCH_MEMORY/); assert.match(host,/compactMemoryWindowReport/); assert.match(host,/GlobalMemoryStatusEx/); From dd46a85f6e1eb177367e04f05b949c216bbd5df8 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:21:22 +0700 Subject: [PATCH 040/219] P0: keep native audio live during VST3 preparation; mute only at successful graph publication --- src/LiveAudioEngine.h | 40 +++++++++++++++++----- src/LiveDryRoutingLab.h | 18 +++++++--- tests/approved_native_m2_contract.test.cjs | 13 +++++++ 3 files changed, 59 insertions(+), 12 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index a621c8718..dc98ddba8 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1137,14 +1137,17 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback error="NATIVE TOPOLOGY: preparation failed: "+juce::String(ex.what()); } catch(...) { error="NATIVE TOPOLOGY: preparation failed"; } - // This is a physical renderer admission, not an extra browser mixer, - // new DSP graph or auto-arm. It must complete before output resumes. + return finishGuardedDryTopology( + expectedEpoch,frames,wasMonitoring,std::move(error)); + } + // One post-publication authority handoff/restoration policy for all + // structural controls. Never confuse muted hardware with detached DSP. + juce::String finishGuardedDryTopology(std::uint64_t expectedEpoch, + int frames,bool wasMonitoring,juce::String error) { if(error.isEmpty() && expectedEpoch==dryRoutingLab_.epoch() && dryRoutingLab_.hasExplicitRoute()) (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( graphOwned_->count,frames,true,currentOriginalCh1Lease()); - // A failed edit may restore the PREVIOUS valid audible route; device - // or graph faults, an unpatched last source, or STREAM never auto-arm. const bool sameEpoch=expectedEpoch==dryRoutingLab_.epoch(); if(wasMonitoring && sameEpoch && armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( @@ -1241,12 +1244,33 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback !pluginFormat->fileMightContainThisPluginType(chosen.path)) return "FX INSERT: VST3 bundle unavailable or invalid; rescan catalog"; const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - return applyGuardedDryTopology(epoch,frames,[&] { - return dryRoutingLab_.insertCatalogFx(lane,slot,epoch,revision, + // The previous audio path keeps sounding while JUCE examines the + // VST3 bundle, instantiates the new effect and prepares its buffers. + // A rejected/missing/latent plugin must NOT briefly mute a singer. + // The pre-publish hook is CONTROL-only; it runs AFTER successful + // fallible preparation and BEFORE switching graph authority. + const bool wasMonitoring=isMonitorEnabled(); + bool enteredPublication=false; + juce::String error; + try { + error=dryRoutingLab_.insertCatalogFx(lane,slot,epoch,revision, chosen,directFence_.permitted(),independent_.active(), graphOwned_->count,formats_,device->getCurrentSampleRate(), - frames); - }); + frames,[&] { + enteredPublication=true; + if(wasMonitoring)setOutputMuted(true); + }); + } catch(const std::exception& ex) { + error="FX INSERT: prepare failed; previous audio preserved: "+ + juce::String(ex.what()); + } catch(...) { + error="FX INSERT: prepare failed; previous audio preserved"; + } + // No graph publication, no change of output state and no + // unnecessary ChannelId re-admission on any preparation failure. + if(!enteredPublication)return error; + return finishGuardedDryTopology( + epoch,frames,wasMonitoring,std::move(error)); } bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index a5d67d6af..a06ebb656 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -20,6 +20,7 @@ #include #include #include +#include #include #include #include @@ -175,7 +176,8 @@ class LiveDryRoutingLab final { const FxSelections& selections, juce::AudioPluginFormatManager& formats, double sampleRate,int deviceFrames,bool explicitSelection=true, - const FxRestores* restores=nullptr) { + const FxRestores* restores=nullptr, + const std::function& beforePublish={}) { // E5: the M4 compiler cannot encode an admitted native GROUP/FX RETURN. // An M4 APPLY, Show recall or structural SOURCE/AUX edit must not // erase native BUS PCM while its ChannelId graph owns the callback. @@ -419,8 +421,14 @@ class LiveDryRoutingLab final { if(!registryValid_.load(std::memory_order_acquire) || epochAtPublish!=currentEpoch) return "Audio device changed before routing publication"; + // The old accepted graph continues to render while a new vendor + // instance is scanned, constructed and prepared on CONTROL. Only + // after ALL fallible preparation and the last device-epoch check + // may the caller briefly close the physical output at commit. + // Never call the gate on a failed plugin admission. + if(beforePublish)beforePublish(); // New M4 routing must not render against an older ChannelId graph. - // Output must remain disarmed throughout structural native APPLY. + // The output must be disarmed by the caller at the publication edge. const auto previousPcmEpoch=channelIdPcmEpoch_.exchange( 0,std::memory_order_acq_rel); const auto result=publisher_.publish(std::move(next),expectedRevision,epochAtPublish); @@ -510,7 +518,8 @@ class LiveDryRoutingLab final { const FxSelection& chosen,bool directPermitted, bool independentClock,int occupiedCh1Fx, juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) { + int deviceFrames, + const std::function& beforePublish={}) { const auto preflight=fxInsertPreflight( lane,slot,expectedEpoch,expectedRevision,chosen); if(preflight.isNotEmpty())return preflight; @@ -521,7 +530,8 @@ class LiveDryRoutingLab final { auto next=acceptedFxSelections_; next[lane][slot]=chosen; return apply(command,directPermitted,independentClock,occupiedCh1Fx, - next,formats,sampleRate,deviceFrames,true); + next,formats,sampleRate,deviceFrames,true,nullptr, + beforePublish); } // M1 direct-source parameter: only same-format physical→physical diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 3c690f233..8b92bca10 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -232,6 +232,19 @@ test("P0 real slot VST3 power and native editor use verified instance tokens",() assert.match(main,/action == "routingFxEditor"/); assert.match(main,/action == "routingFxBypass"/); }); +test("P0 VST3 preparation runs with old live PCM; monitor closes only at publication",()=>{ + const lab=read("src/LiveDryRoutingLab.h"); + const engine=read("src/LiveAudioEngine.h"); + assert.match(lab,/#include /); + assert.match(lab,/if\(beforePublish\)beforePublish\(\)/); + assert.match(lab,/const auto epochAtPublish=deviceEpoch_\.load/); + assert.match(lab,/next,formats,sampleRate,deviceFrames,true,nullptr,\s*beforePublish/); + assert.match(engine,/bool enteredPublication=false/); + assert.match(engine,/enteredPublication=true;\s*if\(wasMonitoring\)setOutputMuted\(true\)/); + assert.match(engine,/if\(!enteredPublication\)return error/); + assert.match(engine,/return finishGuardedDryTopology\(/); + assert.match(engine,/The previous audio path keeps sounding while JUCE examines/); +}); test("P0 FX command preflight never mutes monitoring for deterministic rejection",()=>{ const lab=read("src/LiveDryRoutingLab.h"); const engine=read("src/LiveAudioEngine.h"); From 5904993a3572542d0436eb2966dd14eb4612b8ed Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:23:34 +0700 Subject: [PATCH 041/219] P0: connect SOURCE ONLY / MAIN WIRE removal to verified M4 fallback when ChannelId not admitted --- scripts/build_approved_native_gui.py | 1 + tests/approved_native_m2_contract.test.cjs | 12 ++++++++++++ web/approved-native-bridge.js | 18 ++++++++++++++++-- 3 files changed, 29 insertions(+), 2 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 4c7a938ad..da67afee6 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -174,6 +174,7 @@ def accepted_pages_html() -> str: ("restorePluginPreferences();init();\n})();", "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" + " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" " make,render,findTrack,displayMeterDbfs,\n" " refreshStrip,syncFaderVisual,openFastPicker,openPluginBrowser,\n" " get activeFaderId(){return faderGesture?Number(faderGesture.input.closest('.strip')?.dataset.id):-1;},\n" diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 8b92bca10..5e6d1a7a6 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -254,6 +254,18 @@ test("P0 FX command preflight never mutes monitoring for deterministic rejection assert.match(engine,/pluginFormat->fileMightContainThisPluginType\(chosen\.path\)/); assert.match(engine,/FX INSERT: VST3 bundle unavailable or invalid/); }); +test("P0 native WIRE MAIN disconnect requires exact accepted EdgeId or verified M4 route",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const bundle=read("scripts/build_approved_native_gui.py"); + assert.match(bridge,/const edgeId=wireByUiId\.get\(op\.edgeId\)/); + assert.match(bridge,/const graphMainRemove=op\.type==="REMOVE"/); + assert.match(bridge,/const m4MainRemove=op\.type==="REMOVE"/); + assert.match(bridge,/current\?\.admitted!==true/); + assert.match(bridge,/legacy\(\)\?\.channels\?\.\[lane\]\?\.main===true/); + assert.match(bridge,/e\.id===op\.edgeId&&e\.sourceId===op\.sourceId/); + assert.match(bridge,/e\.destId===scope\?\.master\?\.id/); + assert.match(bundle,/get wireEdges\(\)\{return wireEdges;\}/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 1f7d6c833..d1bfc8f8c 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1560,11 +1560,25 @@ // uiByWireId is the inverse. The old inverse lookup always returned // undefined, so unplugging an existing MAIN wire was impossible. const edgeId=wireByUiId.get(op.edgeId); - const isMainRemove=op.type==="REMOVE" && sourceId && + const lane=m4Index(t); + const graphMainRemove=op.type==="REMOVE" && sourceId && current?.admitted===true && current.graph.edges.some(e=>e.enabled&&e.edgeId===edgeId&& e.from===sourceId&&e.to===current.graph.mainChannelId); - if(t&&m4Index(t)>=0&&(isMainConnect||isMainRemove)){ + // The approved M4 renderer remains the accepted First Sound owner + // if ChannelId projection was not admitted. Verify BOTH an exact UI + // PRIMARY edge and the producer's real MAIN readback before removing. + // When native ChannelId *is* admitted, never replace its edge-token + // guard with an M4 label. No invented browser-only PCM or routing. + const m4MainRemove=op.type==="REMOVE" && current?.admitted!==true && + lane>=0 && m4Verified() && + legacy()?.channels?.[lane]?.main===true && + Array.isArray(scope?.wireEdges) && + scope.wireEdges.some(e=>e.enabled&&e.kind==="primary"&& + e.id===op.edgeId&&e.sourceId===op.sourceId&& + e.destId===scope?.master?.id); + const isMainRemove=graphMainRemove||m4MainRemove; + if(t&&lane>=0&&(isMainConnect||isMainRemove)){ const target=isMainRemove?"NONE":"MAIN"; if(requestPrimaryOut(t,target)) status("CH "+(m4Index(t)+1)+" WIRE → "+ From 2e4a02ce730b188b3ed6a3929a754ef78f3d4fb1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 03:27:44 +0700 Subject: [PATCH 042/219] P0: reconcile visible WIRE MAIN cables with actual accepted M4 routing readback --- scripts/build_approved_native_gui.py | 28 ++++++++++++++++++++++ tests/approved_native_m2_contract.test.cjs | 13 ++++++++++ web/approved-native-bridge.js | 6 +++++ 3 files changed, 47 insertions(+) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index da67afee6..c20c167bc 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -172,9 +172,37 @@ def accepted_pages_html() -> str: # Native WebView2 only: expose the original Pages IIFE model to the thin # bridge. No second renderer/state reducer, no change to public /preview/. ("restorePluginPreferences();init();\n})();", + "let verifiedM4WireSignature='',verifiedM4WireDirty=false;\n" "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" + " syncVerifiedM4Wires(rows,ids){\n" + " if(!Array.isArray(rows)||rows.length!==10||!Array.isArray(ids)||ids.length!==10)\n" + " return false;\n" + " const tracksById=new Map(tracks.filter(t=>t.kind==='audio').map(t=>[t.id,t]));\n" + " if(new Set(ids).size!==10||ids.some(id=>!tracksById.has(id))||\n" + " rows.some(r=>!r||typeof r.main!=='boolean'))return false;\n" + " const next=[];\n" + " for(let i=0;i<10;i++)if(rows[i].main){\n" + " const prior=wireEdges.find(e=>e.enabled&&e.kind==='primary'&&\n" + " e.sourceId===ids[i]&&e.destId===master.id);\n" + " next.push(prior||{id:nextWireId++,sourceId:ids[i],destId:master.id,\n" + " kind:'primary',mode:'postFader',enabled:true,levelDb:0});\n" + " }\n" + " const sig=rows.map((r,i)=>r.main?String(ids[i]):'').join('|');\n" + " if(sig!==verifiedM4WireSignature || wireEdges.length!==next.length ||\n" + " next.some((e,i)=>wireEdges[i]!==e)){\n" + " wireEdges=next;verifiedM4WireSignature=sig;verifiedM4WireDirty=true;\n" + " if(selectedWireEdgeId!==null&&!wireEdges.some(e=>e.id===selectedWireEdgeId))\n" + " selectedWireEdgeId=null;\n" + " syncWireOutputProjection();\n" + " }\n" + " if(verifiedM4WireDirty&&!wireGesture&&!faderGesture&&\n" + " !document.activeElement?.matches?.('.strip select')){\n" + " verifiedM4WireDirty=false;refreshWireRoutingNodes();\n" + " }\n" + " return true;\n" + " },\n" " make,render,findTrack,displayMeterDbfs,\n" " refreshStrip,syncFaderVisual,openFastPicker,openPluginBrowser,\n" " get activeFaderId(){return faderGesture?Number(faderGesture.input.closest('.strip')?.dataset.id):-1;},\n" diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 5e6d1a7a6..cf873de1f 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -266,6 +266,19 @@ test("P0 native WIRE MAIN disconnect requires exact accepted EdgeId or verified assert.match(bridge,/e\.destId===scope\?\.master\?\.id/); assert.match(bundle,/get wireEdges\(\)\{return wireEdges;\}/); }); +test("P0 native-only WIRE cables reflect actual M4 MAIN readback, not demo ghosts",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const bundle=read("scripts/build_approved_native_gui.py"); + assert.match(bridge,/if\(!next\?\.admitted && m4Verified\(\)\)/); + assert.match(bridge,/scope\?\.syncVerifiedM4Wires\?\.\(legacy\(\)\?\.channels,m4TrackIds\)/); + assert.match(bundle,/syncVerifiedM4Wires\(rows,ids\)/); + assert.match(bundle,/typeof r\.main!=='boolean'/); + assert.match(bundle,/if\(rows\[i\]\.main\)/); + assert.match(bundle,/nextWireId\+\+/); + assert.match(bundle,/verifiedM4WireDirty/); + assert.match(bundle,/refreshWireRoutingNodes\(\)/); + assert.match(bundle,/!wireGesture&&!faderGesture/); +}); test("P0 same-VB-Cable feedback is blocked before native MAIN arm",()=>{ const engine=read("src/LiveAudioEngine.h"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index d1bfc8f8c..5d6e9cfb4 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1091,6 +1091,12 @@ function onNativeReadback(next) { updateHardwarePanel(next); paintM4Fallback(next); + // When ChannelId graph is not yet admitted, the REAL 10CH M4 + // channel.main readback is authoritative for visible CH→MAIN cables. + // Project only its verified PRIMARY edges, never the initial Pages demo + // BUS/sends or an assumed always-on MAIN wire. No PCM graph mutation. + if(!next?.admitted && m4Verified()) + scope?.syncVerifiedM4Wires?.(legacy()?.channels,m4TrackIds); // A second channel's IN can be selected while the first transaction is // in flight. Always dispatch its latest choice with a FRESH native route // revision, not stale tokens captured before the previous ACK. From 93145d6a14c47ba3725885ab05f9a92a3f9f34d5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 04:10:06 +0700 Subject: [PATCH 043/219] P0: unify late-publication gate for SOURCE, OUT, M-ST and VST3 structural edits --- src/LiveAudioEngine.h | 75 ++++++++++------------ src/LiveDryRoutingLab.h | 16 +++-- tests/approved_native_m2_contract.test.cjs | 14 +++- 3 files changed, 56 insertions(+), 49 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index dc98ddba8..3e4fdb594 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1117,26 +1117,33 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback setOutputMuted(true); // never expose CH1 unexpectedly on STOP dryRoutingLab_.disable(); } - // Structural source/OUT changes recompile ONE existing native PCM - // publisher. Suspend physical monitoring internally (never ask the user - // to click MUTE/ARM), perform the edit, then re-admit the ChannelId graph - // while disarmed. If admission rejects, the accepted M4 renderer remains - // the only safe fallback in this SAME JUCE callback. - // All control-thread only. A running STREAM forbids structural edits; - // it must never consume a half-switched main graph. + // One structural graph transaction for SOURCE, OUT, M/ST and FX inserts: + // keep the last accepted PCM audible while the CONTROL thread validates, + // clones, and prepares the candidate. Disarm MAIN only at the atomic + // publication boundary, then re-admit ChannelId before restoring it. + // Rejected preparation must never cause a hardware mute or a fake GUI ACK. + // STREAM forbids structural editing and fast scalar controls stay atomic. template juce::String applyGuardedDryTopology(std::uint64_t expectedEpoch, int frames,Edit&& edit) { if(secondaryOutput_.armed()) return "STOP STREAM before a structural INPUT/OUT change"; const bool wasMonitoring=isMonitorEnabled(); - if(wasMonitoring)setOutputMuted(true); + bool enteredPublication=false; juce::String error; - try { error=edit(); } + try { + error=edit([&] { + enteredPublication=true; + if(wasMonitoring)setOutputMuted(true); + }); + } catch(const std::exception& ex) { error="NATIVE TOPOLOGY: preparation failed: "+juce::String(ex.what()); } catch(...) { error="NATIVE TOPOLOGY: preparation failed"; } + // A syntactically valid request can still reject before publication: + // retain the previous monitor, graph and ChannelId authority. + if(!enteredPublication)return error; return finishGuardedDryTopology( expectedEpoch,frames,wasMonitoring,std::move(error)); } @@ -1173,16 +1180,20 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!armix::mixer::NativeTopologyEditSafety::mayEdit( structural,secondaryOutput_.armed())) return "SOURCE: STOP STREAM before changing source format"; - const auto edit=[&]{ + // Existing same-format physical pin changes remain live, atomic + // and 64-sample crossfaded; no unnecessary mute or recompile. + if(!structural) return dryRoutingLab_.repatchPhysicalSource( strip,epoch,revision,mode,left,right, directFence_.permitted(),independent_.active(), graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); - }; - // Existing same-format physical pin changes remain live, atomic - // and 64-sample crossfaded; no unnecessary mute or recompile. - if(!structural)return edit(); - return applyGuardedDryTopology(epoch,frames,edit); + return applyGuardedDryTopology(epoch,frames,[&](const auto& beforePublish){ + return dryRoutingLab_.repatchPhysicalSource( + strip,epoch,revision,mode,left,right, + directFence_.permitted(),independent_.active(), + graphOwned_->count,formats_,device->getCurrentSampleRate(), + frames,beforePublish); + }); } catch(const std::exception& ex) { return "SOURCE: native prepare failed; prior audio kept: " + juce::String(ex.what()); } catch(...) { @@ -1206,11 +1217,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(!device)return "CHANNEL PATCH: no active native audio interface"; try { const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - return applyGuardedDryTopology(epoch,frames,[&] { + return applyGuardedDryTopology(epoch,frames,[&](const auto& beforePublish) { return dryRoutingLab_.repatchChannelStructure( strip,epoch,revision,operation,value, directFence_.permitted(),independent_.active(), - graphOwned_->count,formats_,device->getCurrentSampleRate(),frames); + graphOwned_->count,formats_,device->getCurrentSampleRate(), + frames,beforePublish); }); } catch(...) { return "CHANNEL PATCH: native preparation failed; previous mix preserved"; @@ -1244,33 +1256,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback !pluginFormat->fileMightContainThisPluginType(chosen.path)) return "FX INSERT: VST3 bundle unavailable or invalid; rescan catalog"; const auto frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); - // The previous audio path keeps sounding while JUCE examines the - // VST3 bundle, instantiates the new effect and prepares its buffers. - // A rejected/missing/latent plugin must NOT briefly mute a singer. - // The pre-publish hook is CONTROL-only; it runs AFTER successful - // fallible preparation and BEFORE switching graph authority. - const bool wasMonitoring=isMonitorEnabled(); - bool enteredPublication=false; - juce::String error; - try { - error=dryRoutingLab_.insertCatalogFx(lane,slot,epoch,revision, + return applyGuardedDryTopology(epoch,frames,[&](const auto& beforePublish) { + return dryRoutingLab_.insertCatalogFx(lane,slot,epoch,revision, chosen,directFence_.permitted(),independent_.active(), graphOwned_->count,formats_,device->getCurrentSampleRate(), - frames,[&] { - enteredPublication=true; - if(wasMonitoring)setOutputMuted(true); - }); - } catch(const std::exception& ex) { - error="FX INSERT: prepare failed; previous audio preserved: "+ - juce::String(ex.what()); - } catch(...) { - error="FX INSERT: prepare failed; previous audio preserved"; - } - // No graph publication, no change of output state and no - // unnecessary ChannelId re-admission on any preparation failure. - if(!enteredPublication)return error; - return finishGuardedDryTopology( - epoch,frames,wasMonitoring,std::move(error)); + frames,beforePublish); + }); } bool setDryRoutingLabParameter(int strip,std::uint64_t epoch, std::uint64_t revision,const juce::String& parameter, diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index a06ebb656..2daeda5f3 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -625,7 +625,8 @@ class LiveDryRoutingLab final { int physicalLeft,int physicalRight,bool directPermitted, bool independentClock,int occupiedCh1Fx, juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) + int deviceFrames, + const std::function& beforePublish={}) { if(!ready() || !registryValid_.load(std::memory_order_acquire) || topologyFault_.load(std::memory_order_acquire) || @@ -656,7 +657,7 @@ class LiveDryRoutingLab final { if(error.isNotEmpty())return error; return publishRevisedTopology(staged,expectedEpoch,expectedRevision, directPermitted,independentClock,occupiedCh1Fx,formats, - sampleRate,deviceFrames); + sampleRate,deviceFrames,beforePublish); } // One-click channel OUT and format: the existing native M4 routing/FX @@ -668,7 +669,8 @@ class LiveDryRoutingLab final { const juce::String& operation,const juce::String& requested, bool directPermitted,bool independentClock,int occupiedCh1Fx, juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) { + int deviceFrames, + const std::function& beforePublish={}) { if(!ready()||!registryValid_.load(std::memory_order_acquire)|| topologyFault_.load(std::memory_order_acquire)|| epoch()!=expectedEpoch||revision()!=expectedRevision|| @@ -700,7 +702,7 @@ class LiveDryRoutingLab final { } else return "CHANNEL PATCH: unsupported graph operation"; return publishRevisedTopology(staged,expectedEpoch,expectedRevision, directPermitted,independentClock,occupiedCh1Fx,formats, - sampleRate,deviceFrames); + sampleRate,deviceFrames,beforePublish); } // Operator one-action AUX send connection: prepare a real parallel @@ -795,7 +797,8 @@ class LiveDryRoutingLab final { std::uint64_t expectedEpoch,std::uint64_t expectedRevision, bool directPermitted,bool independentClock,int occupiedCh1Fx, juce::AudioPluginFormatManager& formats,double sampleRate, - int deviceFrames) { + int deviceFrames, + const std::function& beforePublish={}) { auto stagedRows=staged.getProperty("channels",juce::var()); auto* editable=stagedRows.getArray(); if(!editable||editable->size()!=count) @@ -836,7 +839,8 @@ class LiveDryRoutingLab final { !registryValid_.load(std::memory_order_acquire)) return "CHANNEL PATCH: device changed; previous mix preserved"; return apply(staged,directPermitted,independentClock,occupiedCh1Fx, - acceptedFxSelections_,formats,sampleRate,deviceFrames,true); + acceptedFxSelections_,formats,sampleRate,deviceFrames,true, + nullptr,beforePublish); } // Native live control path. Only the JUCE message thread writes. No diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index cf873de1f..07ceea93f 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -243,7 +243,19 @@ test("P0 VST3 preparation runs with old live PCM; monitor closes only at publica assert.match(engine,/enteredPublication=true;\s*if\(wasMonitoring\)setOutputMuted\(true\)/); assert.match(engine,/if\(!enteredPublication\)return error/); assert.match(engine,/return finishGuardedDryTopology\(/); - assert.match(engine,/The previous audio path keeps sounding while JUCE examines/); + assert.match(engine,/return applyGuardedDryTopology\(epoch,frames,\[&\]\(const auto& beforePublish\)/); +}); +test("P0 SOURCE, OUT, M-ST and FX share late-gated graph publication",()=>{ + const lab=read("src/LiveDryRoutingLab.h"); + const engine=read("src/LiveAudioEngine.h"); + // Format/input edits and native VST3 insert must all enter the same gate. + assert.match(lab,/juce::String repatchPhysicalSource[\s\S]*?int deviceFrames,\s*const std::function& beforePublish/); + assert.match(lab,/juce::String repatchChannelStructure[\s\S]*?int deviceFrames,\s*const std::function& beforePublish/); + assert.match(lab,/juce::String publishRevisedTopology[\s\S]*?int deviceFrames,\s*const std::function& beforePublish/); + assert.match(lab,/acceptedFxSelections_,formats,sampleRate,deviceFrames,true,\s*nullptr,beforePublish/); + assert.match(engine,/if\(!structural\)\s*return dryRoutingLab_\.repatchPhysicalSource/); + assert.match(engine,/return applyGuardedDryTopology\(epoch,frames,\[&\]\(const auto& beforePublish\)/); + assert.match(engine,/frames,beforePublish\);/); }); test("P0 FX command preflight never mutes monitoring for deterministic rejection",()=>{ const lab=read("src/LiveDryRoutingLab.h"); From c9261fc98b703b0062abca20e5832309cf116fc5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 04:13:26 +0700 Subject: [PATCH 044/219] P0: surface real JUCE VST3 and routing errors using notice.text protocol --- tests/approved_native_m2_contract.test.cjs | 10 ++++++++++ web/approved-native-bridge.js | 10 +++++++--- 2 files changed, 17 insertions(+), 3 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 07ceea93f..8569c99c6 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -266,6 +266,16 @@ test("P0 FX command preflight never mutes monitoring for deterministic rejection assert.match(engine,/pluginFormat->fileMightContainThisPluginType\(chosen\.path\)/); assert.match(engine,/FX INSERT: VST3 bundle unavailable or invalid/); }); +test("P0 JUCE native errors use the actual notice.text event contract",()=>{ + const host=read("src/Main.cpp"); + const bridge=read("web/approved-native-bridge.js"); + assert.match(host,/o->setProperty \("text", message\)/); + assert.match(host,/o->setProperty \("error", error\)/); + assert.match(bridge,/backend\.addEventListener\("arMixNotice",notice=>/); + assert.match(bridge,/const message=notice\?\.text/); + assert.match(bridge,/nativeToast\(message\)/); + assert.doesNotMatch(bridge,/notice\.message/); +}); test("P0 native WIRE MAIN disconnect requires exact accepted EdgeId or verified M4 route",()=>{ const bridge=read("web/approved-native-bridge.js"); const bundle=read("scripts/build_approved_native_gui.py"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 5d6e9cfb4..d8814b0d9 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1300,9 +1300,13 @@ "Native VST3 scan finished; results from JUCE catalog"; }); backend.addEventListener("arMixNotice",notice=>{ - if(notice?.error===true && typeof notice.message==="string"){ - nativeToast(notice.message); // native VST3/driver cause survives 12Hz status repaint - status("JUCE · "+notice.message); + // ConsoleWindow::emitNotice publishes {text,error}, never {message}. + // The mismatched field hid native VST3 layout/latency, driver and + // routing failures behind rapid meter/readback status updates. + const message=notice?.text; + if(notice?.error===true && typeof message==="string" && message.length){ + nativeToast(message); // physical FX/driver failures remain visible + status("JUCE · "+message); } }); backend.addEventListener("arMixAudioArmAck", ack=>{ From 1768cc2aa8135c15ecedd9db5a45b3b9de190ef7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 05:44:07 +0700 Subject: [PATCH 045/219] Milestone A CI: align native authority regressions and fixture with SessionSnapshot Replace obsolete pre-cutover M4 wire assertion, retain native input timeout policy, and inject a real producer-shaped ChannelId SessionSnapshot in deterministic WebView contract tests. --- tests/approved_native_m2_contract.test.cjs | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 8593e9961..38cfdeeab 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -295,7 +295,7 @@ test("P0 native WIRE MAIN disconnect requires exact accepted EdgeId or verified test("P0 native-only WIRE cables reflect actual M4 MAIN readback, not demo ghosts",()=>{ const bridge=read("web/approved-native-bridge.js"); const bundle=read("scripts/build_approved_native_gui.py"); - assert.match(bridge,/if\(!next\?\.admitted && m4Verified\(\)\)/); + assert.match(bridge,/if\(session\.authority==="M4" && m4Verified\(\)\)/); assert.match(bridge,/scope\?\.syncVerifiedM4Wires\?\.\(legacy\(\)\?\.channels,m4TrackIds\)/); assert.match(bundle,/syncVerifiedM4Wires\(rows,ids\)/); assert.match(bundle,/typeof r\.main!=='boolean'/); @@ -327,7 +327,7 @@ test("single /preview/ GUI: channel IN, actual OUT and correlated device safety assert.match(builder,/public = destination \/ "preview"/); assert.match(bridge,/source:"\/preview\/ approved compiled Pages GUI"/); assert.match(bridge,/field==="input"/); - assert.match(bridge,/nativeUiSourcePending=null;[\s\S]*?response timed out/); + assert.match(bridge,/nativeUiSourcePending=null;[\s\S]*?INPUT timeout/); assert.match(bridge,/row\?\.main===true/); assert.match(bridge,/pendingDeviceMute=\{requestId,epoch:String\(hardware\.device\.epoch\)\}/); assert.match(bridge,/ack\?\.requestId!==pendingDeviceMute\.requestId/); @@ -583,6 +583,13 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a assert.equal(sent[1].name,"arMixConsoleSubscribe"); assert.equal(window.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,false); const accepted=acceptedFixture(); + // The native callback, not this browser fixture, selects ChannelId PCM. + accepted.mixerSession={ + authority:"CHANNEL_ID",deviceEpoch:accepted.device.epoch, + routeRevision:accepted.graph.revision, + rosterRevision:accepted.graph.rosterRevision, + channels:accepted.graph.channels,main:{db:0,mute:false} + }; listeners.get("arMixConsoleSnapshot")(accepted); assert.equal(window.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); assert.equal(scope.tracks.length,1); From cd4551efba704d9c96abc55c44d712447007f75b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 06:17:06 +0700 Subject: [PATCH 046/219] Milestone A staging: adapt reviewed native FX rack gate from #421 to #418 Retain single production JUCE PCM engine and approved GUI. This unattached staging commit adds native rack overrides, real ChannelId lease readback, M4 callback bypass and host CSS semantics. Follow-up integration commit wires the existing #418 operator protocol and single mixerSession before publishing branch. --- .github/workflows/ui-smoke.yml | 2 + engine/core/DynamicChannelFxLeaseBank.h | 30 ++++++- engine/core/LiveChannelFxGraph.h | 26 +++++- .../core/UnifiedLegacyProductionAdmission.h | 6 ++ scripts/approved_fx_rack_power.py | 32 +++++++ scripts/build_pages.py | 2 + src/ApprovedNativeV8Projection.h | 5 ++ src/ConsoleLiveBridgeV6.h | 2 + src/LiveAudioEngine.h | 26 +++++- src/LiveDryRoutingLab.h | 26 ++++++ src/Main.cpp | 72 ++++++++++++++- tests/approved_fx_rack_master_power_smoke.py | 89 +++++++++++++++++++ tests/live_channel_fx_graph_test.cpp | 38 ++++++++ tests/live_graph_contract_test.mjs | 5 +- ...ingle_preview_publication_contract_test.py | 2 + 15 files changed, 355 insertions(+), 8 deletions(-) create mode 100644 scripts/approved_fx_rack_power.py create mode 100644 tests/approved_fx_rack_master_power_smoke.py diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index ffc92c72b..d2d777d94 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -168,6 +168,8 @@ jobs: run: python tests/approved_stage_c_css_visual_parity_smoke.py - name: Check real mobile /preview/ touch toolbar, popup and stray chevrons run: python tests/approved_preview_mobile_navigation_smoke.py + - name: FX rack master bypass preserves each insert state (real Chromium) + run: python tests/approved_fx_rack_master_power_smoke.py - name: Stage D one runtime CSSOM and actual stylesheet network count run: python tests/approved_css_stage_d_single_bundle_smoke.py - name: Stage C rendered CSS parity (original vs compiled, three viewports + hover) diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index 46c29f4f8..36499a531 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -6,6 +6,8 @@ #include #include #include +#include +#include #include #include #include @@ -33,6 +35,9 @@ class DynamicChannelFxLeaseBank final { ChannelId id{}; ProcessingFormat format=ProcessingFormat::stereo; std::vector inserts; // CONTROL only; no creation on callback + // Reused over revision changes. This flag overrides the effective + // output without changing the individual FxInstance bypass flags. + std::shared_ptr> rackBypassed; }; // Occupied CH1 vendor/Orbit owner remains alive with accepted PCM. @@ -101,6 +106,8 @@ class DynamicChannelFxLeaseBank final { if(b.format!=ProcessingFormat::mono && b.format!=ProcessingFormat::stereo)return Fault::invalidBusLayout; Row row;row.id=b.id;row.format=b.format; + row.rackBypassed=b.rackBypassed?b.rackBypassed: + std::make_shared>(false); // CONTROL allocation row.count=static_cast(b.inserts.size()); for(std::size_t i=0;ibypassRequested.store(bypass,std::memory_order_release); return true; } + bool setRackBypass(std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,ChannelId id, + bool bypass) const noexcept { + if(expectedEpoch!=epoch_||expectedRevision!=revision_||!id.value) + return false; + const auto* row=find(id); + if(!row||!row->rackBypassed)return false; + row->rackBypassed->store(bypass,std::memory_order_release); + return true; + } + bool rackBypassed(ChannelId id) const noexcept { + const auto* row=find(id); + return row&&row->rackBypassed && + row->rackBypassed->load(std::memory_order_acquire); + } // The actual prepared vendor instance is also the native editor owner; // never synthesize a WebView editor or use a catalog name as identity. Lease leaseEditor(std::uint64_t expectedEpoch, @@ -199,7 +221,7 @@ class DynamicChannelFxLeaseBank final { retained.reserve(prior.rows_.size()); for(const auto& row:prior.rows_) { Assignment item; - item.id=row.id;item.format=row.format; + item.id=row.id;item.format=row.format;item.rackBypassed=row.rackBypassed; item.inserts.reserve(row.count); for(std::size_t slot=0;slotrackBypassed && + row->rackBypassed->load(std::memory_order_acquire); for(std::size_t i=0;icount;++i) - row->raw[i]->render(left,right,frames); + row->raw[i]->render(left,right,frames,rackOff); } private: @@ -262,6 +287,7 @@ class DynamicChannelFxLeaseBank final { ChannelId id{}; ProcessingFormat format=ProcessingFormat::stereo; std::uint8_t count=0; + std::shared_ptr> rackBypassed; // persists across revisions std::array owners{}; std::array raw{}; }; diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index 281b172f9..7bd2ba0e4 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -79,7 +79,7 @@ class LiveChannelFxGraph final { processing.clear(std::memory_order_release); return ok; } - void render(float* left,float* right,int samples) noexcept { + void render(float* left,float* right,int samples,bool rackBypassed=false) noexcept { if(processing.test_and_set(std::memory_order_acquire)) { contention.fetch_add(1,std::memory_order_relaxed); juce::FloatVectorOperations::clear(left,samples); @@ -87,7 +87,8 @@ class LiveChannelFxGraph final { return; } // G5C: atomic request from control; fade and scratch RT-owned. - bypassFade.request(bypassRequested.load(std::memory_order_relaxed)); + // Master rack bypass affects the WET/DRY envelope, never the remembered insert preference. + bypassFade.request(rackBypassed || bypassRequested.load(std::memory_order_relaxed)); if(bypassFade.fullyBypassed()) { processing.clear(std::memory_order_release); return; @@ -227,6 +228,17 @@ class LiveChannelFxGraph final { fx->bypassRequested.store(bypass,std::memory_order_release); return true; } + // One atomic rack override per channel. Individual slot bypass flags stay + // unchanged; ON restores the previous enabled/disabled combination. + bool setRackBypass(int strip,bool bypass) noexcept { + if(strip<0||strip>=fxSlots)return false; + rackBypassed_[strip].store(bypass,std::memory_order_release); + return true; + } + bool rackBypassed(int strip) const noexcept { + return strip>=0&&stripcatalogId!=catalogId)return false; for(int i=0;i=fxSlots)return; const int count=counts_[strip]; // immutable, prepared OFF RT + const bool rackOff=rackBypassed_[strip].load(std::memory_order_acquire); if(count>0) { for(int slot=0;slotrender(l,r,samples); // no shared_ptr copies or RT heap use + instance->render(l,r,samples,rackOff); // existing 8ms fade; no RT allocation } } else if(strip==0 && externalFx) + // The legacy CH1 callback owns its own per-slot smooth rack + // bypass. Never skip it abruptly or strip out its FX tail. externalFx(externalContext,strip,l,r,samples); }; if(monitorEnabled_ && (!monitorL||!monitorR))return false; @@ -315,6 +334,7 @@ class LiveChannelFxGraph final { RealtimeStripControls controls_ {}; FxBank processors_ {}; std::array counts_ {}; + std::array,fxSlots> rackBypassed_{}; // CONTROL write; one RT read per lane int activeInserts_=0; int pluginQuantum_=512; int mainOutputLeft_=0,mainOutputRight_=1; diff --git a/engine/core/UnifiedLegacyProductionAdmission.h b/engine/core/UnifiedLegacyProductionAdmission.h index 37d431806..e82a86b55 100644 --- a/engine/core/UnifiedLegacyProductionAdmission.h +++ b/engine/core/UnifiedLegacyProductionAdmission.h @@ -59,6 +59,12 @@ struct UnifiedLegacyAccepted final { fxOwners->setInsertBypass(epoch,revision,id,slot, instanceId,bypass); } + bool setFxRackBypass(const DynamicNativeSessionPublisher& publisher, + std::uint64_t epoch,std::uint64_t revision, + ChannelId id,bool bypass) const noexcept { + return matches(publisher,epoch,revision) && + fxOwners->setRackBypass(epoch,revision,id,bypass); + } DynamicChannelFxLeaseBank::Lease leaseFxEditor( const DynamicNativeSessionPublisher& publisher, std::uint64_t epoch,std::uint64_t revision,ChannelId id, diff --git a/scripts/approved_fx_rack_power.py b/scripts/approved_fx_rack_power.py new file mode 100644 index 000000000..5bbad92d3 --- /dev/null +++ b/scripts/approved_fx_rack_power.py @@ -0,0 +1,32 @@ +"""Approved single-GUI FX rack power semantics, injected at the ONE Pages build. + +The historical V28 source HTML is immutable. Apply exactly TWO audited +semantic substitutions to its JavaScript when assembling both public /preview/ +and native JUCE WebView2. No additional stylesheet, second state store, or +private fork of the mixer. t.fxOn is rack authority, slotBypass[] is the +preserved per-insert preference. Effective = fxOn && !slotBypass[i]. +""" +def apply_authoritative_fx_power(html: str) -> str: + substitutions = [ + ( + "name==='None'?'is-empty':t.slotBypass[i]?'is-bypassed':'is-active'", + "name==='None'?'is-empty':(!t.fxOn||t.slotBypass[i])?'is-bypassed':'is-active'", + ), + ( + 'aria-pressed="\'+Boolean(!t.slotBypass[i])+\'">', + 'aria-pressed="\'+Boolean(t.fxOn&&!t.slotBypass[i])+\'">', + ), + ( + "title=\"'+(t.slotBypass[i]?'Enable':'Bypass')+' only insert", + "title=\"'+(!t.fxOn?'Rack bypassed, saved '+(t.slotBypass[i]?'OFF':'ON'):t.slotBypass[i]?'Enable':'Bypass')+' only insert", + ), + ( + "aria-label=\"'+(t.slotBypass[i]?'Enable':'Bypass')+' only FX insert", + "aria-label=\"'+(!t.fxOn?'Rack bypassed, saved '+(t.slotBypass[i]?'OFF':'ON'):t.slotBypass[i]?'Enable':'Bypass')+' only FX insert", + ), + ] + for before, after in substitutions: + if html.count(before) != 1: + raise ValueError("FX master semantics anchor missing or ambiguous: " + before[:90]) + html=html.replace(before,after,1) + return html diff --git a/scripts/build_pages.py b/scripts/build_pages.py index e0e92b0c3..df0937e67 100644 --- a/scripts/build_pages.py +++ b/scripts/build_pages.py @@ -2,6 +2,7 @@ from pathlib import Path import argparse,os,json,shutil,subprocess,sys from compile_approved_css import optimize_assets +from approved_fx_rack_power import apply_authoritative_fx_power ROOT=Path(__file__).resolve().parents[1] p=argparse.ArgumentParser() p.add_argument('--out',default='dist-pages') @@ -59,6 +60,7 @@ if canonical_html.count('')!=1 or probe_tag in canonical_html: raise SystemExit('Approved Pages profiler injection must have exactly one body') canonical_html=canonical_html.replace('',probe_tag+'\n',1) +canonical_html=apply_authoritative_fx_power(canonical_html) # Stage C: compile only DEPLOYED copies, never modify locked V28 source # owners or approved PNG artwork. No new CSS/override or second renderer. canonical_html,css_compilation=optimize_assets(canonical_html,buttons_dest/'assets',runtime_bundle=True) diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index ab95387fd..b5f4b4cc5 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -82,6 +82,11 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { fx.add(juce::var(insert.release())); } ch->setProperty("inserts",juce::var(fx)); + const auto rackBypassed=row.getProperty("fxRackBypassed",{}); + if(!rackBypassed.isVoid()) { + if(!rackBypassed.isBool())return false; + ch->setProperty("fxRackBypassed",rackBypassed); + } ch->setProperty("sends",juce::var(juce::Array{})); if(role!="INPUT"){ auto dst=std::make_unique(); diff --git a/src/ConsoleLiveBridgeV6.h b/src/ConsoleLiveBridgeV6.h index a30991611..8db86ac42 100644 --- a/src/ConsoleLiveBridgeV6.h +++ b/src/ConsoleLiveBridgeV6.h @@ -150,6 +150,8 @@ class LiveConsoleBridgeV6 final { if(peaksL.isArray())object->setProperty("channelPeaksL",peaksL); if(peaksR.isArray())object->setProperty("channelPeaksR",peaksR); if(inserts.isArray())object->setProperty("fxInstances",inserts); + const auto rackPower=route.getProperty("fxRackBypassed",juce::var()); + if(rackPower.isArray())object->setProperty("fxRackBypassed",rackPower); // The prepared/unpatched native M4 graph is a real silent route. // It allows direct IN gesture to activate the FIRST source. // This does not set productionCallbackLive or fake PCM. diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 3e4fdb594..3f6f2bd95 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -92,6 +92,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } std::array slots {}; std::array, maxFx> bypassFlags {}; + std::atomic rackBypassed{false}; // does not overwrite per-slot flags // Owned and advanced exclusively by the realtime render callback. // Physical-slot identity survives an atomic logical reorder (PR #102). std::array bypassEnvelope {}; @@ -1330,6 +1331,16 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback !=armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setFxBypass(lane,slot,epoch,revision,instanceId,bypass); } + bool setDryRoutingLabFxRackBypass(int lane,std::uint64_t epoch, + std::uint64_t revision,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + if(!dryRoutingLab_.setFxRackBypass(lane,epoch,revision,bypass))return false; + if(lane==0 && graphOwned_) + graphOwned_->rackBypassed.store(bypass,std::memory_order_release); + return true; + } armix::mixer::LiveChannelFxGraph::InstanceLease leaseRoutedFxForEditor( int lane,int slot,std::uint64_t epoch,std::uint64_t revision, const juce::String& instanceId) const noexcept { @@ -1434,6 +1445,18 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.bypassNativeInsert(epoch,revision,id,slot, token,bypass); } + bool bypassNativeFxRack(std::uint64_t epoch,std::uint64_t revision, + armix::mixer::ChannelId id,bool bypass) noexcept { + if(routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + if(!dryRoutingLab_.bypassNativeRack(epoch,revision,id,bypass))return false; + // The original CH1 VST3 instance can be external-leased into the + // native ChannelId publisher. Its own crossfade gate must agree. + if(graphOwned_ && dryRoutingLab_.nativeChannelIsOriginalCh1(id)) + graphOwned_->rackBypassed.store(bypass,std::memory_order_release); + return true; + } armix::mixer::LiveChannelFxGraph::InstanceLease leaseNativeVst3Editor( std::uint64_t epoch,std::uint64_t revision, armix::mixer::ChannelId id,std::size_t slot, @@ -2036,7 +2059,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback auto& slot=graph.slots[physical]; if(!slot.processor)continue; auto& bypass=graph.bypassEnvelope[physical]; - bypass.request(graph.bypassFlags[physical].load(std::memory_order_acquire)); + bypass.request(graph.rackBypassed.load(std::memory_order_acquire) || + graph.bypassFlags[physical].load(std::memory_order_acquire)); const bool blend=bypass.transitioning(); if(blend) { diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 2daeda5f3..0af4a2bab 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1056,6 +1056,16 @@ class LiveDryRoutingLab final { }); } + // Master rack gate is a single RT-visible atomic per lane; never overwrite + // stored individual insert bypass flags. Safe under current epoch/revision. + bool setFxRackBypass(int lane,std::uint64_t expectedEpoch, + std::uint64_t expectedRevision,bool bypass) noexcept { + if(lane<0||lane>=fxSlots||!hasExplicitRoute()|| + expectedEpoch!=epoch()||expectedRevision!=revision())return false; + return publisher_.updateActiveControl(expectedEpoch,expectedRevision, + [&](FxGraph& fx) noexcept {return fx.setRackBypass(lane,bypass);}); + } + // Quiescent message-thread identity lease for the vendor's native GUI. // Shared lifetime is independent of route reorder, but not authority: // an editor request MUST match the current accepted route. @@ -1307,6 +1317,16 @@ class LiveDryRoutingLab final { return nativeAccepted_.setFxBypass(nativePublisher_,epochAtEdit, pcmRevision,target,slot,token,bypass); } + bool nativeChannelIsOriginalCh1(armix::mixer::ChannelId target) const noexcept { + return nativeAccepted_.fxOwners && + nativeAccepted_.fxOwners->externalChannel()==target && + target==nativeAccepted_.graph.ids.inputs[0]; + } + bool bypassNativeRack(std::uint64_t epochAtEdit,std::uint64_t pcmRevision, + armix::mixer::ChannelId target,bool bypass) noexcept { + return nativeAccepted_.setFxRackBypass(nativePublisher_,epochAtEdit, + pcmRevision,target,bypass); + } armix::mixer::DynamicChannelFxLeaseBank::Lease leaseNativeInsertEditor( std::uint64_t epochAtEdit,std::uint64_t pcmRevision, armix::mixer::ChannelId target,std::size_t slot, @@ -1830,6 +1850,8 @@ class LiveDryRoutingLab final { liveInserts.add(juce::var(item.release())); } row->setProperty("inserts",juce::var(liveInserts)); + row->setProperty("fxRackBypassed", + nativeAccepted_.fxOwners->rackBypassed(ch.id)); if(pcmMeterValid && meterIndexsetProperty("peakL",static_cast( nativeMeterPeaksL_[meterIndex].load(std::memory_order_relaxed))); @@ -2279,6 +2301,10 @@ class LiveDryRoutingLab final { liveFxInstances.add(juce::var(slots)); } out->setProperty("fxInstances",juce::var(liveFxInstances)); + juce::Array rackFlags; + for(int lane=0;lanerackBypassed(lane):false); + out->setProperty("fxRackBypassed",juce::var(rackFlags)); juce::Array controls,fxNames; for(int i=0;i(); + ack->setProperty("requestId",args.getProperty("requestId",{})); + ack->setProperty("ok",false); + ack->setProperty("error",reason); + browser_.emitEventIfBrowserIsVisible( + "arMixNativeFxPowerAck",juce::var(ack.release())); + } return emitNotice(reason,true); } @@ -1875,6 +1886,65 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!ok)emitNotice("Live AUX send rejected; refresh accepted routing.",true); return; } + // Accepted ChannelId FX power. A rack master is an additive gate, + // not a rewrite of the eight saved individual bypass preferences. + // Both gestures are fenced to the actual device epoch + PCM revision + // and reply with an ACK; the WebView re-reads the producer snapshot. + if(action=="routingNativeFxRackBypass" || + action=="routingNativeFxInsertBypass") { + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawId=args.getProperty("channelId",{}); + const auto rawEpoch=args.getProperty("deviceEpoch",{}); + const auto rawRevision=args.getProperty("revision",{}); + const auto parse=[](const juce::var& wire,std::uint64_t& out) -> bool { + if(!wire.isString())return false; + const auto text=wire.toString().toStdString(); + if(text.empty()||text.size()>20|| + text[0]=='0'||text.find_first_not_of("0123456789")!=std::string::npos) + return false; + try { + const auto decoded=std::stoull(text); + if(!decoded||std::to_string(decoded)!=text)return false; + out=decoded;return true; + } catch(...) {return false;} + }; + std::uint64_t channel=0,ep=0,rev=0; + const bool valid=request.isNotEmpty()&&request.length()<=128 && + parse(rawId,channel)&&parse(rawEpoch,ep)&& + parse(rawRevision,rev)&&value.isBool() && + !studioBackupBusy_&&!nativeShowBusy_&& + !engine_.independentClockActive(); + bool applied=false; + if(valid && !acceptedControlRequests_.contains(request)) { + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + const armix::mixer::ChannelId id{channel}; + if(action=="routingNativeFxRackBypass") + applied=engine_.bypassNativeFxRack(ep,rev,id,static_cast(value)); + else { + const auto token=args.getProperty("insertId",{}).toString(); + applied=slot>=0&&slot(slot),token,static_cast(value)); + } + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("ok",applied); + ack->setProperty("channelId",rawId); + ack->setProperty("bypassed",value); + ack->setProperty("error",applied?juce::String(): + "Native FX power rejected: stale device/revision, Show busy or instance mismatch"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixNativeFxPowerAck",juce::var(ack.release())); + if(applied)diagnostics_.record("NATIVE_FX_POWER", + rawId.toString()+(action=="routingNativeFxRackBypass"?" rack":" insert")+ + (static_cast(value)?" BYPASS":" ENABLE")); + return; + } + // G5C native per-instance BYPASS never recompiles the graph and // does not require muting the output. All identity gates must agree. if (action == "routingFxBypass") { diff --git a/tests/approved_fx_rack_master_power_smoke.py b/tests/approved_fx_rack_master_power_smoke.py new file mode 100644 index 000000000..25eb5dd9e --- /dev/null +++ b/tests/approved_fx_rack_master_power_smoke.py @@ -0,0 +1,89 @@ +"""P0 FX rack: header bypass overrides effective power, never saved slots. + +Chromium exercises ONE actual built /preview/ GUI (also used by native JUCE). +Public Pages only demonstrates the control state; real DSP is checked in +native engine contracts/Windows CTest and physical hardware FAT separately. +""" +from pathlib import Path +from playwright.sync_api import sync_playwright + +PAGE=Path(__file__).resolve().parents[1]/"dist-pages/preview/index.html" + + +def snapshot(page, channel=1): + root=page.locator(f'#tracks .strip[data-id="{channel}"] .fx-section') + return root.evaluate("""el=>({ + rack:el.dataset.fxChainEnabled, + header:el.querySelector('[data-action="fxOn"]').getAttribute('aria-pressed'), + slots:[...el.querySelectorAll('.fxslot-row:not(.is-empty)')].map(row=>({ + id:row.dataset.insertId, + individual:row.dataset.fxSlotEnabled, + effective:row.dataset.fxEffective, + power:row.querySelector('[data-action="slotPower"]') + ?.getAttribute('aria-pressed'), + bypassed:row.classList.contains('is-bypassed') + })) + })""") + + +def main(): + assert PAGE.is_file(), "build official /preview/ first" + with sync_playwright() as pw: + browser=pw.chromium.launch(headless=True) + try: + for width,height in [(390,844),(1366,768),(1680,900)]: + page=browser.new_page(viewport={"width":width,"height":height}) + errors=[] + page.on("pageerror",lambda e:errors.append(str(e))) + page.goto(PAGE.as_uri()) + page.locator("#tracks .strip[data-id='1']").wait_for() + root=page.locator('#tracks .strip[data-id="1"]') + initial=snapshot(page) + assert len(initial["slots"])==1 and initial["slots"][0]["power"]=="true",initial + # Load the second effect using the actual UI picker. + root.locator('.fx-pick.empty').click() + page.locator('#fastResults [data-fast-id]').first.click() + both=snapshot(page) + assert len(both["slots"])==2 and all( + x["power"]=="true" for x in both["slots"]),both + # Individual OFF is a stored preference, never overwritten. + root.locator('[data-action="slotPower"][data-slot="0"]').click() + individual=snapshot(page) + assert individual["slots"][0]["individual"]=="false",individual + assert individual["slots"][1]["individual"]=="true",individual + # On phones the official console banks one channel at a + # time; inspect CH2 via its real bank selector, not a hidden DOM. + if width < 500: + page.locator("#bankSelect").select_option("1") + other=snapshot(page,2) + if width < 500: + page.locator("#bankSelect").select_option("0") + root.locator('[data-action="fxOn"]').click() + off=snapshot(page) + assert off["header"]==off["rack"]=="false",off + assert all(row["power"]=="false" and + row["effective"]=="false" and row["bypassed"] + for row in off["slots"]),off + assert [r["individual"] for r in off["slots"]]==["false","true"],off + assert [r["id"] for r in off["slots"]]==[r["id"] for r in individual["slots"]],off + if width < 500: + page.locator("#bankSelect").select_option("1") + assert snapshot(page,2)==other,"Rack power leaked into other channel" + if width < 500: + page.locator("#bankSelect").select_option("0") + root.locator('[data-action="fxOn"]').click() + restored=snapshot(page) + assert restored["header"]==restored["rack"]=="true",restored + assert [r["power"] for r in restored["slots"]]==["false","true"],restored + assert [r["effective"] for r in restored["slots"]]==["false","true"],restored + assert [r["individual"] for r in restored["slots"]]==["false","true"],restored + assert [r["id"] for r in restored["slots"]]==[r["id"] for r in individual["slots"]],restored + assert not errors,errors + print("PASS FX rack master power + saved individual state",width,height) + page.close() + finally: + browser.close() + + +if __name__=="__main__": + main() diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index 515c7481c..475d820a1 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -178,7 +178,18 @@ static void verifyUniversalChannelIdFxLeaseAndLivePcm() { auto second=newFx(1.25f,"ch11-second-vst3"); assert(Bank::appendOwned(epoch,3,bank,ch11,ProcessingFormat::mono, second,expanded)==Bank::Fault::none); + // Rack OFF applies to the new plugin too; old per-plugin OFF remains + // untouched and native append carries the same authoritative override. + assert(bank.setRackBypass(epoch,2,ch11,true)); + assert(bank.rackBypassed(ch11)); assert(expanded.insertCount(ch11)==2); + // expanded was already created before the OFF gesture. Its revision + // holds the same shared rack gate, so it observes the control live. + assert(expanded.rackBypassed(ch11)); + assert(!expanded.setRackBypass(epoch,2,ch11,false)); // stale version + assert(expanded.setRackBypass(epoch,3,ch11,false)); + assert(!bank.rackBypassed(ch11)); + assert(!expanded.rackBypassed(ch11)); assert(expanded.insertCount(ch1)==bank.insertCount(ch1)); assert((*expanded.ownerForControl(ch11,0))->instanceId== (*bank.ownerForControl(ch11,0))->instanceId); @@ -2246,6 +2257,33 @@ int main(int argc,char** argv) { assert(heapCalls.load(std::memory_order_relaxed)==beforeNextProcess); assert(left[0]>.3f); } + // FX RACK POWER: one atomic master overrides effective processing, + // without destroying the ON/OFF preferences of individual inserts. + { + auto graph=makeGraph(2.f,3.f); + const auto token=graph->insertInstanceId(0); + assert(!graph->rackBypassed(0)); + assert(graph->setInsertBypass(0,0,token,true)); // individual OFF + assert(graph->insertBypassed(0,0)); + assert(graph->setRackBypass(0,true)); // master OFF + assert(graph->rackBypassed(0)&&graph->insertBypassed(0,0)); + assert(graph->setRackBypass(0,false)); // master ON + assert(!graph->rackBypassed(0)); + assert(graph->insertBypassed(0,0)); // stays OFF + assert(graph->setInsertBypass(0,0,token,false)); + assert(graph->setRackBypass(0,true)); + assert(graph->setRackBypass(0,false)); + assert(!graph->insertBypassed(0,0)); // returns to ON + assert(!graph->setRackBypass(-1,true)); + assert(!graph->setRackBypass(LiveChannelFxGraph::fxSlots,true)); + auto moved=makeGraph(1.f,1.f,false); + assert(graph->setRackBypass(0,true)); + assert(moved->reuse(0,*graph,"vst3-ch1-id")); + assert(moved->rackBypassed(0)); // graph retirement retains gate + assert(moved->insertBypassed(0,0)==graph->insertBypassed(0,0)); + assert(moved->setRackBypass(0,false)); + assert(!moved->insertBypassed(0,0)); // saved ON restored + } // Run M5 AFTER the legacy suite: older M4 tests use absolute global // GainFx::living/released counters as their own lifetime oracle. Running // M5 before them changes those historical baseline counts, not DSP. diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs index 6edcd12f1..b33a201fd 100644 --- a/tests/live_graph_contract_test.mjs +++ b/tests/live_graph_contract_test.mjs @@ -62,7 +62,10 @@ test('bypass is sample-smoothed by one original CH1 DSP owner for M4 and native 'native and M4 must share the original CH1 sample-accurate DSP owner'); const originalDSP=e.slice(start,legacy); const adapters=e.slice(legacy,end); - assert.match(originalDSP,/bypass\.request\(graph\.bypassFlags/); + assert.match(originalDSP,/bypass\.request\(graph\.rackBypassed\.load/); + assert.match(originalDSP,/graph\.bypassFlags\[physical\]\.load/); + assert.match(originalDSP,/\|\|/, "rack override must OR with individual insert bypass"); + assert.match(originalDSP,/slot\.processor->processBlock\(buffer,midi\)/); assert.match(originalDSP,/bypass\.transitioning\(\)/); assert.match(originalDSP,/graph\.dryScratch\.getWritePointer\(0\)/); diff --git a/tests/single_preview_publication_contract_test.py b/tests/single_preview_publication_contract_test.py index ea2397a95..93d23b9b7 100644 --- a/tests/single_preview_publication_contract_test.py +++ b/tests/single_preview_publication_contract_test.py @@ -3,6 +3,7 @@ import json, re, sys, hashlib sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts')) from compile_approved_css import LINK, optimize_css, compile_runtime_bundle, link_runtime_bundle, RUNTIME_CSS +from approved_fx_rack_power import apply_authoritative_fx_power ROOT=Path(__file__).resolve().parents[1] DST=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else ROOT/'dist-pages' gui=DST/'preview' @@ -36,6 +37,7 @@ def require(ok,why): require((gui/'assets/gui-perf-probe.js').read_bytes()== (ROOT/'site/preview-v2/assets/gui-perf-probe.js').read_bytes(), 'opt-in performance probe was not copied byte-for-byte') +expected=apply_authoritative_fx_power(expected) # Stage C: the source HTML remains byte-exact, but the 18 deployed CSS files # contain only proven cascade winners. Verify every *generated* byte and query # hash; never approve an extra stylesheet, different owner or PNG mutation. From d82f1515240ea6805f4c613bd7db7aef40f6928f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 06:20:03 +0700 Subject: [PATCH 047/219] Milestone A: one accepted GUI session and atomic FX rack power, PCM kernel golden coverage Reconcile #418 native-only bridge with selected #421 per-rack atomic engine gate. Both M4 compatibility and ChannelId use exact accepted producer readback for rack ON/OFF without destroying individual slot states. Project legacy M4 scalars, physical source and wire only from mixerSession; add negative ACK/epoch gating, C++ mixerSession test, multi-channel native sample golden tests. Preserve one JUCE callback, public /preview/ visual design, and unmerged P1 #422. Physical FAT and complete gesture-to-PCM certification remain outstanding. --- integration/ApprovedNativeRuntimeSnapshot.h | 3 + src/Main.cpp | 58 ++++++- tests/approved_native_v8_projection_test.cpp | 61 +++++++ tests/milestone_a_single_authority.test.cjs | 17 ++ tests/prepared_native_mixer_session_test.cpp | 66 ++++++++ web/approved-native-bridge.js | 167 +++++++++++++++---- 6 files changed, 342 insertions(+), 30 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index b358104bb..aee0ecf1c 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -309,6 +309,7 @@ inline void publishAuthoritativeMixerSession(juce::var& snapshot) const auto controls=m4.getProperty("channelControls",{}); const auto peakL=m4.getProperty("channelPeaksL",{}); const auto peakR=m4.getProperty("channelPeaksR",{}); + const auto rackFlags=m4.getProperty("fxRackBypassed",{}); const bool preparedM4=!channelIdReady && m4.isObject() && static_cast(m4.getProperty("active",false)) && static_cast(m4.getProperty("routeAccepted",false)) && @@ -350,6 +351,8 @@ inline void publishAuthoritativeMixerSession(juce::var& snapshot) src.getProperty("main",false))?"MAIN":"NONE"); row->setProperty("peakL",l); row->setProperty("peakR",r); + if(rackFlags.isArray() && rackFlags.getArray()->size()>i && rackFlags[i].isBool()) + row->setProperty("fxRackBypassed",rackFlags[i]); rows.add(juce::var(row.release())); } if(!validM4)rows.clear(); diff --git a/src/Main.cpp b/src/Main.cpp index 56de4c3e8..0072604af 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1528,7 +1528,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action == "scanVst3" || action == "routingDryApply" || action == "routingFxBypass" || action == "routingNativeFxRackBypass" || - action == "routingNativeFxInsertBypass")) + action == "routingNativeFxInsertBypass" || + action == "routingFxRackBypass")) { const auto reason=juce::String( "Studio backup in progress. Finish backup before editing saved FX or VST library."); @@ -1546,6 +1547,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action=="routingDryApply"?"arMixRoutingLabAck":"arMixRoutingFxBypassAck", juce::var(ack.release())); } + if(action=="routingFxRackBypass" && browser_.loaded){ + auto ack=std::make_unique(); + ack->setProperty("requestId",args.getProperty("requestId",{})); + ack->setProperty("channel",args.getProperty("channel",-1)); + ack->setProperty("ok",false); + ack->setProperty("error",reason); + browser_.emitEventIfBrowserIsVisible( + "arMixRoutingFxRackAck",juce::var(ack.release())); + } if((action=="routingNativeFxRackBypass" || action=="routingNativeFxInsertBypass") && browser_.loaded) { auto ack=std::make_unique(); @@ -1630,6 +1640,52 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "CH "+juce::String(lane+1)+" slot "+juce::String(position+1)); return; } + // M4 is internal PCM compatibility, not an independent GUI state. + // One native rack gate overrides FX wet/dry, preserving slot bypasses. + if(action=="routingFxRackBypass"){ + const auto requestId=args.getProperty("requestId",{}).toString(); + const int lane=static_cast(args.getProperty("channel",-1)); + const auto ep=args.getProperty("deviceEpoch",juce::var()); + const auto rv=args.getProperty("revision",juce::var()); + const auto route=engine_.status().getProperty("dryRoutingLab",{}); + const auto currentEp=route.getProperty("epoch",juce::var()); + const auto currentRv=route.getProperty("revision",juce::var()); + const bool tokens=(ep.isInt()||ep.isInt64()) && + (rv.isInt()||rv.isInt64()) && + static_cast(ep)>0 && + static_cast(ep)==static_cast(currentEp) && + static_cast(rv)==static_cast(currentRv); + const bool replay=acceptedControlRequests_.contains(requestId); + const bool valid=tokens&&value.isBool()&& + requestId.startsWith("rack-m4-")&&requestId.length()<=48 && + lane>=0&&lane(route.getProperty("hasAcceptedRoute",false)) && + !static_cast(route.getProperty("nativeChannelIdPcmActive",false)) && + !static_cast(route.getProperty("nativeBusStructural",false)) && + !static_cast(route.getProperty("topologyFault",true)) && + engine_.directRouteAuthorized()&&!engine_.independentClockActive(); + if(!replay && requestId.startsWith("rack-m4-") && requestId.length()<=48){ + acceptedControlRequests_.add(requestId); + if(acceptedControlRequests_.size()>512)acceptedControlRequests_.remove(0); + } + const bool applied=valid&&engine_.setDryRoutingLabFxRackBypass( + lane,static_cast(static_cast(ep)), + static_cast(static_cast(rv)), + static_cast(value)); + auto ack=std::make_unique(); + ack->setProperty("requestId",requestId); + ack->setProperty("ok",applied); + ack->setProperty("deviceEpoch",currentEp); + ack->setProperty("routingRevision",currentRv); + ack->setProperty("channel",lane); + ack->setProperty("bypassed",value); + ack->setProperty("error",applied?juce::String(): + "Native rack bypass rejected: stale epoch, revision or PCM authority"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixRoutingFxRackAck",juce::var(ack.release())); + return; + } if(action=="routingM4Control"){ const auto requestId=args.getProperty("requestId",juce::var()).toString(); const int channel=static_cast(args.getProperty("channel",-1)); diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 9446e63c3..30d9e7d69 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -481,6 +481,66 @@ static void firstSoundRouteAdmissionRegression() { assert(!publishVerifiedFirstSoundState(withoutInput,live)); } +// Control-only fixture: validates exclusive M4 session normalization, +// never claims that fixture data is a hardware PCM recording. +static void milestoneAM4SessionProjectionRegression() { + auto snapshot=canonicalSnapshot(); + snapshot.getProperty("device",{}).getDynamicObject()->setProperty("epoch","33"); + auto m4=std::make_unique(); + m4->setProperty("active",true); + m4->setProperty("routeAccepted",true); + m4->setProperty("nativeBusStructural",false); + m4->setProperty("routingRevision","19"); + m4->setProperty("masterDb",-7.5); + m4->setProperty("masterMute",false); + juce::Array sources,controls,peaksL,peaksR,rackFlags; + for(int i=0;i<10;++i) { + auto src=std::make_unique(); + src->setProperty("mode",i==4?"MONO":"NONE"); + src->setProperty("left",i==4?2:-1); + src->setProperty("right",-1); + src->setProperty("main",true); + sources.add(juce::var(src.release())); + auto ctl=std::make_unique(); + ctl->setProperty("db",i==4?-6.:0.); + ctl->setProperty("pan",i==4?25.:0.); + ctl->setProperty("mute",false); + ctl->setProperty("solo",false); + controls.add(juce::var(ctl.release())); + peaksL.add(i==4?0.125:0.0); + peaksR.add(i==4?0.25:0.0); + rackFlags.add(i==4); + } + m4->setProperty("channels",juce::var(sources)); + m4->setProperty("channelControls",juce::var(controls)); + m4->setProperty("channelPeaksL",juce::var(peaksL)); + m4->setProperty("channelPeaksR",juce::var(peaksR)); + m4->setProperty("fxRackBypassed",juce::var(rackFlags)); + snapshot.getDynamicObject()->setProperty("legacyM4",juce::var(m4.release())); + publishAuthoritativeMixerSession(snapshot); + const auto session=snapshot.getProperty("mixerSession",{}); + assert(session.getProperty("authority","").toString()=="M4"); + assert(session.getProperty("deviceEpoch","").toString()=="33"); + assert(session.getProperty("routeRevision","").toString()=="19"); + const auto rows=session.getProperty("channels",{}); + assert(rows.isArray()&&rows.getArray()->size()==10); + assert(rows[4].getProperty("id","").toString()=="m4:05"); + assert(rows[4].getProperty("fxRackBypassed",{}).isBool()); + assert(static_cast(rows[4].getProperty("fxRackBypassed",false))); + assert(std::abs(static_cast(rows[4].getProperty("controls",{}) + .getProperty("faderDb",0.0))+6.)<0.00001); + assert(std::abs(static_cast(rows[4].getProperty("controls",{}) + .getProperty("pan",0.0))-.25)<0.00001); + assert(std::abs(static_cast(session.getProperty("main",{}) + .getProperty("db",0.0))+7.5)<0.00001); + // Reject corrupt producer readback atomically, not just the bad strip. + snapshot.getProperty("legacyM4",{}).getProperty("channelControls",{}) + .getArray()->getReference(4).getDynamicObject()->setProperty("db",55.); + publishAuthoritativeMixerSession(snapshot); + assert(snapshot.getProperty("mixerSession",{}) + .getProperty("authority","").toString()=="NONE"); +} + static void firstSoundMeasuredSignalEvidenceRegression() { auto live=parse(R"JSON({ "connected":true,"directRouteAuthorized":true, @@ -573,6 +633,7 @@ int main() { controlIntentTranslationCases(snap,bus); installedCallbackAdmissionRegression(bus); firstSoundRouteAdmissionRegression(); + milestoneAM4SessionProjectionRegression(); firstSoundMeasuredSignalEvidenceRegression(); auto unadmitted=canonicalSnapshot(); publishAuthoritativeMixerSession(unadmitted); diff --git a/tests/milestone_a_single_authority.test.cjs b/tests/milestone_a_single_authority.test.cjs index aa1d6018a..d078e757a 100644 --- a/tests/milestone_a_single_authority.test.cjs +++ b/tests/milestone_a_single_authority.test.cjs @@ -14,6 +14,9 @@ test("only installed callback determines GUI channel control authority",()=>{ assert.match(adapter,/const nativeAdmitted=session\.authority==="CHANNEL_ID"/); assert.match(adapter,/m4ControlIsOwner\(\)&&m4Verified\(\)&&m4Index\(t\)>=0/); assert.doesNotMatch(adapter,/rackSavedBypass/); + assert.match(adapter,/const ctl=session\.channels\.map\(row=>row\.controls\)/); + assert.match(adapter,/session\.channels\.map\(ch=>ch\.source\)/); + assert.match(producer,/row->setProperty\("fxRackBypassed",rackFlags\[i\]\)/); assert.doesNotMatch(adapter,/AudioContext|AudioWorklet/); }); test("M4 scalar commands require correlated ACK then later publisher snapshot",()=>{ @@ -26,6 +29,20 @@ test("M4 scalar commands require correlated ACK then later publisher snapshot",( assert.match(adapter,/reconcileM4ControlReadback\(next\)/); assert.match(adapter,/session\?\.channels\?\.\[p\.channel\]/); }); +test("FX rack parent is a producer gate with independent slot preferences",()=>{ + const host=read("src/Main.cpp"),adapter=read("web/approved-native-bridge.js"); + const fx=read("engine/core/LiveChannelFxGraph.h"); + const lease=read("engine/core/DynamicChannelFxLeaseBank.h"); + assert.match(host,/action=="routingFxRackBypass"/); + assert.match(host,/setDryRoutingLabFxRackBypass/); + assert.match(host,/routingNativeFxRackBypass/); + assert.match(adapter,/requestM4RackPower\(t\)/); + assert.match(adapter,/requestAdmittedFxPower\(t,action,btn\)/); + assert.match(adapter,/reconcileM4RackReadback\(next\)/); + assert.match(fx,/rackBypassed_\[strip\]/); + assert.match(lease,/setRackBypass\(/); + assert.doesNotMatch(adapter,/rackSavedBypass/); +}); test("native ChannelId source preserves post-fader physical MAIN and VST3",()=>{ const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); const host=read("src/Main.cpp"); diff --git a/tests/prepared_native_mixer_session_test.cpp b/tests/prepared_native_mixer_session_test.cpp index ea8251b8e..eca2535df 100644 --- a/tests/prepared_native_mixer_session_test.cpp +++ b/tests/prepared_native_mixer_session_test.cpp @@ -8,7 +8,73 @@ #include using namespace armix::mixer; static bool near(float a,float b){return std::abs(a-b)<1.e-5f;} +// Real prepared native DSP kernel: deterministic multichannel PCM through +// the existing production mixer/publisher, NOT browser-mock or hardware FAT. +static void multiChannelGoldenPcm() { + PreparedNativeMixerSession native; + ChannelRoutingConfig cfg;SendRequest sends; + juce::BigInteger inputsMask,outputsMask; + for(int pin=0;pin<3;++pin)inputsMask.setBit(pin); + outputsMask.setBit(0);outputsMask.setBit(1); + cfg.stripsAndMaster.strips[0]={SourceMode::mono,0,-1,.8f,-1.f,false,false}; + cfg.stripsAndMaster.strips[4]={SourceMode::stereo,1,2,.5f,0.f,false,false}; + cfg.stripsAndMaster.strips[9]={SourceMode::mono,2,-1,.25f,1.f,false,false}; + cfg.stripsAndMaster.master.gainLinear=.5f; + std::uint64_t revision=0; + auto publish=[&](){ + PreparedNativeMixerSession::PrepareResult result; + auto candidate=PreparedNativeMixerSession::prepare( + cfg,sends,inputsMask,outputsMask,77,revision+1,64,result); + assert(candidate); + assert(native.publish(std::move(candidate),revision,77)== + PreparedNativeMixerSession::PublishResult::applied); + ++revision; + (void)native.pollRetirement(); + }; + const std::array a{.1f,.1f,.1f,.1f,.1f,.1f,.1f,.1f}; + const std::array b{.2f,.2f,.2f,.2f,.2f,.2f,.2f,.2f}; + const std::array c{.4f,.4f,.4f,.4f,.4f,.4f,.4f,.4f}; + const float* inputs[]{a.data(),b.data(),c.data()}; + std::array l{},r{}; + auto noop=[](int,float*,float*,int) noexcept {}; + auto check=[&](float left,float right){ + assert(native.render(inputs,3,l.data(),r.data(),2,8,77,noop)); + for(int i=0;i<8;++i){assert(near(l[i],left));assert(near(r[i],right));} + }; + publish();check(.09f,.15f); // CH01+CH05+CH10, true mono/stereo PCM + cfg.stripsAndMaster.strips[4].solo=true; + publish();check(.05f,.10f); // native SOLO excludes both other inputs + cfg.stripsAndMaster.strips[4].solo=false; + cfg.stripsAndMaster.strips[9].mute=true; + publish();check(.09f,.10f); // native per-lane MUTE + cfg.stripsAndMaster.master.mute=true; + publish();check(0.f,0.f); // real PCM post-mixer MAIN mute + auto invalid=cfg; + invalid.stripsAndMaster.strips[0].inputA=7; + PreparedNativeMixerSession::PrepareResult result; + auto rejected=PreparedNativeMixerSession::prepare( + invalid,sends,inputsMask,outputsMask,77,revision+1,64,result); + assert(!rejected);check(0.f,0.f); // invalid pin never replaces graph + cfg.stripsAndMaster.master.mute=false; + cfg.stripsAndMaster.strips[9].mute=false; + cfg.stripsAndMaster.strips[0].inputA=2; + publish();check(.21f,.15f); // source switch, retained lane controls + auto stale=PreparedNativeMixerSession::prepare( + cfg,sends,inputsMask,outputsMask,77,revision+1,64,result); + assert(stale); + assert(native.publish(std::move(stale),revision-1,77)!= + PreparedNativeMixerSession::PublishResult::applied); + check(.21f,.15f); // rejected stale revision cannot change PCM + cfg.stripsAndMaster.strips[3]=cfg.stripsAndMaster.strips[0]; + cfg.stripsAndMaster.strips[0]=StripConfig{}; + publish();check(.21f,.15f); // lane reorder preserves actual routing PCM + l.fill(8.f);r.fill(8.f); + assert(!native.render(inputs,3,l.data(),r.data(),2,8,78,noop)); + assert(l[0]==0.f&&r[0]==0.f); // device hotplug epoch fails silent + native.unpublish(); +} int main(){ + multiChannelGoldenPcm(); PreparedNativeMixerSession session; ChannelRoutingConfig cfg; SendRequest sends; juce::BigInteger in,out; diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 87be64aa6..6790f6d62 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -21,6 +21,8 @@ // B-stage: attached-node-only meter caches; a structural render invalidates // them atomically. Never retain detached WebView2 strips or stale channel IDs. const meterElements = new Map(); + let nativeFxPowerSerial=0,pendingNativeFxPower=null; + const pendingM4RackPowers=new Map(); let controller = null; const status = message => { lastNativeError = message; @@ -98,6 +100,7 @@ (out?.name||"SOURCE ONLY (No Main)"); } t.selected=previous.get(t.id)?.selected || false; + if(typeof ch.fxRackBypassed==="boolean")t.fxOn=!ch.fxRackBypassed; if (Array.isArray(ch.inserts)) { t.fx=Array.from({length:8},(_,i)=>ch.inserts[i]?.name||"None"); t.slotBypass=Array.from({length:8},(_,i)=>Boolean(ch.inserts[i]?.bypassed)); @@ -144,7 +147,7 @@ function projectNativeGraphWithoutFocusLoss(next) { const structure=JSON.stringify([ next.graph.channels.map(ch=>[ch.id,ch.role,ch.name, - ch.processingFormat,ch.source,ch.primaryOutId,ch.inserts]), + ch.processingFormat,ch.source,ch.primaryOutId,ch.inserts,ch.fxRackBypassed]), next.graph.edges]); if(structure!==lastNativeTopologySignature){ if(!projection(next))return false; @@ -389,6 +392,68 @@ },5000); return true; } + // M4 remains an internal PCM implementation; only native mixerSession + // readback commits UI state. Rack gate never rewrites saved plugin flags. + function requestM4RackPower(t){ + const lane=m4Index(t),session=mixerSession(),row=session?.channels?.[lane]; + const ep=safeNativeCounter(session?.deviceEpoch), + rev=safeNativeCounter(session?.routeRevision); + if(session?.authority!=="M4"||lane<0||!row || + typeof row.fxRackBypassed!=="boolean"||ep===null||rev===null|| + pendingM4RackPowers.has(lane))return false; + const bypassed=!row.fxRackBypassed,requestId="rack-m4-"+(++nativeFxPowerSerial); + pendingM4RackPowers.set(lane,{requestId,channel:lane,bypassed, + epoch:String(ep),revision:String(rev),acked:false}); + backend.emitEvent("arMixAction",{action:"routingFxRackBypass", + requestId,channel:lane,deviceEpoch:ep,revision:rev,value:bypassed}); + window.setTimeout(()=>{ + if(pendingM4RackPowers.get(lane)?.requestId!==requestId)return; + pendingM4RackPowers.delete(lane); + status("Native rack gate timed out · restoring accepted readback"); + controller?.subscribe(); + },8000); + return true; + } + function reconcileM4RackReadback(next){ + const session=next?.raw?.mixerSession; + for(const [lane,p] of pendingM4RackPowers){ + if(session?.authority!=="M4"|| + session.deviceEpoch!==p.epoch||session.routeRevision!==p.revision){ + pendingM4RackPowers.delete(lane);continue; + } + const actual=session.channels?.[lane]?.fxRackBypassed; + if(p.acked && actual===p.bypassed)pendingM4RackPowers.delete(lane); + } + } + function requestAdmittedFxPower(t,action,button){ + const session=mixerSession(),current=controller?.state()?.current; + const channelId=nativeIdFor(t); + const ch=current?.graph?.channels?.find(x=>x.id===channelId); + if(session?.authority!=="CHANNEL_ID"||!current?.admitted|| + !channelId||!ch||pendingNativeFxPower)return false; + const rack=action==="fxOn",slot=Number(button?.dataset?.slot); + const insert=!rack&&Number.isInteger(slot)&&slot>=0&&slot<8? + ch.inserts?.[slot]:null; + if((rack&&typeof ch.fxRackBypassed!=="boolean")|| + (!rack&&(!insert||typeof insert.id!=="string"|| + !insert.id||typeof insert.bypassed!=="boolean")))return false; + const bypassed=rack?!ch.fxRackBypassed:!insert.bypassed; + const requestId="native-rack-"+(++nativeFxPowerSerial); + pendingNativeFxPower={requestId,channelId,kind:rack?"rack":"insert", + insertId:insert?.id,bypassed,acked:false}; + backend.emitEvent("arMixAction",{action:rack? + "routingNativeFxRackBypass":"routingNativeFxInsertBypass", + requestId,channelId,deviceEpoch:current.device.epoch, + revision:current.graph.revision,value:bypassed, + ...(rack?{}:{slot,insertId:insert.id})}); + window.setTimeout(()=>{ + if(pendingNativeFxPower?.requestId!==requestId)return; + pendingNativeFxPower=null; + status("Native FX power timed out · accepted state preserved"); + controller?.subscribe(); + },8000); + return true; + } let pendingNativeControl=new Map(),lastNativeControlSent=new Map(); const m4Meters=new Map(); const m4Verified=()=>{ @@ -445,7 +510,11 @@ const rows=m.fxInstances[lane]; if(!t||!Array.isArray(rows))continue; let change=false; - if(t.fxOn!==true){t.fxOn=true;change=true;} + const acceptedRack=mixerSession()?.authority==="M4"? + mixerSession()?.channels?.[lane]?.fxRackBypassed:undefined; + if(typeof acceptedRack==="boolean" && t.fxOn===acceptedRack){ + t.fxOn=!acceptedRack;change=true; + } for(let slot=0;slot<8;slot++){ const live=rows[slot],entry=nativeCatalog.get(live?.catalogId); const name=live?(entry?.name||"VST3 Loaded"):"None"; @@ -519,47 +588,49 @@ } function paintM4Fallback(next) { if(!m4Verified()||!Array.isArray(scope?.tracks))return; - const m=next.raw.legacyM4,ctl=m.channelControls; + const session=next.raw?.mixerSession,m=next.raw?.legacyM4; + if(session?.authority!=="M4"||!Array.isArray(session.channels)||session.channels.length!==10)return; + const ctl=session.channels.map(row=>row.controls); paintM4FxInstances(m); const controlSignature=JSON.stringify([next.device.epoch, - m.routingRevision,ctl,m.masterDb,m.masterMute]); + session.routeRevision,ctl,session.main]); if(controlSignature!==lastM4Controls) { lastM4Controls=controlSignature; for(let i=0;i<10;i++){ const t=scope.tracks.find(x=>x.id===m4TrackIds[i]),c=ctl[i]; - if(!t||!c||!Number.isFinite(c.db)||!Number.isFinite(c.pan)|| + const db=c?.faderDb,pan=c?.pan*100; + if(!t||!c||!Number.isFinite(db)||!Number.isFinite(pan)|| typeof c.mute!=="boolean"||typeof c.solo!=="boolean")return; const oldDb=t.level; const switchChanged=t.mute!==c.mute||t.solo!==c.solo; - t.level=c.db;t.pan=c.pan;t.mute=c.mute;t.solo=c.solo; + t.level=db;t.pan=pan;t.mute=c.mute;t.solo=c.solo; if(switchChanged && scope.activeFaderId!==t.id){ scope.refreshStrip?.(t); m4Meters.delete(t.id); - }else if(Math.abs(oldDb-c.db)>.015 && + }else if(Math.abs(oldDb-db)>.015 && scope.activeFaderId!==t.id) scope.syncFaderVisual?.(t); const panKnob=document.querySelector( '.strip[data-id="'+t.id+'"] .center-pan'); if(panKnob && document.activeElement!==panKnob) - panKnob.value=String(c.pan); + panKnob.value=String(pan); } - if(scope.master && Number.isFinite(m.masterDb) && - Math.abs(scope.master.level-m.masterDb)>.015){ - scope.master.level=m.masterDb; + if(scope.master && Number.isFinite(session.main?.db) && + Math.abs(scope.master.level-session.main.db)>.015){ + scope.master.level=session.main.db; if(scope.activeFaderId!==scope.master.id) scope.syncFaderVisual?.(scope.master); } - if(scope.master && typeof m.masterMute==="boolean" && - scope.master.mute!==m.masterMute){ - scope.master.mute=m.masterMute; + if(scope.master && typeof session.main?.mute==="boolean" && + scope.master.mute!==session.main.mute){ + scope.master.mute=session.main.mute; if(scope.activeFaderId!==scope.master.id) scope.refreshStrip?.(scope.master); } } // Only measured JUCE callback peaks are painted. Cache actual live DOM // fills to avoid repeated selector searches for every timer/signal tick. - if(!Array.isArray(m.channelPeaksL)||!Array.isArray(m.channelPeaksR)|| - !scope?.displayMeterDbfs)return; + if(!scope?.displayMeterDbfs)return; const now=performance.now(); for(let i=0;i<10;i++){ const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); @@ -573,7 +644,7 @@ m4Meters.set(t.id,entry); } for(const side of ["left","right"]){ - const peak=side==="left"?m.channelPeaksL[i]:m.channelPeaksR[i]; + const peak=side==="left"?session.channels[i].peakL:session.channels[i].peakR; if(!Number.isFinite(peak)||peak<0)continue; const fill=entry[side];if(!fill)continue; scope.displayMeterDbfs(fill,peak===0?-90: @@ -585,8 +656,10 @@ function refreshRealM4Inputs(next){ if(!scope?.tracks || next?.admitted || !Array.isArray(scope.tracks) || scope.tracks.length<10) return; + const session=next?.raw?.mixerSession; + if(session?.authority!=="M4"||!Array.isArray(session.channels)||session.channels.length!==10)return; const m4=next?.raw?.legacyM4; - const rows=m4?.channels; + const rows=session.channels.map(ch=>ch.source); const signature=JSON.stringify([next?.device?.epoch, next?.device?.enabledInputs,next?.device?.inputEndpoints, m4?.active,m4?.routingRevision,rows]); @@ -1138,9 +1211,10 @@ } // Never paint unacknowledged or still-unproven M4 scalar edits. if(reconcileM4ControlReadback(next))return; + reconcileM4RackReadback(next); if(session.authority==="M4" && m4Verified()) { paintM4Fallback(next); - scope?.syncVerifiedM4Wires?.(legacy()?.channels,m4TrackIds); + scope?.syncVerifiedM4Wires?.(session.channels.map(ch=>ch.source),m4TrackIds); } // A second channel's IN can be selected while the first transaction is // in flight. Always dispatch its latest choice with a FRESH native route @@ -1162,7 +1236,7 @@ // Control readback may change at the SAME structural graph revision. // Compare the actual accepted controls/edges, never skip native fader updates. const signature=next.identity+"|"+JSON.stringify(next.graph.channels.map(ch=>[ - ch.id,ch.controls,ch.inserts,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges); + ch.id,ch.controls,ch.inserts,ch.fxRackBypassed,ch.primaryOutId]))+"|"+JSON.stringify(next.graph.edges); if (signature===lastPaintedSignature) { // Telemetry often advances without a structural graph revision. paintNativeMeters(next); @@ -1175,6 +1249,13 @@ } flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); + if(pendingNativeFxPower?.acked){ + const p=pendingNativeFxPower; + const ch=next.graph.channels.find(x=>x.id===p.channelId); + const actual=p.kind==="rack"?ch?.fxRackBypassed: + ch?.inserts?.find(x=>x.id===p.insertId)?.bypassed; + if(actual===p.bypassed)pendingNativeFxPower=null; + } status((next.productLive?"NATIVE PRODUCT LIVE":"NATIVE PCM GRAPH ACCEPTED · FAT PENDING")+ " · device "+next.device.epoch+ " · graph "+next.graph.revision+" · roster "+next.graph.rosterRevision); @@ -1213,6 +1294,27 @@ finally{profiler.sample("nativeSnapshotJsMs",performance.now()-started);} }); backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); + backend.addEventListener("arMixNativeFxPowerAck",ack=>{ + const p=pendingNativeFxPower; + if(!p||ack?.requestId!==p.requestId)return; + if(ack?.ok!==true || ack?.channelId!==p.channelId || + ack?.bypassed!==p.bypassed){ + pendingNativeFxPower=null; + status("NATIVE FX rejected · "+(ack?.error||"stale epoch or insert")); + }else p.acked=true; + controller.subscribe(); // ACK is not independently observed PCM state + }); + backend.addEventListener("arMixRoutingFxRackAck",ack=>{ + const p=pendingM4RackPowers.get(ack?.channel); + if(!p||ack?.requestId!==p.requestId)return; + if(ack?.ok!==true || String(ack.deviceEpoch)!==p.epoch || + String(ack.routingRevision)!==p.revision || + ack.bypassed!==p.bypassed){ + pendingM4RackPowers.delete(p.channel); + status("Native M4 rack gate rejected · "+(ack?.error||"stale route")); + }else p.acked=true; + controller.subscribe(); // later authoritative M4 snapshot required + }); backend.addEventListener("arMixSourceSwitchAck", ack=>{ if(nativeUiSourcePending && ack?.requestId===nativeUiSourcePending.requestId) { @@ -1529,18 +1631,25 @@ return true; } if(action==="slotPower"){ - const lane=m4Index(t); - const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); - if(!instance||!requestNativeFxPower(t,slot,!instance.live.bypassed)) - nativeToast("FX bypass unavailable · select an accepted VST3 slot"); + if(mixerSession()?.authority==="CHANNEL_ID"){ + if(!requestAdmittedFxPower(t,action,btn)) + nativeToast("Native FX slot unavailable · accepted insert/epoch required"); + }else{ + const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); + if(!m4ControlIsOwner()||!instance|| + !requestNativeFxPower(t,slot,!instance.live.bypassed)) + nativeToast("FX bypass unavailable · select an accepted VST3 slot"); + } return true; } if(action==="fxOn"){ - // #421 supplies the native atomic rack bypass. Until admitted here, - // preserve all independent VST3 slot states: never fan out partial - // per-slot bypass commands from browser JavaScript. - nativeToast("FX rack master bypass requires admitted native gate"); - status("FX HEADER NOT ADMITTED · individual VST3 states preserved"); + const authority=mixerSession()?.authority; + const ok=authority==="M4"?requestM4RackPower(t): + authority==="CHANNEL_ID"?requestAdmittedFxPower(t,action,btn):false; + if(!ok){ + nativeToast("FX header requires an accepted native rack gate"); + status("FX rack unchanged · native PCM authority or readback unavailable"); + } return true; } if(action==="format"&&t?.kind==="audio"){ From 7eddb2e6d2fe593493ebe6926ca22a9e6e4e80f4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 06:23:08 +0700 Subject: [PATCH 048/219] Milestone A: fix obsolete node expectations for newly admitted native FX rack and mixerSession WIRE --- tests/approved_native_m2_contract.test.cjs | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 38cfdeeab..62bfd9ba8 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -227,8 +227,10 @@ test("P0 real slot VST3 power and native editor use verified instance tokens",() assert.match(bridge,/if\(action==="slotPower"\)/); assert.match(bridge,/if\(action==="fxOn"\)/); assert.doesNotMatch(bridge,/rackSavedBypass/); - assert.match(bridge,/FX HEADER NOT ADMITTED/); - assert.match(bridge,/individual VST3 states preserved/); + assert.match(bridge,/requestM4RackPower\(t\)/); + assert.match(bridge,/requestAdmittedFxPower\(t,action,btn\)/); + assert.match(bridge,/FX rack unchanged/); + assert.match(bridge,/pendingM4RackPowers/); assert.match(bridge,/action:"routingFxEditor"/); assert.match(bridge,/action:"routingFxBypass"/); assert.match(bridge,/backend\.addEventListener\("arMixRoutingFxBypassAck"/); @@ -296,7 +298,7 @@ test("P0 native-only WIRE cables reflect actual M4 MAIN readback, not demo ghost const bridge=read("web/approved-native-bridge.js"); const bundle=read("scripts/build_approved_native_gui.py"); assert.match(bridge,/if\(session\.authority==="M4" && m4Verified\(\)\)/); - assert.match(bridge,/scope\?\.syncVerifiedM4Wires\?\.\(legacy\(\)\?\.channels,m4TrackIds\)/); + assert.match(bridge,/scope\?\.syncVerifiedM4Wires\?\.\(session\.channels\.map\(ch=>ch\.source\),m4TrackIds\)/); assert.match(bundle,/syncVerifiedM4Wires\(rows,ids\)/); assert.match(bundle,/typeof r\.main!=='boolean'/); assert.match(bundle,/if\(rows\[i\]\.main\)/); From ffa121e987fddee73457a859f850f72a2601941c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:18:55 +0700 Subject: [PATCH 049/219] fix(P0): stream held fader drag through current native PCM owner --- web/approved-native-bridge.js | 101 +++++++++++++++++++++++++--------- 1 file changed, 76 insertions(+), 25 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 6790f6d62..907655931 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -468,35 +468,78 @@ safeNativeCounter(m.routingRevision)!==null; }; - // One verified control path for original 10 channels and MAIN, whether - // the callback currently renders M4 or its admitted ChannelId mirror. - // Browser holds only transient gesture feedback; engine remains SSOT. - const controlKey=(parameter,t)=>parameter+":"+(t?.kind==="master"?"main":m4Index(t)); + // Live gestures choose the installed PCM authority. The M4 ordinal is + // NEVER a native ChannelId: a ChannelId graph uses its exact admitted id + // and its existing ACK + later readback contract. MAIN is a physical host + // scalar and retains its guarded routingM4Control gateway. + const controlKey=(parameter,t)=>parameter+":"+(t?.kind==="master"?"main":t?.id); + const channelIdScalarReady=(parameter,t)=>{ + const current=controller?.state()?.current; + return t?.kind!=="master" && + mixerSession()?.authority==="CHANNEL_ID" && + flags.acceptedGraphConnected && current?.admitted===true && + !!nativeIdFor(t) && + current.graph.capabilities.supportedOps.includes( + parameter==="faderDb"?"SET_FADER":"SET_PAN"); + }; + function liveScalarReady(parameter,t) { + if(t?.kind==="master")return parameter==="masterGain" && + (m4Verified()||nativeMasterReady()); + if(m4ControlIsOwner())return m4Verified()&&m4Index(t)>=0; + return channelIdScalarReady(parameter,t); + } + const nativeEditIdentity=(t)=>({ + epoch:String(hardware?.device?.epoch), + authority:mixerSession()?.authority, + channelId:t?.kind==="master"?null:nativeIdFor(t) + }); + function sameNativeEditIdentity(edit) { + const now=nativeEditIdentity(edit.t); + return edit.epoch===now.epoch && + edit.authority===now.authority && + edit.channelId===now.channelId; + } + // null means an admitted ChannelId intent is already awaiting its ACK / + // producer readback. Keep ONLY the newest dB target, never drop release. + function dispatchLiveScalar(edit) { + if(!sameNativeEditIdentity(edit) || + !liveScalarReady(edit.parameter,edit.t))return false; + if(edit.t?.kind==="master" || m4ControlIsOwner()) + return sendM4Control(edit.parameter,edit.t,edit.value); + if(controller?.state()?.pending)return null; + return intent(edit.parameter==="faderDb"?"SET_FADER":"SET_PAN", + edit.t,edit.parameter==="faderDb"? + {valueDb:edit.value}:{value:edit.value/100}); + } + function flushLiveScalars() { + for(const [key,edit] of pendingNativeControl) { + const result=dispatchLiveScalar(edit); + if(result===null)continue; + pendingNativeControl.delete(key); + if(result)lastNativeControlSent.set(key,performance.now()); + else status("LIVE PCM scalar rejected · native identity changed"); + } + } function streamFaderControl(parameter,t,value,final){ - if(!m4Verified())return false; + if(!liveScalarReady(parameter,t))return false; const key=controlKey(parameter,t),now=performance.now(); - const last=lastNativeControlSent.get(key)||0; - if(!final&&now-last<30){ - pendingNativeControl.set(key,{parameter,t,value}); - return true; - } - pendingNativeControl.delete(key); - lastNativeControlSent.set(key,now); - return sendM4Control(parameter,t,value); + const edit={parameter,t,value,...nativeEditIdentity(t)}; + pendingNativeControl.set(key,edit); // coalesce: last writer always wins + const last=lastNativeControlSent.get(key); + if(final||last===undefined||now-last>=30) + flushLiveScalars(); // pointermove publishes BEFORE pointerup + if(pendingNativeControl.has(key))queueLiveControlFlush(); + return true; } - // A quiet trailing flush guarantees final PCM value, even if the pointer - // stops between two 30ms live-control ticks or a keyboard commits instantly. + // A queued ChannelId target is retried only after its real ACK/readback + // completes (see onStatus), not by a second timer polling the audio engine. let nativeControlFlushQueued=false; function queueLiveControlFlush(){ if(nativeControlFlushQueued)return; nativeControlFlushQueued=true; window.setTimeout(()=>{ nativeControlFlushQueued=false; - for(const [key,edit] of pendingNativeControl) { - pendingNativeControl.delete(key); - lastNativeControlSent.set(key,performance.now()); - sendM4Control(edit.parameter,edit.t,edit.value); - } + flushLiveScalars(); },32); } function previewFaderWithoutModelMutation(t,db){ @@ -1267,6 +1310,15 @@ onStatus:state=>{ if(state.lastError==="PENDING_NATIVE_ACK"||state.lastError==="PENDING_ACCEPTED_SNAPSHOT") status("NATIVE "+state.lastError+" · awaiting authoritative readback"); + if(!state.pending && state.lastError==="ACCEPTED_READBACK" && + pendingNativeControl.size)queueLiveControlFlush(); + if(!state.pending && state.lastError!=="ACCEPTED_READBACK" && + state.lastError!=="NONE" && state.lastError!=="NATIVE_NOT_SUBSCRIBED"){ + // A rejected/stale ChannelId edit must not automatically re-arm a + // superseded gesture command on an unverified graph. + for(const [key,edit] of pendingNativeControl) + if(edit.authority==="CHANNEL_ID")pendingNativeControl.delete(key); + } else if(state.lastError!=="ACCEPTED_READBACK"&&state.lastError!=="NONE"&& state.lastError!=="NATIVE_NOT_SUBSCRIBED") { lastNativeError=state.lastError; @@ -1560,8 +1612,8 @@ // regardless of whether the admitted ChannelId callback or M4 renders. // <=33 commands/s/control while dragging; always flush on release. if((field==="level"||field==="pan") && - ((t.kind==="master"&&(m4Verified()||nativeMasterReady())) || - (m4ControlIsOwner()&&m4Verified()&&m4Index(t)>=0))){ + liveScalarReady(field==="level"? + (t.kind==="master"?"masterGain":"faderDb"):"pan",t)){ const numeric=Number(el.value); if(!Number.isFinite(numeric))return true; const normalized=field==="pan"? @@ -1570,9 +1622,8 @@ const key=field==="level"? (t.kind==="master"?"masterGain":"faderDb"):"pan"; if(field==="level")previewFaderWithoutModelMutation(t,numeric); - if(streamFaderControl(key,t,normalized,event.type==="change")) - queueLiveControlFlush(); - else status("LIVE PCM control rejected; checking route identity"); + if(!streamFaderControl(key,t,normalized,event.type==="change")) + status("LIVE PCM control rejected; checking route identity"); return true; } if (!flags.acceptedGraphConnected) { From 188230285a89ff618617adfdce9c68dcdb091f57 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:21:15 +0700 Subject: [PATCH 050/219] test(P0): prove held-drag native intents precede pointerup and latest gain flush --- tests/live_fader_held_drag.test.cjs | 155 ++++++++++++++++++++++++++++ 1 file changed, 155 insertions(+) create mode 100644 tests/live_fader_held_drag.test.cjs diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs new file mode 100644 index 000000000..703998b2a --- /dev/null +++ b/tests/live_fader_held_drag.test.cjs @@ -0,0 +1,155 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// P0: native fader targets must leave the GUI while the pointer is still held. +// This is a bridge/ACK regression, NOT a physical speaker FAT. +const test=require("node:test"); +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 read=p=>readFileSync(p,"utf8"); +const clone=x=>JSON.parse(JSON.stringify(x)); +const fixture=JSON.parse(read("integration/console-v6/fixtures.json")).g0; +function nativeChannelIdFixture(){ + const s=clone(fixture),main="18446744073709551615"; + s.device.epoch="18446744073709551610"; + s.productionCallbackLive=true; + s.graph.revision="5";s.graph.rosterRevision="7"; + s.graph.mainChannelId=main; + s.graph.capabilities.callbackOwnsChannelIds=true; + s.graph.capabilities.supportedOps=["SET_FADER","SET_PAN","SET_MUTE","APPLY_WIRE_TRANSACTION"]; + const ids=Array.from({length:10},(_,i)=>String(9007199254740994+i)); + s.graph.channels=ids.map((id,i)=>({ + id,role:"INPUT",name:"CH"+(i+1),processingFormat:"MONO", + primaryOutId:main, + controls:{faderDb:-6,pan:0,mute:false,solo:false},inserts:[],sends:[] + })); + s.graph.channels.push({ + id:main,role:"MAIN",name:"MAIN",processingFormat:"STEREO", + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[] + }); + s.graph.destinations=[{id:main}];s.graph.edges=[]; + s.mixerSession={ + authority:"CHANNEL_ID",deviceEpoch:s.device.epoch, + routeRevision:s.graph.revision,rosterRevision:s.graph.rosterRevision, + channels:s.graph.channels,main:{db:0,mute:false} + }; + return s; +} +function harness(){ + const sent=[],listeners=new Map(),timers=[],visual=[]; + let now=1000,nextId=100; + const scope={ + tracks:[],master:{id:1,name:"MAIN"},colors:["#568ead"], + wireGraph:{validateCandidateGraph:()=>({ok:true})}, + make:(name,kind,color)=>({id:nextId++,name,kind,color,selected:false}), + render(){},findTrack(el){return this.tracks[el.lane||0];}, + displayMeterDbfs(){},allocateWireId(){return nextId++;}, + installGraph(channels,master,edges){this.tracks=channels;this.master=master;this.edges=edges;}, + syncFaderVisual(t){visual.push({id:t.id,db:t.level});}, + stopDemo(){} + }; + const backend={ + emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn) + }; + const document={ + readyState:"complete",documentElement:{dataset:{}}, + getElementById:id=>id==="info"?{textContent:""}: + id==="preview"?{disabled:false,setAttribute(){}}:null, + querySelector:()=>null,addEventListener(){} + }; + const window={ + __JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(fn){timers.push(fn);return timers.length;} + }; + vm.runInNewContext(read("web/approved-native-bridge.js"),{ + window,document,performance:{now:()=>now},console + },{timeout:2500}); + return {scope,window,backend,sent,listeners,timers,visual, + tick(ms=40){now+=ms;const due=timers.splice(0);for(const fn of due)fn();} + }; +} +test("held ChannelId drag publishes first gain and coalesces latest BEFORE release",()=>{ + const h=harness(),s=nativeChannelIdFixture(); + h.listeners.get("arMixConsoleSnapshot")(s); + assert.equal(h.window.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); + // Pointerdown and successive pointermoves: the approved Pages setFaderFromPointer + // calls handleField(type=input), which the native-only builder forwards here. + const fader={dataset:{field:"level"},lane:4,value:"-12",min:"-60",max:"10",closest:()=>null}; + const move=db=>{ + fader.value=String(db); + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"input"}),true); + }; + move(-12); // pointerdown (button still pressed) + assert.equal(h.visual.at(-1).db,-12,"readout immediately follows finger, not native ACK"); + const first=h.sent.findLast(e=>e.name==="arMixConsoleIntent").payload; + assert.equal(first.operation,"SET_FADER"); + assert.equal(first.targetChannelId,s.graph.channels[4].id,"CH5 exact native ChannelId"); + assert.equal(first.payload.valueDb,-12,"native target emitted without pointerup"); + move(-18);move(-24);h.tick(); + assert.equal(h.sent.filter(e=>e.name==="arMixConsoleIntent").length,1, + "one in-flight native ACK: latest queued, no unbounded event storm"); + assert.equal(h.visual.at(-1).db,-24,"CH5 readout updates during mouse hold"); + const old=clone(s); // ACK alone does not repaint the accepted model + h.listeners.get("arMixConsoleAck")({ + requestId:first.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + assert.equal(h.scope.tracks[4].level,-6); + old.graph.channels[4].controls.faderDb=-12; + h.listeners.get("arMixConsoleSnapshot")(old); + h.tick(); + const second=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; + assert.equal(second.payload.valueDb,-24, + "latest intermediate target sent while pointer remains HELD"); + assert.notEqual(second.requestId,first.requestId); + // This is still BEFORE pointerup; the native backend can apply a second + // PCM gain target through its existing atomic ChannelId SET_FADER setter. + h.listeners.get("arMixConsoleAck")({ + requestId:second.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + const updated=clone(old);updated.graph.channels[4].controls.faderDb=-24; + h.listeners.get("arMixConsoleSnapshot")(updated); + assert.equal(h.scope.tracks[4].level,-24); + move(-30); // final mouse pointerup will commit this new value + h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"change"}); + const final=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; + assert.equal(final.payload.valueDb,-30,"release flushes final value"); + assert.equal(h.scope.tracks[4].level,-24,"no optimistic native readback"); + h.listeners.get("arMixConsoleAck")({ + requestId:final.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:s.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + const accepted=clone(updated);accepted.graph.channels[4].controls.faderDb=-30; + h.listeners.get("arMixConsoleSnapshot")(accepted); + assert.equal(h.scope.tracks[4].level,-30); +}); +test("all CH1/CH2/CH5/CH10 and MAIN pointermove use native scalar path",()=>{ + const source=read("site/preview-v2/index.html"); + const builder=read("scripts/build_approved_native_gui.py"); + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/LiveDryRoutingLab.h"); + assert.match(source,/function setFaderFromPointer\(ev,gesture\)/); + assert.match(source,/handleField\(\{target:input,type:'input'/); + assert.match(source,/if\(!faderGesture\|\|ev.pointerId!==faderGesture.pointerId\)return;\s*setFaderFromPointer\(ev,faderGesture\);/); + assert.match(builder,/window\.__ARMIX_NATIVE_M2__\?\.consumeField\?\.\(event\)/); + assert.match(bridge,/mixerSession\(\)\?\.authority==="CHANNEL_ID"/); + assert.match(bridge,/parameter==="faderDb"\?"SET_FADER":"SET_PAN"/); + assert.match(native,/updated\.linear=value<= -60\.f\?0\.f:std::pow\(10\.f,value\/20\.f\)/); + assert.match(native,/setNativeInputMix\(expectedEpoch,nativeAccepted_\.pcmRevision/); + // Valid input faders retain strict ChannelId mapping across a channel reorder. + // A real callback/PCM FAT is still required; gain math alone is NOT a sound test. + const h=harness(),s=nativeChannelIdFixture(); + h.listeners.get("arMixConsoleSnapshot")(s); + for(const lane of [0,1,4,9]){ + const fader={dataset:{field:"level"},lane,value:String(-8-lane)}; + h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"input"}); + // Without ACK, the single native contract allows only one active edit. + const first=h.sent.find(e=>e.name==="arMixConsoleIntent"); + assert.equal(first.payload.targetChannelId,s.graph.channels[0].id); + } + assert.match(bridge,/t\?\.kind==="master"\|\|m4ControlIsOwner\(\)/, + "MAIN physical host scalar remains routed through existing atomic gain"); +}); From da5f8d14877626ee6b43a3e5c64f5c658af9a181 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:24:05 +0700 Subject: [PATCH 051/219] test(P0): validate held CH1 CH2 CH5 CH10 and physical MAIN native targets --- tests/live_fader_held_drag.test.cjs | 36 ++++++++++++++++++++++------- 1 file changed, 28 insertions(+), 8 deletions(-) diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs index 703998b2a..409f6627f 100644 --- a/tests/live_fader_held_drag.test.cjs +++ b/tests/live_fader_held_drag.test.cjs @@ -17,7 +17,7 @@ function nativeChannelIdFixture(){ s.graph.mainChannelId=main; s.graph.capabilities.callbackOwnsChannelIds=true; s.graph.capabilities.supportedOps=["SET_FADER","SET_PAN","SET_MUTE","APPLY_WIRE_TRANSACTION"]; - const ids=Array.from({length:10},(_,i)=>String(9007199254740994+i)); + const ids=Array.from({length:10},(_,i)=>String(9007199254740994n+BigInt(i))); s.graph.channels=ids.map((id,i)=>({ id,role:"INPUT",name:"CH"+(i+1),processingFormat:"MONO", primaryOutId:main, @@ -28,6 +28,7 @@ function nativeChannelIdFixture(){ controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[] }); s.graph.destinations=[{id:main}];s.graph.edges=[]; + s.legacyM4={routingRevision:"3"}; s.mixerSession={ authority:"CHANNEL_ID",deviceEpoch:s.device.epoch, routeRevision:s.graph.revision,rosterRevision:s.graph.rosterRevision, @@ -143,13 +144,32 @@ test("all CH1/CH2/CH5/CH10 and MAIN pointermove use native scalar path",()=>{ // A real callback/PCM FAT is still required; gain math alone is NOT a sound test. const h=harness(),s=nativeChannelIdFixture(); h.listeners.get("arMixConsoleSnapshot")(s); + let accepted=s; for(const lane of [0,1,4,9]){ - const fader={dataset:{field:"level"},lane,value:String(-8-lane)}; - h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"input"}); - // Without ACK, the single native contract allows only one active edit. - const first=h.sent.find(e=>e.name==="arMixConsoleIntent"); - assert.equal(first.payload.targetChannelId,s.graph.channels[0].id); + const value=-8-lane; + const fader={dataset:{field:"level"},lane,value:String(value)}; + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"input"}),true); + const cmd=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; + assert.equal(cmd.targetChannelId,accepted.graph.channels[lane].id, + "CH"+(lane+1)+" exact ChannelId before pointerup"); + assert.equal(cmd.payload.valueDb,value); + h.listeners.get("arMixConsoleAck")({ + requestId:cmd.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:accepted.device.epoch,graphRevision:"5",rosterRevision:"7" + }); + const next=clone(accepted);next.graph.channels[lane].controls.faderDb=value; + h.listeners.get("arMixConsoleSnapshot")(next); + assert.equal(h.scope.tracks[lane].level,value); + accepted=next;h.tick(); } - assert.match(bridge,/t\?\.kind==="master"\|\|m4ControlIsOwner\(\)/, - "MAIN physical host scalar remains routed through existing atomic gain"); + const master={dataset:{field:"level"},lane:10,value:"-9"}; + h.scope.findTrack=el=>el.lane===10?h.scope.master:h.scope.tracks[el.lane||0]; + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({target:master,type:"input"}),true); + const main=h.sent.filter(e=>e.name==="arMixAction").at(-1); + assert.equal(main.payload.action,"routingM4Control"); + assert.equal(main.payload.channel,-1); + assert.equal(main.payload.parameter,"masterGain"); + assert.equal(main.payload.controlValue,-9); + assert.match(bridge,/t\\?\\.kind==="master"\\s*\\|\\|\\s*m4ControlIsOwner\\(\\)/, + "MAIN scalar uses guarded native host gain"); }); From dc7d6d675dcf68ecd87efea00a1e4b83b651fcf9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:24:08 +0700 Subject: [PATCH 052/219] test(P0): execute pre-release fader regression in existing quality gates --- tests/approved_native_m2_contract.test.cjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 62bfd9ba8..216b0840d 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -687,3 +687,6 @@ test("native Windows operator can explicitly patch first physical input, arm and assert.match(engine,/juce::String switchDryRoutingLabSource\(/); assert.match(engine,/setOutputMuted\(true\)/); }); + +// Held-pointer native fader regression runs within existing Windows / Chromium test gates. +require("./live_fader_held_drag.test.cjs"); From ab0cd750ceb3152c447e4ab04ce1744d998b28f1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:25:30 +0700 Subject: [PATCH 053/219] test(P0): use hardware-token-safe epoch for MAIN held-gain case --- tests/live_fader_held_drag.test.cjs | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs index 409f6627f..d49b7b3f8 100644 --- a/tests/live_fader_held_drag.test.cjs +++ b/tests/live_fader_held_drag.test.cjs @@ -143,6 +143,9 @@ test("all CH1/CH2/CH5/CH10 and MAIN pointermove use native scalar path",()=>{ // Valid input faders retain strict ChannelId mapping across a channel reorder. // A real callback/PCM FAT is still required; gain math alone is NOT a sound test. const h=harness(),s=nativeChannelIdFixture(); + // The physical-host MAIN gateway uses safe integer transport tokens, while + // ChannelId itself deliberately remains an exact uint64 decimal string. + s.device.epoch="77";s.mixerSession.deviceEpoch="77"; h.listeners.get("arMixConsoleSnapshot")(s); let accepted=s; for(const lane of [0,1,4,9]){ From 6c052b60e69d8a4fdedc1ecf77d349b049a28663 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:33:01 +0700 Subject: [PATCH 054/219] fix(P0): preserve native fader rollback and test held-drag against real timer deadlines --- tests/live_fader_held_drag.test.cjs | 15 ++++++++++++--- web/approved-native-bridge.js | 24 ++++++++++-------------- 2 files changed, 22 insertions(+), 17 deletions(-) diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs index d49b7b3f8..bca027a98 100644 --- a/tests/live_fader_held_drag.test.cjs +++ b/tests/live_fader_held_drag.test.cjs @@ -62,13 +62,20 @@ function harness(){ const window={ __JUCE__:{backend},ArSonApprovedNativeContract:protocol, __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, - setTimeout(fn){timers.push(fn);return timers.length;} + setTimeout(fn,delay=0){timers.push({fn,at:now+Math.max(0,Number(delay)||0)});return timers.length;} }; vm.runInNewContext(read("web/approved-native-bridge.js"),{ window,document,performance:{now:()=>now},console },{timeout:2500}); return {scope,window,backend,sent,listeners,timers,visual, - tick(ms=40){now+=ms;const due=timers.splice(0);for(const fn of due)fn();} + tick(ms=40){ + now+=ms; + for(let i=0;inow){i++;continue;} + timers.splice(i,1);timer.fn(); + } + } }; } test("held ChannelId drag publishes first gain and coalesces latest BEFORE release",()=>{ @@ -89,6 +96,8 @@ test("held ChannelId drag publishes first gain and coalesces latest BEFORE relea assert.equal(first.targetChannelId,s.graph.channels[4].id,"CH5 exact native ChannelId"); assert.equal(first.payload.valueDb,-12,"native target emitted without pointerup"); move(-18);move(-24);h.tick(); + assert.equal(h.window.__ARMIX_NATIVE_M2__.state().pending?.operation,"SET_FADER", + "a 40ms UI tick must NEVER execute the native 8000ms timeout"); assert.equal(h.sent.filter(e=>e.name==="arMixConsoleIntent").length,1, "one in-flight native ACK: latest queued, no unbounded event storm"); assert.equal(h.visual.at(-1).db,-24,"CH5 readout updates during mouse hold"); @@ -173,6 +182,6 @@ test("all CH1/CH2/CH5/CH10 and MAIN pointermove use native scalar path",()=>{ assert.equal(main.payload.channel,-1); assert.equal(main.payload.parameter,"masterGain"); assert.equal(main.payload.controlValue,-9); - assert.match(bridge,/t\\?\\.kind==="master"\\s*\\|\\|\\s*m4ControlIsOwner\\(\\)/, + assert.match(bridge,/edit\.t\?\.kind==="master"\s*\|\|\s*m4ControlIsOwner\(\)/, "MAIN scalar uses guarded native host gain"); }); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 907655931..e3e900437 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1312,23 +1312,19 @@ status("NATIVE "+state.lastError+" · awaiting authoritative readback"); if(!state.pending && state.lastError==="ACCEPTED_READBACK" && pendingNativeControl.size)queueLiveControlFlush(); - if(!state.pending && state.lastError!=="ACCEPTED_READBACK" && - state.lastError!=="NONE" && state.lastError!=="NATIVE_NOT_SUBSCRIBED"){ - // A rejected/stale ChannelId edit must not automatically re-arm a - // superseded gesture command on an unverified graph. + // Rejection cleanup and native rollback must BOTH run. + // Former else-if was unreachable after the cleanup branch matched. + const failed=!state.pending && + state.lastError!=="ACCEPTED_READBACK" && + state.lastError!=="NONE" && + state.lastError!=="NATIVE_NOT_SUBSCRIBED"; + if(failed){ for(const [key,edit] of pendingNativeControl) if(edit.authority==="CHANNEL_ID")pendingNativeControl.delete(key); - } - else if(state.lastError!=="ACCEPTED_READBACK"&&state.lastError!=="NONE"&& - state.lastError!=="NATIVE_NOT_SUBSCRIBED") { lastNativeError=state.lastError; - // Native REJECTED / STALE / timeout must roll back a temporary fader - // cap and every input value; no optimistic GUI state survives. - if (!state.pending && flags.acceptedGraphConnected && - (scope.activeFaderId??-1)<0){ - // A rejected edit MUST restore the visual model immediately, - // but never unmount an open hardware selector. This also keeps - // existing native transaction rollback semantics testable. + // Never destroy an active pointer capture. Once the user releases, + // restore only the last independently accepted native controls. + if(flags.acceptedGraphConnected && (scope.activeFaderId??-1)<0){ if(!document.activeElement?.matches?.(".strip select")) scope.render?.(); controller.subscribe(); From 2b5e084d52a31bd3a9c31b95e8d8d03519fed42c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:38:39 +0700 Subject: [PATCH 055/219] fix(P0): keep released fader at last pending gain until authoritative readback --- tests/live_fader_held_drag.test.cjs | 6 ++++ web/approved-native-bridge.js | 43 +++++++++++++++++++++++++---- 2 files changed, 44 insertions(+), 5 deletions(-) diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs index bca027a98..bb12707d0 100644 --- a/tests/live_fader_held_drag.test.cjs +++ b/tests/live_fader_held_drag.test.cjs @@ -109,6 +109,8 @@ test("held ChannelId drag publishes first gain and coalesces latest BEFORE relea assert.equal(h.scope.tracks[4].level,-6); old.graph.channels[4].controls.faderDb=-12; h.listeners.get("arMixConsoleSnapshot")(old); + assert.equal(h.visual.at(-1).db,-24, + "old native ACK/readback may update model, never snap the visual fader backwards"); h.tick(); const second=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; assert.equal(second.payload.valueDb,-24, @@ -125,6 +127,10 @@ test("held ChannelId drag publishes first gain and coalesces latest BEFORE relea assert.equal(h.scope.tracks[4].level,-24); move(-30); // final mouse pointerup will commit this new value h.window.__ARMIX_NATIVE_M2__.consumeField({target:fader,type:"change"}); + // Pointer capture has ended. A delayed old native snapshot is NOT permission + // to replace the final target that is still in flight. + h.listeners.get("arMixConsoleSnapshot")(clone(updated)); + assert.equal(h.visual.at(-1).db,-30,"released cap holds final latest target"); const final=h.sent.filter(e=>e.name==="arMixConsoleIntent").at(-1).payload; assert.equal(final.payload.valueDb,-30,"release flushes final value"); assert.equal(h.scope.tracks[4].level,-24,"no optimistic native readback"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index e3e900437..dfad2b2d1 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -164,14 +164,16 @@ const c=ch.controls; const db=c.faderDb,pan=c.pan*100; const faderChanged=Number.isFinite(db)&&Math.abs(t.level-db)>.015; + const visualDb=Number.isFinite(db)?pendingFaderVisualDb(t,db):null; const switchChanged=t.mute!==c.mute||t.solo!==c.solo; if(faderChanged)t.level=db; if(Number.isFinite(pan))t.pan=pan; t.mute=c.mute;t.solo=c.solo; - if(switchChanged){ + if(switchChanged && scope.activeFaderId!==t.id){ scope.refreshStrip?.(t); + if(visualDb!==null)scope.syncFaderVisual?.({...t,level:visualDb}); meterElements.delete(t.id); - }else if(faderChanged&&scope.activeFaderId!==t.id) + }else if(faderChanged&&scope.activeFaderId!==t.id&&visualDb===null) scope.syncFaderVisual?.(t); const root=document.querySelector('.strip[data-id="'+t.id+'"]'); const knob=root?.querySelector('.center-pan'); @@ -499,6 +501,23 @@ edit.authority===now.authority && edit.channelId===now.channelId; } + // Only the last gesture target owns the visual fader cap until the + // producer independently reads that SAME target back. Earlier ACKs and + // snapshot ticks must not move the cap backwards after pointer release. + // The track model always remains native-owned (not optimistically edited). + const liveFaderVisualTargets=new Map(); + function pendingFaderVisualDb(t,actualDb){ + const key=controlKey(t?.kind==="master"?"masterGain":"faderDb",t); + const pending=liveFaderVisualTargets.get(key); + if(!pending)return null; + if(!sameNativeEditIdentity(pending)){ + liveFaderVisualTargets.delete(key);return null; + } + if(Math.abs(actualDb-pending.value)<=.11){ + liveFaderVisualTargets.delete(key);return null; + } + return pending.value; + } // null means an admitted ChannelId intent is already awaiting its ACK / // producer readback. Keep ONLY the newest dB target, never drop release. function dispatchLiveScalar(edit) { @@ -517,7 +536,11 @@ if(result===null)continue; pendingNativeControl.delete(key); if(result)lastNativeControlSent.set(key,performance.now()); - else status("LIVE PCM scalar rejected · native identity changed"); + else { + if(liveFaderVisualTargets.get(key)===edit) + liveFaderVisualTargets.delete(key); + status("LIVE PCM scalar rejected · native identity changed"); + } } } function streamFaderControl(parameter,t,value,final){ @@ -525,6 +548,8 @@ const key=controlKey(parameter,t),now=performance.now(); const edit={parameter,t,value,...nativeEditIdentity(t)}; pendingNativeControl.set(key,edit); // coalesce: last writer always wins + if(parameter==="faderDb"||parameter==="masterGain") + liveFaderVisualTargets.set(key,edit); const last=lastNativeControlSent.get(key); if(final||last===undefined||now-last>=30) flushLiveScalars(); // pointermove publishes BEFORE pointerup @@ -645,13 +670,15 @@ if(!t||!c||!Number.isFinite(db)||!Number.isFinite(pan)|| typeof c.mute!=="boolean"||typeof c.solo!=="boolean")return; const oldDb=t.level; + const visualDb=pendingFaderVisualDb(t,db); const switchChanged=t.mute!==c.mute||t.solo!==c.solo; t.level=db;t.pan=pan;t.mute=c.mute;t.solo=c.solo; if(switchChanged && scope.activeFaderId!==t.id){ scope.refreshStrip?.(t); + if(visualDb!==null)scope.syncFaderVisual?.({...t,level:visualDb}); m4Meters.delete(t.id); }else if(Math.abs(oldDb-db)>.015 && - scope.activeFaderId!==t.id) + scope.activeFaderId!==t.id&&visualDb===null) scope.syncFaderVisual?.(t); const panKnob=document.querySelector( '.strip[data-id="'+t.id+'"] .center-pan'); @@ -660,8 +687,9 @@ } if(scope.master && Number.isFinite(session.main?.db) && Math.abs(scope.master.level-session.main.db)>.015){ + const visualDb=pendingFaderVisualDb(scope.master,session.main.db); scope.master.level=session.main.db; - if(scope.activeFaderId!==scope.master.id) + if(scope.activeFaderId!==scope.master.id && visualDb===null) scope.syncFaderVisual?.(scope.master); } if(scope.master && typeof session.main?.mute==="boolean" && @@ -1321,6 +1349,8 @@ if(failed){ for(const [key,edit] of pendingNativeControl) if(edit.authority==="CHANNEL_ID")pendingNativeControl.delete(key); + for(const [key,edit] of liveFaderVisualTargets) + if(edit.authority==="CHANNEL_ID")liveFaderVisualTargets.delete(key); lastNativeError=state.lastError; // Never destroy an active pointer capture. Once the user releases, // restore only the last independently accepted native controls. @@ -1419,6 +1449,9 @@ ack.channel===p.channel && ack.parameter===p.parameter; if(!accepted) { pendingM4Controls.delete(key); + if(p.parameter==="masterGain")liveFaderVisualTargets.delete("masterGain:main"); + else if(p.parameter==="faderDb") + liveFaderVisualTargets.delete("faderDb:"+m4TrackIds[p.channel]); status("NATIVE M4 REJECTED · "+(ack?.error||"stale control token")); } else p.acked=true; controller.subscribe(); // request later independent producer readback From 8b1b36ad0ac8eb866b2af1314456333d760e2fb1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 07:46:53 +0700 Subject: [PATCH 056/219] test(P0): exercise actual CH1 CH2 CH5 CH10 PCM through held-drag intermediate gains --- tests/dynamic_accepted_session_test.cpp | 78 +++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index d39762988..85ea292fe 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -449,6 +449,83 @@ static void verifyPrimaryOutKeepsCanonicalEdgeIdentity() { session.pollRetirement(); } +// Real PCM golden regression for a HELD operator fader, not a mouse-up-only +// scalar. Between each input move, the installed native DSP renders another +// callback block and must audibly change the waveform. Structural revision +// stays constant; there is no second callback or graph compilation. +static void verifyHeldDragIntermediatePcmOnOriginalChannels() { + constexpr std::uint64_t epoch=94021; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession pcm; + DynamicGraphRequest physical; + physical.physicalInputs=4; + physical.maxFrames=64; + std::vector initial; + for(int i=0;i<10;++i) + initial.push_back(add(static_cast(i), + ChannelRole::input,"HELD ORIGINAL CH")); + initial.push_back(add(10,ChannelRole::main,"MAIN", + ProcessingFormat::stereo)); + const auto accepted=pcm.edit(0,0,initial,physical,epoch,epoch,true); + assert(accepted.ok() && accepted.edit.createdIds.size()==11); + const auto& ids=accepted.edit.createdIds; + const auto main=ids[10]; + const std::array channels{ids[0],ids[1],ids[4],ids[9]}; + const std::array links{ + output(channels[0],main),output(channels[1],main), + output(channels[2],main),output(channels[3],main)}; + for(std::size_t i=0;i(i),-1,false}); + const auto patched=pcm.edit(1,1,links,physical,epoch,epoch,true); + assert(patched.ok() && pcm.acceptedGraphRevision()==2); + std::array a{},b{},c{},d{},left{},right{}; + a.fill(.1f);b.fill(.2f);c.fill(.3f);d.fill(.4f); + const float* pins[]{a.data(),b.data(),c.data(),d.data()}; + const std::array signal{.1f,.2f,.3f,.4f}; + std::array levels{1.f,1.f,1.f,1.f}; + const auto noFx=+[](ChannelId,float*,float*,int) noexcept {}; + const auto renderAndCheck=[&] { + assert(pcm.render(epoch,pins,4,left.data(),right.data(),64, + false,noFx)); + float sum=0.f; + for(std::size_t i=0;ifaderLinear, + linear)); + assert(pcm.acceptedGraphRevision()==2); + } + // Release is merely the last target: no structural commit and no + // newly armed audio path is required to restore the baseline. + assert(pcm.setLiveMix(epoch,2,channels[i],1.f,0.f)); + levels[i]=1.f; + assert(near(renderAndCheck(),center)); + } + // A stale epoch/revision cannot mutate an otherwise live fader or PCM. + assert(!pcm.setLiveMix(epoch-1,2,channels[2],0.f,0.f)); + assert(!pcm.setLiveMix(epoch,1,channels[2],0.f,0.f)); + assert(near(renderAndCheck(),center)); + pcm.unpublish(); + pcm.pollRetirement(); +} + // Original CH1-10 do not get a different fader/solo DSP owner from CH11. // This is an actual accepted native publisher PCM test, not a mock GUI reducer. static void verifyOriginalAndAddedInputsShareNativePcmControls() { @@ -523,6 +600,7 @@ static void verifyOriginalAndAddedInputsShareNativePcmControls() { } int main() { + verifyHeldDragIntermediatePcmOnOriginalChannels(); verifyOriginalAndAddedInputsShareNativePcmControls(); verifyPrimaryOutKeepsCanonicalEdgeIdentity(); verifyDefaultNativeMainEdgeAndDisconnectedRestore(); From 626f333159de74bb5aaad37cd6821f859a1b8cac Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:21:49 +0700 Subject: [PATCH 057/219] P0 live mixer: retain verified MAIN through temporary input NONE MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Keep an already-authorized MAIN output armed through safe same-device structural SOURCE edits even when all capture sources are temporarily NONE. New manual output arm still requires a real physical source; retain device epoch, route, VB-Cable feedback, stream safety and explicit mute behavior. Add shipped native contract regression for STEREO→NONE→STEREO. --- src/LiveAudioEngine.h | 15 ++++++++++++--- tests/approved_native_m2_contract.test.cjs | 21 +++++++++++++++++++++ 2 files changed, 33 insertions(+), 3 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 3f6f2bd95..f79406a38 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -308,7 +308,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback in.contains("cable output") && out.contains("cable input"); } - juce::String liveOutputArmFault() + // First-time output authorization requires a verified capture source. + // Restoring an ALREADY-ARMED MAIN after a structural input edit instead + // verifies the existing destination/route even when every source is NONE: + // silence is safe and the user must not have to re-press MONITOR after + // NONE -> STEREO on the same device. Epoch/feedback/STREAM fences remain. + juce::String liveOutputArmFault(bool requirePhysicalSource=true) { auto* device=deviceManager_.getCurrentAudioDevice(); if (!device || !device->isOpen() || !directFence_.permitted() @@ -338,7 +343,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(row.getProperty("mode",juce::var()).toString()=="MONO" || row.getProperty("mode",juce::var()).toString()=="STEREO") {physicalSource=true;break;} - if (!physicalSource)return "No physical input assigned. Connect CH1/CH2 first."; + if (!physicalSource && requirePhysicalSource) + return "No physical input assigned. Connect CH1/CH2 first."; return {}; } void setMonitorEnabled (bool value) noexcept { monitor_.store (value); } @@ -1159,7 +1165,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const bool sameEpoch=expectedEpoch==dryRoutingLab_.epoch(); if(wasMonitoring && sameEpoch && armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( - wasMonitoring,sameEpoch,liveOutputArmFault().isEmpty(), + // The destination was previously authorized by the operator. + // The accepted graph may now be silent (all sources NONE). + // Requiring another source here loses MAIN state permanently. + wasMonitoring,sameEpoch,liveOutputArmFault(false).isEmpty(), secondaryOutput_.armed())) setMonitorEnabled(true); return error; diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 216b0840d..7201c8480 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -171,6 +171,27 @@ test("DAW G0 native M4 controls, source clear, OUT & monitoring are real",()=>{ assert.match(builder,/type==='output'/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); +test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",()=>{ + const engine=read("src/LiveAudioEngine.h"); + const host=read("src/Main.cpp"); + const bridge=read("web/approved-native-bridge.js"); + const guard=read("src/NativeTopologyEditSafety.h"); + // First ARM remains strict, including inactive hardware and known VB-Cable loops. + assert.match(engine,/liveOutputArmFault\(bool requirePhysicalSource=true\)/); + assert.match(engine,/if \(!physicalSource && requirePhysicalSource\)/); + assert.match(engine,/knownVirtualCableFeedbackPair\(currentSetup\.inputDeviceName,/); + assert.match(host,/fault=engine_\.liveOutputArmFault\(\)/); + // Structural SOURCE changes briefly close MAIN at publish, then restore the + // previously verified destination on the SAME epoch, including silent NONE. + assert.match(engine,/if\(wasMonitoring\)setOutputMuted\(true\)/); + assert.match(engine,/wasMonitoring,sameEpoch,liveOutputArmFault\(false\)\.isEmpty\(\),/); + assert.match(guard,/return previouslyArmed && sameDeviceEpoch && outputArmSafe && !streamArmed/); + assert.match(bridge,/action:"routingSourceSwitch"/); + // The browser must not be the authority for re-arming a previously verified + // route; the engine owns state across silent source changes. + assert.doesNotMatch(bridge,/routingSourceSwitch[^;]+monitor\(false\)/); +}); + test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",()=>{ const bridge=read("web/approved-native-bridge.js"); const builder=read("scripts/build_approved_native_gui.py"); From e7eb318cf792aa2401d5fb330ee807fbc47dad80 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:25:15 +0700 Subject: [PATCH 058/219] fix(P0): preserve strict manual monitor preflight ABI while retaining silent source context --- src/LiveAudioEngine.h | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index f79406a38..30209f510 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -313,7 +313,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // verifies the existing destination/route even when every source is NONE: // silence is safe and the user must not have to re-press MONITOR after // NONE -> STEREO on the same device. Epoch/feedback/STREAM fences remain. - juce::String liveOutputArmFault(bool requirePhysicalSource=true) + // Manual MONITOR arming always requires a verified source. An already + // authorized MAIN may remain safely armed while an input is temporarily + // NONE; this overload NEVER relaxes the explicit arm safety contract. + juce::String liveOutputArmFault() { return liveOutputArmFault(true); } + juce::String liveOutputArmFault(bool requirePhysicalSource) { auto* device=deviceManager_.getCurrentAudioDevice(); if (!device || !device->isOpen() || !directFence_.permitted() From ac1e1e135b80447d5d17d1330cc9eda6ce8fe6f9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:29:55 +0700 Subject: [PATCH 059/219] fix(P0): connect approved WIRE gestures to acknowledged native ChannelId PCM graph --- integration/ApprovedNativeControlIntent.h | 154 +++++++++++++++++++ tests/approved_native_v8_projection_test.cpp | 84 ++++++++++ 2 files changed, 238 insertions(+) diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index e5062b9a3..6773c6799 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -9,6 +9,8 @@ #include #include #include +#include +#include // INTEGRATOR M3-B: bridge the approved /preview/ control ABI to the ONE // native ChannelId PCM owner from ENGINE #266. Translation is CONTROL-thread @@ -68,6 +70,108 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( return reject("STALE_NATIVE_CONTROL_REVISION"); if(!request.isString() || request.toString().isEmpty() || request.toString().length()>128)return reject("INVALID_REQUEST_ID"); + // P1 WIRE: the previous GUI emitted APPLY_WIRE_TRANSACTION, but this + // translator accepted only fader/pan/mute/solo and silently left native + // BUS routing unavailable. Validate the exact accepted ChannelId/EdgeId + // inventory and public+native capabilities BEFORE compiling any changes. + if(op=="APPLY_WIRE_TRANSACTION") { + if(!approvedHasOperation(caps.getProperty("supportedOps",{}), + "APPLY_WIRE_TRANSACTION") || + !approvedHasOperation(installedBus.getProperty("supportedOps",{}), + "NATIVE_APPLY_WIRE_TRANSACTION")) + return reject("NATIVE_WIRE_NOT_ADMITTED"); + juce::var owner,producer; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())owner=row; + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())producer=row; + if(!owner.isObject()||!producer.isObject()|| + owner.getProperty("role","").toString()!= + producer.getProperty("role","").toString()) + return reject("WIRE_SOURCE_NOT_ADMITTED"); + const auto sourceRole=owner.getProperty("role","").toString(); + if(sourceRole!="INPUT"&&sourceRole!="GROUP"&&sourceRole!="FX_RETURN") + return reject("WIRE_INVALID_SOURCE_ROLE"); + const auto sourcePayload=publicIntent.getProperty("payload",{}); + const auto rawChanges=sourcePayload.getProperty("changes",{}); + const auto* changes=rawChanges.getArray(); + if(!changes||changes->isEmpty()||changes->size()>64) + return reject("WIRE_INVALID_BATCH"); + const auto pubEdges=graph.getProperty("edges",{}); + const auto nativeEdges=installedBus.getProperty("edges",{}); + if(!pubEdges.isArray()||!nativeEdges.isArray()) + return reject("WIRE_EDGE_INVENTORY_UNAVAILABLE"); + juce::Array verified; + for(const auto& edit:*changes) { + if(!edit.isObject())return reject("WIRE_INVALID_EDIT"); + const auto kind=edit.getProperty("op","").toString(); + const auto from=edit.getProperty("from",{}); + if(from.toString()!=ids.toString()|| + (kind!="CONNECT" && kind!="REMOVE" && + kind!="RETARGET" && kind!="ROUTE_ONLY")) + return reject("WIRE_SOURCE_OR_OPERATION_INVALID"); + auto item=std::make_unique(); + item->setProperty("op",kind); + item->setProperty("from",ids); + if(kind=="REMOVE" || kind=="RETARGET") { + const auto edgeId=edit.getProperty("edgeId",{}); + if(!nativeV8Decimal(edgeId))return reject("WIRE_EDGE_ID_INVALID"); + bool pubFound=false,nativeFound=false; + for(const auto& e:*pubEdges.getArray()) + if(e.getProperty("edgeId","").toString()==edgeId.toString() && + e.getProperty("from","").toString()==ids.toString()) + pubFound=true; + for(const auto& e:*nativeEdges.getArray()) + if(e.getProperty("edgeId","").toString()==edgeId.toString() && + e.getProperty("from","").toString()==ids.toString()) + nativeFound=true; + if(!pubFound||!nativeFound)return reject("WIRE_STALE_EDGE"); + item->setProperty("edgeId",edgeId); + } + if(kind=="CONNECT" || kind=="RETARGET" || kind=="ROUTE_ONLY") { + const auto to=edit.getProperty("to",{}); + if(!nativeV8Decimal(to) || to.toString()==ids.toString()) + return reject("WIRE_INVALID_DESTINATION"); + juce::String role; + bool nativeFound=false; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==to.toString()) + role=row.getProperty("role","").toString(); + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==to.toString()) + nativeFound=true; + if(!nativeFound || + (role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN")) + return reject("WIRE_UNSUPPORTED_DESTINATION"); + // The roster's ROUTE_ONLY decoder explicitly forbids MAIN; + // choosing MAIN requires a native primary-output operation. + if(kind=="ROUTE_ONLY"&&role=="MAIN") + return reject("WIRE_MAIN_PRIMARY_REQUIRED"); + item->setProperty("to",to); + } + if(kind=="CONNECT" || kind=="ROUTE_ONLY") { + double gain=0.; + if(edit.getProperty("tap","").toString()!="POST_FADER" || + !nativeV8Number(edit.getProperty("gainLinear",{}),gain) || + gain<0.||gain>4.|| + (kind=="ROUTE_ONLY"&&gain!=1.)) + return reject("WIRE_UNSUPPORTED_TAP_OR_GAIN"); + item->setProperty("gainLinear",gain); + } + verified.add(juce::var(item.release())); + } + auto payload=std::make_unique(); + payload->setProperty("changes",juce::var(verified)); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_APPLY_WIRE_TRANSACTION"); + converted->setProperty("payload",juce::var(payload.release())); + return {juce::var(converted.release()),{}}; + } if(op!="SET_FADER" && op!="SET_PAN" && op!="SET_MUTE" && op!="SET_SOLO")return reject("UNSUPPORTED_APPROVED_CONTROL"); // Both native *and* GUI-side capabilities must be explicitly advertised @@ -203,6 +307,56 @@ inline bool executeApprovedNativeControl(Engine& engine, if(!payload.isObject())return false; const auto operation=translated.getProperty("operation","").toString(); const auto channel=armix::mixer::ChannelId{id}; + if(operation=="NATIVE_APPLY_WIRE_TRANSACTION") { + const raw=payload.getProperty("changes",{}); + const auto* edits=raw.getArray(); + if(!edits||edits->isEmpty()||edits->size()>64)return false; + std::vector changes; + changes.reserve(static_cast(edits->size())); + for(const auto& edit:*edits) { + if(!edit.isObject())return false; + const auto op=edit.getProperty("op","").toString(); + std::uint64_t from=0,to=0,edgeId=0; + if(!approvedNativeId(edit.getProperty("from",{}),from) || from!=id) + return false; + armix::mixer::WireChange change; + change.from=armix::mixer::ChannelId{from}; + if(op=="CONNECT")change.kind=armix::mixer::WireChange::Kind::connect; + else if(op=="REMOVE")change.kind=armix::mixer::WireChange::Kind::remove; + else if(op=="RETARGET")change.kind=armix::mixer::WireChange::Kind::retarget; + else if(op=="ROUTE_ONLY")change.kind=armix::mixer::WireChange::Kind::routeOnly; + else return false; + if(op=="CONNECT"||op=="RETARGET"||op=="ROUTE_ONLY") { + if(!approvedNativeId(edit.getProperty("to",{}),to)||to==from) + return false; + change.to=armix::mixer::ChannelId{to}; + } + if(op=="REMOVE"||op=="RETARGET") { + if(!approvedNativeId(edit.getProperty("edgeId",{}),edgeId)) + return false; + change.edgeId=edgeId; + } + if(op=="CONNECT"||op=="ROUTE_ONLY") { + double gain=0.; + if(!nativeV8Number(edit.getProperty("gainLinear",{}),gain) || + gain<0.||gain>4.|| + (op=="ROUTE_ONLY"&&gain!=1.)) + return false; + change.gain=static_cast(gain); + } + changes.push_back(change); + } + // The real engine may still reject while monitoring/output is armed. + // Never auto-mute, fabricate a JS graph, or bypass its safety fence. + if constexpr(requires(Engine& e, std::span values) { + e.applyNativeWireTransaction(epoch,revision,roster,values); + }) { + const auto applied=engine.applyNativeWireTransaction( + epoch,revision,roster, + std::span(changes)); + return applied.accepted && applied.error.isEmpty(); + } else return false; + } if(operation=="NATIVE_SET_CHANNEL_MIX" || operation=="NATIVE_SET_BUS_MIX") { const auto rawGain=payload.getProperty("gain",{}); diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 30d9e7d69..357e00031 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -243,6 +243,89 @@ static void controlIntentTranslationCases(const juce::var& canonical, } +// P1 WIRE gateway regression: all ChannelId/EdgeId conversion is validated +// on the CONTROL thread. A test probe is not a hardware PCM producer. +struct NativeWireProbe { + std::uint64_t epoch=0,pcmRevision=0,rosterRevision=0; + std::vector applied; + struct Result { bool accepted=false; juce::String error; }; + Result applyNativeWireTransaction(std::uint64_t ep,std::uint64_t rev, + std::uint64_t roster,std::span edits) { + epoch=ep;pcmRevision=rev;rosterRevision=roster; + applied.assign(edits.begin(),edits.end()); + return {true,{}}; + } +}; +static void approvedWireTranslationRegression(const juce::var& canonical, + const juce::var& producer) { + auto accepted=juce::JSON::parse(juce::JSON::toString(canonical,false)); + auto bus=juce::JSON::parse(juce::JSON::toString(producer,false)); + juce::Array publicOps,nativeOps; + publicOps.add("APPLY_WIRE_TRANSACTION"); + nativeOps.add("NATIVE_APPLY_WIRE_TRANSACTION"); + accepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + bus.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + const juce::String id="9007199254740993"; + const juce::String edge="9223372036854775808"; + auto request=std::make_unique(); + request->setProperty("requestId","p1-wire-control-test"); + request->setProperty("operation","APPLY_WIRE_TRANSACTION"); + request->setProperty("targetChannelId",id); + request->setProperty("deviceEpoch","91"); + request->setProperty("baseGraphRevision","25"); + request->setProperty("baseRosterRevision","9"); + auto one=std::make_unique(); + one->setProperty("op","REMOVE"); + one->setProperty("from",id); + one->setProperty("edgeId",edge); + juce::Array changes;changes.add(juce::var(one.release())); + auto payload=std::make_unique(); + payload->setProperty("changes",juce::var(changes)); + request->setProperty("payload",juce::var(payload.release())); + const auto original=juce::var(request.release()); + const auto translated=translateApprovedNativeControl(original,accepted,bus); + assert(translated.ok()); + assert(translated.translated.getProperty("operation","").toString() + =="NATIVE_APPLY_WIRE_TRANSACTION"); + NativeWireProbe native; + assert(executeApprovedNativeControl(native,translated.translated)); + assert(native.epoch==91&&native.pcmRevision==25&&native.rosterRevision==9); + assert(native.applied.size()==1); + assert(native.applied[0].kind==armix::mixer::WireChange::Kind::remove); + assert(native.applied[0].from.value==9007199254740993ULL); + assert(native.applied[0].edgeId==9223372036854775808ULL); + + auto fail=[&](juce::var intent,juce::var acceptedState,juce::var nativeState){ + const auto before=juce::JSON::toString(nativeState,false); + const auto result=translateApprovedNativeControl(intent,acceptedState,nativeState); + assert(!result.ok());assert(!result.translated.isObject()); + assert(juce::JSON::toString(nativeState,false)==before); + return result.error; + }; + auto forged=juce::JSON::parse(juce::JSON::toString(original,false)); + forged.getProperty("payload",{}).getProperty("changes",{})[0] + .getDynamicObject()->setProperty("edgeId","9223372036854775807"); + assert(fail(forged,accepted,bus)=="WIRE_STALE_EDGE"); + auto wrongSource=juce::JSON::parse(juce::JSON::toString(original,false)); + wrongSource.getProperty("payload",{}).getProperty("changes",{})[0] + .getDynamicObject()->setProperty("from","18446744073709551615"); + assert(fail(wrongSource,accepted,bus)=="WIRE_SOURCE_OR_OPERATION_INVALID"); + auto stale=juce::JSON::parse(juce::JSON::toString(original,false)); + stale.getDynamicObject()->setProperty("baseGraphRevision","24"); + assert(fail(stale,accepted,bus)=="STALE_NATIVE_CONTROL_REVISION"); + auto noNative=juce::JSON::parse(juce::JSON::toString(bus,false)); + noNative.getDynamicObject()->setProperty("supportedOps", + juce::var(juce::Array{})); + assert(fail(original,accepted,noNative)=="NATIVE_WIRE_NOT_ADMITTED"); + auto invalidTap=juce::JSON::parse(juce::JSON::toString(original,false)); + auto edit=invalidTap.getProperty("payload",{}).getProperty("changes",{})[0]; + edit.getDynamicObject()->setProperty("op","CONNECT"); + edit.getDynamicObject()->setProperty("to","18446744073709551615"); + edit.getDynamicObject()->setProperty("tap","PRE_FADER"); + edit.getDynamicObject()->setProperty("gainLinear",1.0); + assert(fail(invalidTap,accepted,bus)=="WIRE_UNSUPPORTED_TAP_OR_GAIN"); +} static void installedCallbackAdmissionRegression(const juce::var& rawBus) { // This fixture is ONLY accepted native readback; not a hardware device. // It proves Main.cpp cannot publish a fake live graph from G0/M4 JSON. @@ -631,6 +714,7 @@ int main() { assert(!static_cast(snap.getProperty("productionCallbackLive",false))); controlIntentTranslationCases(snap,bus); + approvedWireTranslationRegression(snap,bus); installedCallbackAdmissionRegression(bus); firstSoundRouteAdmissionRegression(); milestoneAM4SessionProjectionRegression(); From 9c65abfc8952586170a60164c1bf227bdb50b7ba Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:33:40 +0700 Subject: [PATCH 060/219] test(P0): verify strict manual monitor and safe source-resume overloads --- tests/approved_native_m2_contract.test.cjs | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 7201c8480..c1edc4bda 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -177,7 +177,10 @@ test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",( const bridge=read("web/approved-native-bridge.js"); const guard=read("src/NativeTopologyEditSafety.h"); // First ARM remains strict, including inactive hardware and known VB-Cable loops. - assert.match(engine,/liveOutputArmFault\(bool requirePhysicalSource=true\)/); + assert.match(engine,/juce::String liveOutputArmFault\(\)\s*\{\s*return liveOutputArmFault\(true\);\s*\}/, + "manual MONITOR always uses strict source verification"); + assert.match(engine,/juce::String liveOutputArmFault\(bool requirePhysicalSource\)/, + "previously-authorized silent MAIN may resume without a physical IN"); assert.match(engine,/if \(!physicalSource && requirePhysicalSource\)/); assert.match(engine,/knownVirtualCableFeedbackPair\(currentSetup\.inputDeviceName,/); assert.match(host,/fault=engine_\.liveOutputArmFault\(\)/); From e59166f919f4fd2b4310d31de52784a0ca45ad99 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:37:40 +0700 Subject: [PATCH 061/219] fix(P0): discover local VST3 automatically on first Add FX without blocking live PCM --- tests/approved_native_m2_contract.test.cjs | 16 ++++++++++++++++ web/approved-native-bridge.js | 19 ++++++++++++++++++- 2 files changed, 34 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index c1edc4bda..7f0e97d44 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -171,6 +171,22 @@ test("DAW G0 native M4 controls, source clear, OUT & monitoring are real",()=>{ assert.match(builder,/type==='output'/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); +test("P0 first Add FX discovers real local VST3 lazily without an audio-thread scan",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const native=read("src/Main.cpp"); + const catalog=read("src/PluginCatalog.h"); + assert.match(bridge,/function discoverFxOnFirstPickerOpen\(\)/); + assert.match(bridge,/nativeFxDiscoveryRequested=true;/); + assert.match(bridge,/backend\.emitEvent\("arMixAction",\{action:"scanVst3"\}\)/); + assert.match(bridge,/discoverFxOnFirstPickerOpen\(\);[\s\S]*?scope\?\.openFastPicker/); + assert.match(native,/action == "scanVst3"[\s\S]*?catalog_\.scanDefaults\(\)/); + assert.match(catalog,/struct Scanner final : juce::Thread/); + assert.match(bridge,/scope\?\.setNativeCatalog\?\.\(\[\.\.\.nativeCatalog\.values\(\)\]\)/); + // Neither startup nor audio callback can trigger a surprise system scan. + assert.doesNotMatch(bridge.slice(0,bridge.indexOf("function discoverFxOnFirstPickerOpen")), + /action:"scanVst3"/); +}); + test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",()=>{ const engine=read("src/LiveAudioEngine.h"); const host=read("src/Main.cpp"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index dfad2b2d1..c84f4fe38 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -364,6 +364,17 @@ return true; } let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); + let nativeFxDiscoveryRequested=false,nativeFxCatalogScanning=false; + // Lazy USER-triggered discovery: the first Add FX opens immediately and + // starts real JUCE VST3 scanning on its dedicated non-audio worker. Never + // scan during cold device startup, on a timer, or on the RT callback. + function discoverFxOnFirstPickerOpen(){ + if(!connected||nativeCatalog.size||nativeFxDiscoveryRequested|| + nativeFxCatalogScanning)return; + nativeFxDiscoveryRequested=true; + backend.emitEvent("arMixAction",{action:"scanVst3"}); + status("FX · scanning installed VST3 on background worker; picker updates automatically"); + } const pendingSlotPowers=new Map(); // ACK/readback, never demo FX flags // The rack header restores exact prior per-insert state, including // deliberately bypassed plugins; it never blindly turns ALL FX on. @@ -1522,10 +1533,13 @@ }); backend.addEventListener("arMixCatalog",catalog=>{ if(!Array.isArray(catalog?.items))return; + nativeFxCatalogScanning=catalog.scanning===true; nativeCatalog=new Map(catalog.items.filter(p=> p&&typeof p.id==="string"&&p.id.length>0&& typeof p.name==="string"&&p.name.length>0).map(p=>[p.id,p])); scope?.setNativeCatalog?.([...nativeCatalog.values()]); + if(nativeFxDiscoveryRequested&&!nativeFxCatalogScanning&&nativeCatalog.size===0) + status("No installed VST3 discovered · use Import VST3 in Plugin Manager"); if(hardware?.raw?.legacyM4)paintM4FxInstances(hardware.raw.legacyM4); const count=document.getElementById("pluginCount"); if(count)count.title="Verified JUCE native VST3 catalog"; @@ -1707,7 +1721,10 @@ channel:instance.lane,slot, instanceId:instance.live.instanceId,deviceEpoch:ep,revision:rev}); else nativeToast("VST3 editor · refresh native device and FX instance"); - }else scope?.openFastPicker?.(t,slot,btn); + }else { + discoverFxOnFirstPickerOpen(); + scope?.openFastPicker?.(t,slot,btn); + } return true; } if(action==="slotPower"){ From 3e2e4648d0bf3d1d55a97f83b7f35460e727a2ec Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:44:03 +0700 Subject: [PATCH 062/219] fix(P0): enforce actual native Wire ACK error ABI and use matching production probe --- integration/ApprovedNativeControlIntent.h | 6 +++++- tests/approved_native_v8_projection_test.cpp | 5 +++-- 2 files changed, 8 insertions(+), 3 deletions(-) diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index 6773c6799..e7c5f1b30 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -354,7 +354,11 @@ inline bool executeApprovedNativeControl(Engine& engine, const auto applied=engine.applyNativeWireTransaction( epoch,revision,roster, std::span(changes)); - return applied.accepted && applied.error.isEmpty(); + // NativeBusResult.error is const char*, not juce::String. + // The compiler and regression probe must share the exact native + // error ABI. Never claim ACK for a contradictory accepted/error pair. + return applied.accepted && applied.error != nullptr && + applied.error[0] == '\0'; } else return false; } if(operation=="NATIVE_SET_CHANNEL_MIX" || diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 357e00031..62c000f73 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -248,12 +248,13 @@ static void controlIntentTranslationCases(const juce::var& canonical, struct NativeWireProbe { std::uint64_t epoch=0,pcmRevision=0,rosterRevision=0; std::vector applied; - struct Result { bool accepted=false; juce::String error; }; + // Match the actual LiveDryRoutingLab::NativeBusResult ABI. + struct Result { bool accepted=false; const char* error="NATIVE_REJECTED"; }; Result applyNativeWireTransaction(std::uint64_t ep,std::uint64_t rev, std::uint64_t roster,std::span edits) { epoch=ep;pcmRevision=rev;rosterRevision=roster; applied.assign(edits.begin(),edits.end()); - return {true,{}}; + return {true,""}; } }; static void approvedWireTranslationRegression(const juce::var& canonical, From a80e33cf6174d5c65d26867e9b507fed84e6611a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:48:01 +0700 Subject: [PATCH 063/219] fix(P0): route MAIN WIRE and OUT through ChannelId PCM when admitted, never stale M4 --- tests/approved_native_m2_contract.test.cjs | 9 +++++ web/approved-native-bridge.js | 38 ++++++++++++++++++++++ 2 files changed, 47 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 7f0e97d44..25d7c4bcc 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -216,6 +216,15 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( const builder=read("scripts/build_approved_native_gui.py"); const native=read("src/Main.cpp"); assert.match(bridge,/function requestPrimaryOut\(t,target\)/); + assert.match(bridge,/session\?\.authority==="CHANNEL_ID"/); + assert.match(bridge,/controller\.intent\("APPLY_WIRE_TRANSACTION",channelId,/); + assert.match(bridge,/change=\{op:"ROUTE_ONLY",from:channelId,to:main,/); + assert.match(bridge,/change=\{op:"REMOVE",from:channelId,edgeId:edge\.edgeId\}/); + assert.match(bridge,/e\.primaryOutput!==false/); + assert.match(bridge,/const channel=m4Index\(t\)/); + // A native-owned MAIN WIRE never triggers the legacy routingChannelPatch. + assert.ok(bridge.indexOf('session?.authority==="CHANNEL_ID"')< + bridge.indexOf('backend.emitEvent("arMixAction",{action:"routingChannelPatch"')); assert.match(bridge,/const isMainConnect=/); assert.match(bridge,/const isMainRemove=/); assert.match(bridge,/current\.graph\.edges\.some/); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index c84f4fe38..1dc1588ee 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -331,6 +331,44 @@ // One request/ACK/readback path for BOTH the ordinary OUT select and the // hardware-like OUT→MAIN WIRE jack. No browser graph mutation on click. function requestPrimaryOut(t,target){ + // Exactly ONE PCM route authority: the admitted ChannelId publisher + // owns all MAIN/Group WIRE and OUT mutations, including original CH1-10. + // Calling the old M4 structural patch after native WIRE admission would + // reject valid routes or attempt to resurrect an incompatible M4 graph. + const session=mixerSession(),current=controller?.state()?.current; + if(session?.authority==="CHANNEL_ID"){ + const channelId=nativeIdFor(t); + const ch=current?.graph?.channels?.find(row=>row.id===channelId); + const main=current?.graph?.mainChannelId; + if(!current?.admitted || !channelId || !ch || !main || + !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION") || + !["INPUT","GROUP","FX_RETURN"].includes(ch.role) || + (target!=="MAIN"&&target!=="NONE"))return false; + const dest=ch.primaryOutId||null; + if((target==="MAIN"&&dest===main)||(target==="NONE"&&!dest)){ + controller.subscribe();return true; + } + let change; + if(target==="MAIN"){ + change={op:"ROUTE_ONLY",from:channelId,to:main, + tap:"POST_FADER",gainLinear:1}; + }else{ + // Exact EdgeId from the independent native readback; never invent a + // disconnect ID or remove an unrelated parallel SEND. + const edge=current.graph.edges.find(e=>e.enabled && + e.from===channelId && e.to===dest && + e.primaryOutput!==false); + if(!edge)return false; + change={op:"REMOVE",from:channelId,edgeId:edge.edgeId}; + } + const accepted=controller.intent("APPLY_WIRE_TRANSACTION",channelId, + {changes:[change]}); + if(!accepted.ok){status("Native OUT rejected · "+accepted.error);return false;} + window.setTimeout(()=>controller?.expire(accepted.requestId),8000); + status(t.name+" OUT → "+(target==="MAIN"?"MAIN":"NONE")+ + " · native PCM readback pending"); + return true; + } const channel=m4Index(t); const ep=safeNativeCounter(hardware?.device?.epoch), rev=safeNativeCounter(legacy()?.routingRevision); From e169f3728cdac4c2a404620724478bab8e0c1f94 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:50:20 +0700 Subject: [PATCH 064/219] test(P0): scope WIRE authority regression to primary OUT function, not unrelated routes --- tests/approved_native_m2_contract.test.cjs | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 25d7c4bcc..4b07c1d48 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -223,8 +223,12 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(bridge,/e\.primaryOutput!==false/); assert.match(bridge,/const channel=m4Index\(t\)/); // A native-owned MAIN WIRE never triggers the legacy routingChannelPatch. - assert.ok(bridge.indexOf('session?.authority==="CHANNEL_ID"')< - bridge.indexOf('backend.emitEvent("arMixAction",{action:"routingChannelPatch"')); + const primary=bridge.slice(bridge.indexOf("function requestPrimaryOut(t,target)"), + bridge.indexOf("let pendingFxInsert")); + assert.ok(primary.indexOf('session?.authority==="CHANNEL_ID"')>=0); + assert.ok(primary.indexOf('session?.authority==="CHANNEL_ID"')< + primary.indexOf("const channel=m4Index(t)"), + "ChannelId branch must precede the legacy M4 fallback inside requestPrimaryOut"); assert.match(bridge,/const isMainConnect=/); assert.match(bridge,/const isMainRemove=/); assert.match(bridge,/current\.graph\.edges\.some/); From 6070911f37bdf09c018d9949204ba087406d4285 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 08:56:07 +0700 Subject: [PATCH 065/219] fix(build): declare native WIRE change array with correct C++ auto type --- integration/ApprovedNativeControlIntent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index e7c5f1b30..792ea1f21 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -308,7 +308,7 @@ inline bool executeApprovedNativeControl(Engine& engine, const auto operation=translated.getProperty("operation","").toString(); const auto channel=armix::mixer::ChannelId{id}; if(operation=="NATIVE_APPLY_WIRE_TRANSACTION") { - const raw=payload.getProperty("changes",{}); + const auto raw=payload.getProperty("changes",{}); const auto* edits=raw.getArray(); if(!edits||edits->isEmpty()||edits->size()>64)return false; std::vector changes; From e407089c3ddce6c71f8f29b287372aa818bb9145 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:02:16 +0700 Subject: [PATCH 066/219] test(P0): exercise WIRE control with complete native engine ABI, including existing scalars --- tests/approved_native_v8_projection_test.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 62c000f73..d021c0bf1 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -245,7 +245,7 @@ static void controlIntentTranslationCases(const juce::var& canonical, // P1 WIRE gateway regression: all ChannelId/EdgeId conversion is validated // on the CONTROL thread. A test probe is not a hardware PCM producer. -struct NativeWireProbe { +struct NativeWireProbe : NativeControlProbe { std::uint64_t epoch=0,pcmRevision=0,rosterRevision=0; std::vector applied; // Match the actual LiveDryRoutingLab::NativeBusResult ABI. From 4849b7abe1d7a8640be9ea1608c11a231ac5a137 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:21:46 +0700 Subject: [PATCH 067/219] fix(P0): preserve authorized MAIN across structural source reconnect without toggling operator monitor --- src/LiveAudioEngine.h | 33 +++++++++++++------ tests/prepared_native_mixer_session_test.cpp | 34 ++++++++++++++++++++ 2 files changed, 57 insertions(+), 10 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 30209f510..e34a7720e 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1145,7 +1145,11 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback try { error=edit([&] { enteredPublication=true; - if(wasMonitoring)setOutputMuted(true); + // A topology publication is NOT an operator MONITOR OFF. + // Preserve the authorized MAIN decision across NONE -> STEREO. + // Only gate the physical render for this short commit window. + if(wasMonitoring) + topologyPublicationMute_.store(true,std::memory_order_release); }); } catch(const std::exception& ex) { @@ -1167,14 +1171,18 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback (void)dryRoutingLab_.admitChannelIdFromAcceptedM4( graphOwned_->count,frames,true,currentOriginalCh1Lease()); const bool sameEpoch=expectedEpoch==dryRoutingLab_.epoch(); - if(wasMonitoring && sameEpoch && - armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( - // The destination was previously authorized by the operator. - // The accepted graph may now be silent (all sources NONE). - // Requiring another source here loses MAIN state permanently. - wasMonitoring,sameEpoch,liveOutputArmFault(false).isEmpty(), - secondaryOutput_.armed())) - setMonitorEnabled(true); + const bool safeToResume=wasMonitoring && sameEpoch && + armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + // An accepted NONE source is silent, but never removes the + // user's previously authorized output destination. + wasMonitoring,sameEpoch,liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed()); + // When a device/handoff/output fence fails, revoke authorization + // instead of accidentally reopening a changed or unsafe endpoint. + // For a safe same-device edit, do NOT rewrite the user's MONITOR bit: + // the temporary publication gate is a separate realtime control. + if(wasMonitoring && !safeToResume)setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); return error; } juce::String switchDryRoutingLabSource(int strip,std::uint64_t epoch, @@ -1908,6 +1916,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::atomic routeReconfiguring_ {false}; std::optional savedLiveSetup_; // Indexed atomic bypass flags: instant RT-safe toggles, no graph detachment. + // Temporary publication silence never changes operator MONITOR or MAIN MUTE. + // The DIRECT device fence and physical-output verification remain separate. + std::atomic topologyPublicationMute_ { false }; std::atomic monitor_ { false }, channelMute_ { false }, masterMute_ { false }, masterMono_ { false }, dryTest_ { false }; std::atomic masterGain_ { 1.f }, channelGain_ { 1.f }, channelPan_ { 0.f }; std::atomic inputPeak_ { 0.f }, postFxPeak_ { 0.f }, outputPeak_ { 0.f }; @@ -2249,7 +2260,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback activeDiagnosticRoute == armix::diagnostics::Route::normal, !routeReconfiguring_.load(std::memory_order_acquire), !masterMute_.load(std::memory_order_relaxed), - monitor_.load(std::memory_order_relaxed), + monitor_.load(std::memory_order_relaxed) && + !topologyPublicationMute_.load(std::memory_order_acquire), secondaryOutput_.armed()); const bool outputPermitted=outputGate.renderMain; // Native input PCM must remain observable even with safe output MUTE. @@ -2368,6 +2380,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback jassert(armix::mixer::NativeRenderAuthority::mayRunDiagnostic( renderOwner)); const bool enabled = monitor_.load (std::memory_order_relaxed) + && !topologyPublicationMute_.load (std::memory_order_acquire) && !routeReconfiguring_.load (std::memory_order_acquire); const auto route = diagnosticRoute_.load (std::memory_order_relaxed); const bool toneTest = route == armix::diagnostics::Route::outputOnlyTone; diff --git a/tests/prepared_native_mixer_session_test.cpp b/tests/prepared_native_mixer_session_test.cpp index eca2535df..79b2479b9 100644 --- a/tests/prepared_native_mixer_session_test.cpp +++ b/tests/prepared_native_mixer_session_test.cpp @@ -59,6 +59,40 @@ static void multiChannelGoldenPcm() { cfg.stripsAndMaster.strips[9].mute=false; cfg.stripsAndMaster.strips[0].inputA=2; publish();check(.21f,.15f); // source switch, retained lane controls + // Production PCM regression: connected input -> NONE -> same input. + // Every control/other channel stays attached; silence never changes + // physical MAIN authorization, which belongs to LiveAudioEngine. + const auto ch1=cfg.stripsAndMaster.strips[0]; + const auto ch5=cfg.stripsAndMaster.strips[4]; + const auto ch10=cfg.stripsAndMaster.strips[9]; + cfg.stripsAndMaster.strips[0].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[0].inputA=-1; + cfg.stripsAndMaster.strips[0].inputB=-1; + publish();check(.05f,.15f); // CH5+CH10 still sound + cfg.stripsAndMaster.strips[0]=ch1; + publish();check(.21f,.15f); // CH1 resumes without resetting gain + cfg.stripsAndMaster.strips[4].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[4].inputA=-1; + cfg.stripsAndMaster.strips[4].inputB=-1; + publish();check(.16f,.05f); // CH5 stereo->NONE, others still sound + cfg.stripsAndMaster.strips[4]=ch5; + publish();check(.21f,.15f); // CH5 stereo resumes + cfg.stripsAndMaster.strips[9].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[9].inputA=-1; + cfg.stripsAndMaster.strips[9].inputB=-1; + publish();check(.21f,.10f); // CH10 mono->NONE + cfg.stripsAndMaster.strips[9]=ch10; + publish();check(.21f,.15f); // CH10 mono resumes + // An explicitly muted MAIN remains silent through both graph edits. + cfg.stripsAndMaster.master.mute=true; + cfg.stripsAndMaster.strips[4].source=SourceMode::disconnected; + cfg.stripsAndMaster.strips[4].inputA=-1; + cfg.stripsAndMaster.strips[4].inputB=-1; + publish();check(0.f,0.f); + cfg.stripsAndMaster.strips[4]=ch5; + publish();check(0.f,0.f); + cfg.stripsAndMaster.master.mute=false; + publish();check(.21f,.15f); auto stale=PreparedNativeMixerSession::prepare( cfg,sends,inputsMask,outputsMask,77,revision+1,64,result); assert(stale); From 9be7c82be8e4333d0b85d92a464879312f093827 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:25:13 +0700 Subject: [PATCH 068/219] fix(P0): normalize exact native session tokens for FX, OUT and mixer commands --- src/Main.cpp | 29 +++++++++------------- src/NativeSessionToken.h | 33 +++++++++++++++++++++++++ tests/native_dry_route_command_test.cpp | 21 ++++++++++++++++ 3 files changed, 66 insertions(+), 17 deletions(-) create mode 100644 src/NativeSessionToken.h diff --git a/src/Main.cpp b/src/Main.cpp index 0072604af..ff5ecd958 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -9,6 +9,7 @@ #include "../integration/ApprovedNativeRuntimeSnapshot.h" #include "../integration/ApprovedNativeControlIntent.h" #include "LiveAudioEngine.h" +#include "NativeSessionToken.h" #include "ArSonMixStartupSplash.h" #include "VstOrbitController.h" #include "../engine/core/OrbitDistanceMapping.h" @@ -1608,11 +1609,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto actualRev=status.getProperty("revision",{}); const auto* plugin=catalog_.find(id); juce::String error="FX INSERT: invalid/stale device, channel, slot or catalog"; - const bool tokens=(ep.isInt()||ep.isInt64())&& - (rv.isInt()||rv.isInt64())&& - static_cast(ep)>0 && - static_cast(ep)==static_cast(actualEp)&& - static_cast(rv)==static_cast(actualRev); + const bool tokens= + armix::console::nativeSessionTokenMatches(ep,actualEp) && + armix::console::nativeSessionTokenMatches(rv,actualRev); if(requestId.startsWith("fx-")&&requestId.length()<=48 && tokens && lane>=0&&lane=0&&position(ep)>0 && - static_cast(ep)==static_cast(currentEp) && - static_cast(rv)==static_cast(currentRv); + const bool tokens= + armix::console::nativeSessionTokenMatches(ep,currentEp) && + armix::console::nativeSessionTokenMatches(rv,currentRv); const bool replay=acceptedControlRequests_.contains(requestId); const bool valid=tokens&&value.isBool()&& requestId.startsWith("rack-m4-")&&requestId.length()<=48 && @@ -1697,11 +1694,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto route=state.getProperty("dryRoutingLab",{}); const auto currentEp=route.getProperty("epoch",juce::var()); const auto currentRv=route.getProperty("revision",juce::var()); - const bool tokenOk=(ep.isInt()||ep.isInt64()) && - (rv.isInt()||rv.isInt64()) && - static_cast(ep)>0 && - static_cast(ep)==static_cast(currentEp) && - static_cast(rv)==static_cast(currentRv); + const bool tokenOk= + armix::console::nativeSessionTokenMatches(ep,currentEp) && + armix::console::nativeSessionTokenMatches(rv,currentRv); const bool ready=tokenOk && requestId.startsWith("m4-") && requestId.length()<=48 && !nativeShowBusy_ && !studioBackupBusy_ && @@ -1764,8 +1759,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (operation=="SET_PROCESSING_FORMAT" && (target=="MONO"||target=="STEREO")); if(requestId>0 && channel>=0 && channel(static_cast(ep)), diff --git a/src/NativeSessionToken.h b/src/NativeSessionToken.h new file mode 100644 index 000000000..0b5399739 --- /dev/null +++ b/src/NativeSessionToken.h @@ -0,0 +1,33 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include + +namespace armix::console { +// The WebView JSON bridge may encode an integral Number as JUCE double. +// Never reinterpret a fractional/NaN/oversized JavaScript value as a +// different device epoch or graph revision. This is CONTROL thread only. +inline std::uint64_t nativeSessionTokenValue(const juce::var& value) noexcept { + if(value.isInt() || value.isInt64()) { + const auto n=static_cast(value); + return n>0 ? static_cast(n) : 0; + } + if(value.isDouble()) { + const auto n=static_cast(value); + constexpr double maxExact=9007199254740991.0; // 2^53 - 1 + if(std::isfinite(n) && n>0. && n<=maxExact && + std::floor(n)==n) + return static_cast(n); + } + return 0; +} +inline bool nativeSessionTokenValid(const juce::var& supplied) noexcept { + return nativeSessionTokenValue(supplied)!=0; +} +inline bool nativeSessionTokenMatches(const juce::var& supplied, + const juce::var& producer) noexcept { + const auto accepted=nativeSessionTokenValue(producer); + return accepted!=0 && nativeSessionTokenValue(supplied)==accepted; +} +} // namespace armix::console diff --git a/tests/native_dry_route_command_test.cpp b/tests/native_dry_route_command_test.cpp index dbc1852d5..3b2e5e951 100644 --- a/tests/native_dry_route_command_test.cpp +++ b/tests/native_dry_route_command_test.cpp @@ -3,6 +3,8 @@ #include "../engine/core/PreparedMixerBlock.h" #include "../src/NativeVerifiedSourcePatch.h" #include "../src/NativeTopologyEditSafety.h" +#include "../src/NativeSessionToken.h" +#include #if defined(NDEBUG) #undef NDEBUG #endif @@ -17,6 +19,25 @@ int main(){ // STREAM is consuming the old graph. Physical re-arm is never implicit // after a device epoch change or unsafe / unpatched output. using Guard=NativeTopologyEditSafety; + // JUCE WebView JSON can carry whole numbers as Double. Native routing + // commands must accept the SAME epoch/revision but reject stale/fractional + // and JS-inexact tokens, regardless of action (FX/OUT/M4). + using armix::console::nativeSessionTokenMatches; + using armix::console::nativeSessionTokenValid; + const juce::var epoch=juce::int64(91); + assert(nativeSessionTokenMatches(juce::var(91),epoch)); + assert(nativeSessionTokenMatches(juce::var(91.0),epoch)); + assert(nativeSessionTokenMatches(juce::var(juce::int64(91)),epoch)); + assert(!nativeSessionTokenMatches(juce::var(92.0),epoch)); + assert(!nativeSessionTokenMatches(juce::var(91.5),epoch)); + assert(!nativeSessionTokenMatches(juce::var("91"),epoch)); + assert(!nativeSessionTokenValid(juce::var(0.0))); + assert(!nativeSessionTokenValid(juce::var(-1.0))); + assert(!nativeSessionTokenValid(juce::var(9007199254740992.0))); + assert(!nativeSessionTokenValid( + juce::var(std::numeric_limits::quiet_NaN()))); + assert(!nativeSessionTokenValid( + juce::var(std::numeric_limits::infinity()))); static_assert(!Guard::structuralSource(true,true)); static_assert( Guard::structuralSource(true,false)); static_assert( Guard::structuralSource(false,true)); From bf67cc9607c3dcc96b0ae88ef728b36b23ff3e03 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:28:16 +0700 Subject: [PATCH 069/219] test(P0): verify non-destructive publication safety gate instead of old monitor toggle --- tests/approved_native_m2_contract.test.cjs | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 4b07c1d48..5310a3784 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -200,9 +200,12 @@ test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",( assert.match(engine,/if \(!physicalSource && requirePhysicalSource\)/); assert.match(engine,/knownVirtualCableFeedbackPair\(currentSetup\.inputDeviceName,/); assert.match(host,/fault=engine_\.liveOutputArmFault\(\)/); - // Structural SOURCE changes briefly close MAIN at publish, then restore the - // previously verified destination on the SAME epoch, including silent NONE. - assert.match(engine,/if\(wasMonitoring\)setOutputMuted\(true\)/); + // Structural SOURCE changes gate physical output only at publication. + // The user's MONITOR decision persists on the same safe device/route. + assert.match(engine,/if\(wasMonitoring\)\s*topologyPublicationMute_\.store\(true,std::memory_order_release\)/); + assert.match(engine,/if\(wasMonitoring && !safeToResume\)setOutputMuted\(true\)/); + assert.match(engine,/topologyPublicationMute_\.store\(false,std::memory_order_release\)/); + assert.match(engine,/monitor_\.load\(std::memory_order_relaxed\) &&\s*!topologyPublicationMute_\.load\(std::memory_order_acquire\)/); assert.match(engine,/wasMonitoring,sameEpoch,liveOutputArmFault\(false\)\.isEmpty\(\),/); assert.match(guard,/return previouslyArmed && sameDeviceEpoch && outputArmSafe && !streamArmed/); assert.match(bridge,/action:"routingSourceSwitch"/); @@ -299,7 +302,7 @@ test("P0 VST3 preparation runs with old live PCM; monitor closes only at publica assert.match(lab,/const auto epochAtPublish=deviceEpoch_\.load/); assert.match(lab,/next,formats,sampleRate,deviceFrames,true,nullptr,\s*beforePublish/); assert.match(engine,/bool enteredPublication=false/); - assert.match(engine,/enteredPublication=true;\s*if\(wasMonitoring\)setOutputMuted\(true\)/); + assert.match(engine,/enteredPublication=true;[\s\S]*?if\(wasMonitoring\)\s*topologyPublicationMute_\.store\(true,std::memory_order_release\)/); assert.match(engine,/if\(!enteredPublication\)return error/); assert.match(engine,/return finishGuardedDryTopology\(/); assert.match(engine,/return applyGuardedDryTopology\(epoch,frames,\[&\]\(const auto& beforePublish\)/); From d6e34182b0f4ab9cf514dfc77a6c48a964f0d529 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:51:04 +0700 Subject: [PATCH 070/219] fix(P0): make WIRE ROUTE_ONLY to MAIN an exclusive native PCM route with verified edge identity --- engine/core/DynamicChannelRoster.h | 22 ++++++++++--- integration/ApprovedNativeControlIntent.h | 7 ++-- tests/approved_native_v8_projection_test.cpp | 23 +++++++++++++ tests/dynamic_accepted_session_test.cpp | 34 ++++++++++++++++++++ web/approved-native-bridge.js | 11 ++++--- 5 files changed, 84 insertions(+), 13 deletions(-) diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index 3b435432d..c8712ef62 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -390,19 +390,31 @@ class DynamicChannelRoster final { } if(!op.to.value || op.to==op.from || !std::isfinite(op.gain) || op.gain<0.f || op.gain>4.f || - (op.kind==WireChange::Kind::routeOnly && op.to==mainId)){ + (op.kind==WireChange::Kind::routeOnly && op.gain!=1.f)){ result.fault=ChannelEditFault::invalidValue;break; } - const bool already=std::any_of(sends.begin(),sends.end(), + const auto existing=std::find_if(sends.begin(),sends.end(), [&](const auto& s){return s.destination==op.to;}); - if(already && op.kind==WireChange::Kind::connect){ + if(existing!=sends.end() && op.kind==WireChange::Kind::connect){ result.fault=ChannelEditFault::duplicateSend;break; } if(op.kind==WireChange::Kind::routeOnly){ + // ROUTE_ONLY is an exclusive primary OUT choice, including + // MAIN. Replace the previous primary destination (MAIN or + // GROUP), but preserve other deliberate parallel SENDs. sends.erase(std::remove_if(sends.begin(),sends.end(), - [&](const auto& s){return s.destination==mainId;}), + [&](const auto& s){return s.primaryOutput && + s.destination!=op.to;}), sends.end()); - if(already)continue; // retain original edgeId/gain + const auto target=std::find_if(sends.begin(),sends.end(), + [&](const auto& s){return s.destination==op.to;}); + if(target!=sends.end()){ + // Promote the EXACT existing EdgeId to primary instead + // of doubling a parallel SEND in the accepted PCM. + target->primaryOutput=true; + target->gain=1.f;target->preFader=false;target->pan=0.f; + continue; + } } if(sends.size()>=budget_.maximumSendsPerChannel){ result.fault=ChannelEditFault::budgetExceeded;break; diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index 792ea1f21..8583585cd 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -143,10 +143,9 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( if(!nativeFound || (role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN")) return reject("WIRE_UNSUPPORTED_DESTINATION"); - // The roster's ROUTE_ONLY decoder explicitly forbids MAIN; - // choosing MAIN requires a native primary-output operation. - if(kind=="ROUTE_ONLY"&&role=="MAIN") - return reject("WIRE_MAIN_PRIMARY_REQUIRED"); + // MAIN is a supported ROUTE_ONLY target: the roster makes + // exactly one serial unity-gain primary edge, no double dry. + item->setProperty("to",to); } if(kind=="CONNECT" || kind=="ROUTE_ONLY") { diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index d021c0bf1..5136a9da4 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -296,6 +296,25 @@ static void approvedWireTranslationRegression(const juce::var& canonical, assert(native.applied[0].kind==armix::mixer::WireChange::Kind::remove); assert(native.applied[0].from.value==9007199254740993ULL); assert(native.applied[0].edgeId==9223372036854775808ULL); + // The accepted ChannelId MAIN is a valid ROUTE_ONLY target from a + // real UI OUT gesture (even though the decoder formerly rejected it). + auto reconnect=juce::JSON::parse(juce::JSON::toString(original,false)); + auto wire=std::make_unique(); + wire->setProperty("op","ROUTE_ONLY"); + wire->setProperty("from",id); + wire->setProperty("to","18446744073709551615"); + wire->setProperty("tap","POST_FADER"); + wire->setProperty("gainLinear",1.0); + juce::Array reconnectChanges; + reconnectChanges.add(juce::var(wire.release())); + reconnect.getProperty("payload",{}).getDynamicObject() + ->setProperty("changes",juce::var(reconnectChanges)); + auto back=translateApprovedNativeControl(reconnect,accepted,bus); + assert(back.ok()); + assert(executeApprovedNativeControl(native,back.translated)); + assert(native.applied.size()==1); + assert(native.applied.front().kind==armix::mixer::WireChange::Kind::routeOnly); + assert(native.applied.front().to.value==18446744073709551615ULL); auto fail=[&](juce::var intent,juce::var acceptedState,juce::var nativeState){ const auto before=juce::JSON::toString(nativeState,false); @@ -319,6 +338,10 @@ static void approvedWireTranslationRegression(const juce::var& canonical, noNative.getDynamicObject()->setProperty("supportedOps", juce::var(juce::Array{})); assert(fail(original,accepted,noNative)=="NATIVE_WIRE_NOT_ADMITTED"); + auto fractionalMain=juce::JSON::parse(juce::JSON::toString(reconnect,false)); + fractionalMain.getProperty("payload",{}).getProperty("changes",{})[0] + .getDynamicObject()->setProperty("gainLinear",0.8); + assert(fail(fractionalMain,accepted,bus)=="WIRE_UNSUPPORTED_TAP_OR_GAIN"); auto invalidTap=juce::JSON::parse(juce::JSON::toString(original,false)); auto edit=invalidTap.getProperty("payload",{}).getProperty("changes",{})[0]; edit.getDynamicObject()->setProperty("op","CONNECT"); diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index 85ea292fe..72621d58e 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -355,6 +355,40 @@ static void verifyAtomicWireTransactionAndZeroSampleHops() { assert(a.ok() && a.graphRevision==7); assert(findEdge(one,main,7)==chainId && !findEdge(one,two,7)); assert(render() && near(left[11],.3f*center)); + + // MAIN is a valid ROUTE_ONLY destination while the physical output is + // armed. GROUP -> MAIN is one exclusive path, never double dry PCM. + a=session.wireTransaction(7,7,hop1,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==8); + assert(!findEdge(one,main,8) && findEdge(one,two,8)); + assert(render() && near(left[11],.3f*center)); + // Deliberately connect an independent 40%-gain parallel send to MAIN. + const std::array parallelMain{connect(one,main,.4f)}; + a=session.wireTransaction(8,8,parallelMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==9); + const auto parallelEdge=findEdge(one,main,9); + assert(parallelEdge && findEdge(one,two,9)); + assert(render() && near(left[11],.3f*1.4f*center,1e-4f)); + // ROUTE_ONLY to MAIN promotes that same EdgeId, removes only the + // previous primary to GROUP, and forces unity post-fader output. + const std::array backToMain{routeOnly(one,main)}; + a=session.wireTransaction(9,9,backToMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==10); + const auto* afterMain=session.acceptedRouting(epoch,10); + assert(afterMain && afterMain->find(one)->primaryOutput==main); + assert(!findEdge(one,two,10) && findEdge(one,main,10)==parallelEdge); + assert(std::count_if(afterMain->edges.begin(),afterMain->edges.end(), + [&](const auto& edge){return edge.from==one;})==1); + assert(render() && near(left[11],.3f*center,1e-4f)); + a=session.wireTransaction(10,10,backToMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==11); + assert(findEdge(one,main,11)==parallelEdge); + assert(render() && near(left[11],.3f*center,1e-4f)); + auto staleMain=session.wireTransaction(10,10,backToMain, + physical,epoch,epoch,false); + assert(staleMain.fault==DynamicAcceptedSession::Fault::staleRoster); + assert(session.acceptedGraphRevision()==11); + assert(render() && near(left[11],.3f*center,1e-4f)); session.unpublish(); session.pollRetirement(); } diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 1dc1588ee..0fdb63338 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -357,7 +357,7 @@ // disconnect ID or remove an unrelated parallel SEND. const edge=current.graph.edges.find(e=>e.enabled && e.from===channelId && e.to===dest && - e.primaryOutput!==false); + e.primaryOutput===true); if(!edge)return false; change={op:"REMOVE",from:channelId,edgeId:edge.edgeId}; } @@ -1835,7 +1835,8 @@ const graphMainRemove=op.type==="REMOVE" && sourceId && current?.admitted===true && current.graph.edges.some(e=>e.enabled&&e.edgeId===edgeId&& - e.from===sourceId&&e.to===current.graph.mainChannelId); + e.from===sourceId&&e.to===current.graph.mainChannelId&& + e.primaryOutput===true); // The approved M4 renderer remains the accepted First Sound owner // if ChannelId projection was not admitted. Verify BOTH an exact UI // PRIMARY edge and the producer's real MAIN readback before removing. @@ -1849,10 +1850,12 @@ e.id===op.edgeId&&e.sourceId===op.sourceId&& e.destId===scope?.master?.id); const isMainRemove=graphMainRemove||m4MainRemove; - if(t&&lane>=0&&(isMainConnect||isMainRemove)){ + // Admitted new ChannelIds after CH10 have no M4 lane ordinal. + if(t&&(lane>=0||(current?.admitted===true&&sourceId))&& + (isMainConnect||isMainRemove)){ const target=isMainRemove?"NONE":"MAIN"; if(requestPrimaryOut(t,target)) - status("CH "+(m4Index(t)+1)+" WIRE → "+ + status(t.name+" WIRE → "+ (target==="MAIN"?"MAIN":"SOURCE ONLY")+ " · native ACK/readback required"); else nativeToast("WIRE MAIN unavailable · verify channel and routing state"); From b10aa7deaa53d30ec232d9c0bc0135d478a1d546 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:52:41 +0700 Subject: [PATCH 071/219] test(P0): require exact primary EdgeId and exclusive native WIRE to MAIN --- tests/approved_native_m2_contract.test.cjs | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 5310a3784..b9ebb8f1b 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -223,7 +223,15 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(bridge,/controller\.intent\("APPLY_WIRE_TRANSACTION",channelId,/); assert.match(bridge,/change=\{op:"ROUTE_ONLY",from:channelId,to:main,/); assert.match(bridge,/change=\{op:"REMOVE",from:channelId,edgeId:edge\.edgeId\}/); - assert.match(bridge,/e\.primaryOutput!==false/); + // Only the accepted PRIMARY edge may be detached. A parallel SEND to + // MAIN must not be misclassified as a physical OUT. + assert.match(bridge,/e\\.primaryOutput===true/); + assert.doesNotMatch(bridge,/e\\.primaryOutput!==false/); + const roster=read("engine/core/DynamicChannelRoster.h"); + const translator=read("integration/ApprovedNativeControlIntent.h"); + assert.match(roster,/target->primaryOutput=true/); + assert.match(roster,/s\\.primaryOutput &&/); + assert.doesNotMatch(translator,/WIRE_MAIN_PRIMARY_REQUIRED/); assert.match(bridge,/const channel=m4Index\(t\)/); // A native-owned MAIN WIRE never triggers the legacy routingChannelPatch. const primary=bridge.slice(bridge.indexOf("function requestPrimaryOut(t,target)"), From 42452c3b7efe44b40921d3f662271a4f159ec16e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:53:07 +0700 Subject: [PATCH 072/219] test(P0): correct literal-dot regex for strict primary WIRE assertions --- tests/approved_native_m2_contract.test.cjs | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index b9ebb8f1b..4c462b325 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -225,12 +225,12 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(bridge,/change=\{op:"REMOVE",from:channelId,edgeId:edge\.edgeId\}/); // Only the accepted PRIMARY edge may be detached. A parallel SEND to // MAIN must not be misclassified as a physical OUT. - assert.match(bridge,/e\\.primaryOutput===true/); - assert.doesNotMatch(bridge,/e\\.primaryOutput!==false/); + assert.match(bridge,/e\.primaryOutput===true/); + assert.doesNotMatch(bridge,/e\.primaryOutput!==false/); const roster=read("engine/core/DynamicChannelRoster.h"); const translator=read("integration/ApprovedNativeControlIntent.h"); assert.match(roster,/target->primaryOutput=true/); - assert.match(roster,/s\\.primaryOutput &&/); + assert.match(roster,/s\.primaryOutput &&/); assert.doesNotMatch(translator,/WIRE_MAIN_PRIMARY_REQUIRED/); assert.match(bridge,/const channel=m4Index\(t\)/); // A native-owned MAIN WIRE never triggers the legacy routingChannelPatch. From 6f84492c9137a23880e5b5cd4bf018a1c43e2db4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 09:58:28 +0700 Subject: [PATCH 073/219] fix(P0): preserve actual live fader/PAN/MUTE/SOLO when adding VST3 or republishing native topology --- src/LiveDryRoutingLab.h | 87 +++++++++++++--------- tests/approved_native_m2_contract.test.cjs | 7 ++ 2 files changed, 58 insertions(+), 36 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 0af4a2bab..8aec495e6 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -510,6 +510,48 @@ class LiveDryRoutingLab final { return {}; } + // SINGLE CONTROL-thread control-state inheritance used by BOTH SOURCE/ + // OUT edits and vendor VST3 insertion. An FX add must not recompile an + // earlier APPLY's fader/PAN/MUTE/SOLO into the already-audible PCM. + // This copies authoritative M4 controls, or the actual ChannelId roster + // while ChannelId owns PCM; it never borrows a browser/demo state. + juce::String inheritLiveControlsForRecompile(juce::var& staged, + std::uint64_t expectedEpoch) const { + auto stagedRows=staged.getProperty("channels",juce::var()); + auto* editable=stagedRows.getArray(); + if(!editable||editable->size()!=count) + return "malformed accepted native channel topology"; + const bool nativeControls=channelIdPhysicalPcmActive(); + if(nativeControls && (nativeStructureLive_ || + nativeAccepted_.deviceEpoch!=expectedEpoch)) + return "incompatible ChannelId roster or stale device epoch"; + for(int i=0;igetReference(i).getDynamicObject(); + if(!row)return "missing accepted native channel"; + const auto& c=channelEdits_[i]; + const auto* accepted=nativeControls + ?nativeAccepted_.graph.roster.find(nativeAccepted_.graph.ids.inputs[i]) + :nullptr; + if(nativeControls && (!accepted || + accepted->role!=armix::mixer::ChannelRole::input)) + return "admitted input channel roster is stale"; + const armix::mixer::NativeTopologyEditSafety::MixSnapshot legacy{ + c.linear,c.pan,c.mute,c.solo}; + const armix::mixer::NativeTopologyEditSafety::MixSnapshot native{ + accepted?accepted->faderLinear:c.linear, + accepted?accepted->pan:c.pan, + accepted?accepted->mute:c.mute, + accepted?accepted->solo:c.solo}; + const auto kept=armix::mixer::NativeTopologyEditSafety::preserveAcceptedMix( + legacy,native,nativeControls); + row->setProperty("gain",static_cast(kept.linear)); + row->setProperty("pan",static_cast(kept.pan)); + row->setProperty("mute",kept.mute); + row->setProperty("solo",kept.solo); + } + return {}; + } + // Native /preview/ FX picker: append one catalog-verified stereo VST3 to // the SAME accepted ten-channel/4AUX renderer. This is a prepared graph // transaction on JUCE CONTROL, never a JS plugin or RT instantiation. @@ -527,6 +569,12 @@ class LiveDryRoutingLab final { juce::JSON::toString(sourceTemplate_,false)); if(!command.isObject()) return "FX INSERT: accepted source template cannot be cloned"; + // A vendor plugin prepare happens AFTER live native fader/PAN edits. + // Recompile from the last accepted operator controls, not the stale + // pre-fader sourceTemplate_ values. Rejection keeps the old PCM live. + const auto inherited=inheritLiveControlsForRecompile( + command,expectedEpoch); + if(inherited.isNotEmpty())return "FX INSERT: "+inherited; auto next=acceptedFxSelections_; next[lane][slot]=chosen; return apply(command,directPermitted,independentClock,occupiedCh1Fx, @@ -799,42 +847,9 @@ class LiveDryRoutingLab final { juce::AudioPluginFormatManager& formats,double sampleRate, int deviceFrames, const std::function& beforePublish={}) { - auto stagedRows=staged.getProperty("channels",juce::var()); - auto* editable=stagedRows.getArray(); - if(!editable||editable->size()!=count) - return "CHANNEL PATCH: malformed native topology"; - // ChannelId gestures are authoritative once admitted. M4's saved - // channelEdits_ may be older; copy ACTUAL accepted roster controls - // into the recompiled M4 fallback so a SOURCE/OUT edit never changes - // a singer's last fader, pan, mute or solo setting. - const bool nativeControls=channelIdPhysicalPcmActive(); - if(nativeControls && (nativeStructureLive_ || - nativeAccepted_.deviceEpoch!=expectedEpoch)) - return "CHANNEL PATCH: incompatible native roster"; - for(int i=0;igetReference(i).getDynamicObject(); - if(!row)return "CHANNEL PATCH: missing native channel"; - const auto& c=channelEdits_[i]; - const auto* accepted=nativeControls - ?nativeAccepted_.graph.roster.find(nativeAccepted_.graph.ids.inputs[i]) - :nullptr; - if(nativeControls && (!accepted || - accepted->role!=armix::mixer::ChannelRole::input)) - return "CHANNEL PATCH: admitted input roster is stale"; - const armix::mixer::NativeTopologyEditSafety::MixSnapshot legacy{ - c.linear,c.pan,c.mute,c.solo}; - const armix::mixer::NativeTopologyEditSafety::MixSnapshot native{ - accepted?accepted->faderLinear:c.linear, - accepted?accepted->pan:c.pan, - accepted?accepted->mute:c.mute, - accepted?accepted->solo:c.solo}; - const auto preserved=armix::mixer::NativeTopologyEditSafety::preserveAcceptedMix( - legacy,native,nativeControls); - row->setProperty("gain",static_cast(preserved.linear)); - row->setProperty("pan",static_cast(preserved.pan)); - row->setProperty("mute",preserved.mute); - row->setProperty("solo",preserved.solo); - } + const auto inherited=inheritLiveControlsForRecompile( + staged,expectedEpoch); + if(inherited.isNotEmpty())return "CHANNEL PATCH: "+inherited; if(expectedEpoch!=epoch()||expectedRevision!=revision()|| !registryValid_.load(std::memory_order_acquire)) return "CHANNEL PATCH: device changed; previous mix preserved"; diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 4c462b325..ffc7f6b5c 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -314,6 +314,13 @@ test("P0 VST3 preparation runs with old live PCM; monitor closes only at publica assert.match(engine,/if\(!enteredPublication\)return error/); assert.match(engine,/return finishGuardedDryTopology\(/); assert.match(engine,/return applyGuardedDryTopology\(epoch,frames,\[&\]\(const auto& beforePublish\)/); + // FX and SOURCE recompiles must inherit the SAME real active fader, pan, + // mute and solo from native ChannelId or M4 before replacing a graph. + assert.match(lab,/juce::String inheritLiveControlsForRecompile\(/); + assert.match(lab,/juce::String insertCatalogFx[\s\S]*?const auto inherited=inheritLiveControlsForRecompile\(\s*command,expectedEpoch\)/); + assert.match(lab,/juce::String publishRevisedTopology[\s\S]*?const auto inherited=inheritLiveControlsForRecompile\(\s*staged,expectedEpoch\)/); + assert.match(lab,/NativeTopologyEditSafety::preserveAcceptedMix\(/); + assert.match(lab,/case Publisher::Result::applied:[\s\S]*?nativeControlDirty_=false/); }); test("P0 SOURCE, OUT, M-ST and FX share late-gated graph publication",()=>{ const lab=read("src/LiveDryRoutingLab.h"); From 35e61ac32c75e5ccbd74147889531702f13820c3 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 10:28:14 +0700 Subject: [PATCH 074/219] fix(P0): reject stale or fractional native SOURCE switch tokens before PCM mutation --- src/Main.cpp | 19 +++++++++++++++---- tests/approved_native_m2_contract.test.cjs | 16 ++++++++++++++++ 2 files changed, 31 insertions(+), 4 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index ff5ecd958..9c15fd3f2 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1785,13 +1785,24 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto rv=args.getProperty("revision",juce::var()); const int left=static_cast(args.getProperty("left",-1)); const int right=static_cast(args.getProperty("right",-1)); - const juce::String error=requestId>0&&!ep.isVoid()&&!rv.isVoid()&& + // SOURCE uses the SAME exact native session authority as FX, + // OUT and M4. A JUCE JSON double may be an exact integer, but + // fractional/NaN/rounded or stale tokens must never be cast to + // a valid active epoch/revision before changing physical PCM. + const auto nativeRoute=engine_.status().getProperty("dryRoutingLab",{}); + const bool tokens= + armix::console::nativeSessionTokenMatches( + ep,nativeRoute.getProperty("epoch",{})) && + armix::console::nativeSessionTokenMatches( + rv,nativeRoute.getProperty("revision",{})); + const juce::String error=requestId>0 && + channel>=0&&channel(static_cast(ep)), - static_cast(static_cast(rv)), + armix::console::nativeSessionTokenValue(ep), + armix::console::nativeSessionTokenValue(rv), mode,left,right): - juce::String("SOURCE SWITCH: stale request or Show/backup busy"); + juce::String("SOURCE SWITCH: stale native epoch/revision, channel or Show/backup busy"); auto ack=std::make_unique(); ack->setProperty("requestId",requestId); ack->setProperty("channel",channel); diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index ffc7f6b5c..ec9c94f75 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -171,6 +171,22 @@ test("DAW G0 native M4 controls, source clear, OUT & monitoring are real",()=>{ assert.match(builder,/type==='output'/); assert.doesNotMatch(bridge,/AudioContext|AudioWorklet/); }); +test("P0 physical SOURCE switching rejects fractional and stale native session tokens before PCM",()=>{ + const main=read("src/Main.cpp"); + const tokens=read("src/NativeSessionToken.h"); + const start=main.indexOf('if(action=="routingSourceSwitch")'); + const end=main.indexOf('if (action == "routingDryApply")',start); + assert.ok(start>=0&&end>start); + const source=main.slice(start,end); + assert.match(source,/nativeSessionTokenMatches\(/); + assert.match(source,/nativeSessionTokenValue\(ep\)/); + assert.match(source,/nativeSessionTokenValue\(rv\)/); + assert.match(source,/channel>=0&&channel\(ep\)/); + assert.match(tokens,/std::isfinite\(n\)/); + assert.match(tokens,/std::floor\(n\)==n/); +}); test("P0 first Add FX discovers real local VST3 lazily without an audio-thread scan",()=>{ const bridge=read("web/approved-native-bridge.js"); const native=read("src/Main.cpp"); From 2c500993dbcb679cad22e10dd5d96525a513edb5 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 10:48:00 +0700 Subject: [PATCH 075/219] fix(P0): admit verified native WIRE into approved GUI and preserve parallel MAIN send identity --- integration/ApprovedNativeRuntimeSnapshot.h | 9 ++++++-- tests/approved_native_m2_contract.test.cjs | 11 ++++++++++ tests/approved_native_v8_projection_test.cpp | 23 ++++++++++++++++++++ web/approved-native-bridge.js | 7 +++--- 4 files changed, 45 insertions(+), 5 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index aee0ecf1c..573f32998 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -261,8 +261,8 @@ inline bool projectInstalledNativeChannelIdGraph( // Advertise only controls provided by the currently installed and // positively admitted native callback (never inferred from a JSON shape // or the browser). Both the native and public capability are required by - // the stateless control translator. WIRE remains explicitly disabled - // until the native structural dispatcher is independently admitted. + // the stateless control translator. Never invent a WIRE capability; it + // is enabled only by positive native ChannelId PCM readback. juce::Array available; const auto nativeOps=bus.getProperty("supportedOps",{}); const auto* actual=nativeOps.getArray(); @@ -277,6 +277,11 @@ inline bool projectInstalledNativeChannelIdGraph( available.add(juce::String("SET_MUTE")); available.add(juce::String("SET_SOLO")); } + // The installed native publisher already supported WIRE, but the host + // projection discarded it. The GUI then rejected every real BUS/WIRE + // gesture as NOT_ADMITTED. Admit only the actual installed operation. + if(has("NATIVE_APPLY_WIRE_TRANSACTION")) + available.add(juce::String("APPLY_WIRE_TRANSACTION")); const auto graph=snapshot.getProperty("graph",{}); const auto caps=graph.getProperty("capabilities",{}); if (auto* props=caps.getDynamicObject()) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index ec9c94f75..6b2dcdffd 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -230,6 +230,17 @@ test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",( assert.doesNotMatch(bridge,/routingSourceSwitch[^;]+monitor\(false\)/); }); +test("P0 installed ChannelId WIRE capability reaches the GUI",()=>{ + const projection=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const native=read("src/LiveDryRoutingLab.h"); + const bridge=read("web/approved-native-bridge.js"); + assert.match(native,/NATIVE_APPLY_WIRE_TRANSACTION/); + assert.match(projection,/if\(has\("NATIVE_APPLY_WIRE_TRANSACTION"\)\)/); + assert.match(projection,/available\.add\(juce::String\("APPLY_WIRE_TRANSACTION"\)\)/); + assert.match(bridge,/const kind=isPrimary\?"primary"/); + assert.match(bridge,/if \(isPrimary && edge\.gainLinear!==1\)/); + assert.doesNotMatch(bridge,/if \(isMain && edge\.gainLinear!==1\)/); +}); test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",()=>{ const bridge=read("web/approved-native-bridge.js"); const builder=read("scripts/build_approved_native_gui.py"); diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 5136a9da4..ae5b1b361 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -470,6 +470,29 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { assert(graph.getProperty("channels",{}).getArray()->size()==2); assert(graph.getProperty("capabilities",{}) .getProperty("supportedOps",{}).getArray()->isEmpty()); + // Only a real installed callback may advertise WIRE; G0 and producer + // snapshots without the corresponding capability remain fail-closed. + auto wiredBus=juce::JSON::parse(juce::JSON::toString(rawBus,false)); + juce::Array nativeWireOps; + nativeWireOps.add("NATIVE_APPLY_WIRE_TRANSACTION"); + wiredBus.getDynamicObject()->setProperty( + "supportedOps",juce::var(nativeWireOps)); + auto wiredLive=juce::JSON::parse(juce::JSON::toString(live,false)); + wiredLive.getProperty("dryRoutingLab",{}).getDynamicObject() + ->setProperty("nativeBus",wiredBus); + auto wiredSnap=canonicalSnapshot(); + auto* wiredDevice=wiredSnap.getProperty("device",{}).getDynamicObject(); + wiredDevice->setProperty("sampleRate",48000.0); + wiredDevice->setProperty("bufferFrames",256); + wiredDevice->setProperty("enabledInputs",juce::var(inputs)); + wiredDevice->setProperty("enabledOutputs",juce::var(outputs)); + assert(synchronizeApprovedRouteDeviceEpoch(wiredSnap,wiredLive)); + assert(projectInstalledNativeChannelIdGraph(wiredSnap,wiredLive)); + const auto wireCaps=wiredSnap.getProperty("graph",{}) + .getProperty("capabilities",{}).getProperty("supportedOps",{}); + assert(wireCaps.getArray()&& + wireCaps.getArray()->contains("APPLY_WIRE_TRANSACTION")); + assert(!static_cast(wiredSnap.getProperty("productionCallbackLive",false))); assert(!static_cast(snap.getProperty("productionCallbackLive",false))); } diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 0fdb63338..4b2b012d9 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -119,11 +119,12 @@ const source=accepted.channels.find(ch=>ch.id===edge.from); const isMain=edge.to===accepted.mainChannelId; const isPrimary=source?.primaryOutId===edge.to; - const kind=isMain||isPrimary?"primary":edge.tap==="SPLIT_PRE"||edge.tap==="SPLIT_POST"?"split":"send"; + // An independent SEND to MAIN is not the source's primary OUT. + const kind=isPrimary?"primary":edge.tap==="SPLIT_PRE"||edge.tap==="SPLIT_POST"?"split":"send"; const mode=isMain?"postFader":kind==="primary"?"routeOnly": kind==="split"?(edge.tap==="SPLIT_PRE"?"splitPre":"splitPost"):"send"; - if (isMain && edge.gainLinear!==1) return false; - const gainDb=isMain?0:Math.round(Math.max(-60,Math.min(6, + if (isPrimary && edge.gainLinear!==1) return false; + const gainDb=isPrimary?0:Math.round(Math.max(-60,Math.min(6, edge.gainLinear>0?20*Math.log10(edge.gainLinear):-60))*10)/10; let uiId=uiByWireId.get(edge.edgeId); if (uiId===undefined) uiId=scope.allocateWireId(); From ec9d15a29424a2aadfc3ed02c9e30d6127afe76f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 10:53:13 +0700 Subject: [PATCH 076/219] feat(P0): make +Bus and OUT to GROUP real live native ChannelId PCM actions --- integration/ApprovedNativeRuntimeSnapshot.h | 2 + src/LiveAudioEngine.h | 40 +++++++++-- src/LiveDryRoutingLab.h | 6 +- src/Main.cpp | 62 +++++++++++++++++ tests/approved_native_m2_contract.test.cjs | 17 +++++ tests/approved_native_v8_projection_test.cpp | 6 ++ web/approved-native-bridge.js | 72 ++++++++++++++++++-- 7 files changed, 190 insertions(+), 15 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 573f32998..39c9a29bd 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -282,6 +282,8 @@ inline bool projectInstalledNativeChannelIdGraph( // gesture as NOT_ADMITTED. Admit only the actual installed operation. if(has("NATIVE_APPLY_WIRE_TRANSACTION")) available.add(juce::String("APPLY_WIRE_TRANSACTION")); + if(has("NATIVE_CREATE_GROUP_SELECTED")) + available.add(juce::String("CREATE_GROUP")); const auto graph=snapshot.getProperty("graph",{}); const auto caps=graph.getProperty("capabilities",{}); if (auto* props=caps.getDynamicObject()) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index e34a7720e..2345eb033 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1393,18 +1393,44 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const std::string& name,float gain, armix::mixer::ChannelId remove={}) { LiveDryRoutingLab::NativeBusResult rejected; - rejected.error="HARDWARE_NOT_DISARMED"; - if(independent_.active() || !attached_ || + rejected.error="NATIVE_BUS_DEVICE_UNAVAILABLE"; + if(independent_.active() || !attached_ || secondaryOutput_.armed() || !directFence_.permitted() || routeReconfiguring_.load(std::memory_order_acquire) || diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal || - !allOutputsDisarmed() || handoff_.busy() || - fxMovePhase_.load(std::memory_order_acquire)!=0) + handoff_.busy() || fxMovePhase_.load(std::memory_order_acquire)!=0) + return rejected; + const bool wasMonitoring=isMonitorEnabled(); + bool publishing=false; + try { + const auto result=dryRoutingLab_.editNativeBus( + epoch,pcmRevision,rosterRevision,role,selected, + name,gain,remove,true,[&] { + publishing=true; + // User must not have to toggle MONITOR for an ordinary + // Add BUS. A late output gate covers only publication. + if(wasMonitoring)topologyPublicationMute_.store( + true,std::memory_order_release); + }); + if(publishing) { + if(wasMonitoring && + !armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + wasMonitoring,epoch==dryRoutingLab_.epoch(), + liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed())) + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + return result; + } catch(...) { + if(publishing) { + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + rejected.error="NATIVE_BUS_PUBLICATION_EXCEPTION"; return rejected; - return dryRoutingLab_.editNativeBus( - epoch,pcmRevision,rosterRevision,role,selected, - name,gain,remove,true); + } } // User-owned VST3 on a true dynamic ChannelId. Instantiation/scan/layout // work is CONTROL only; the callback receives an immutable fx lease. diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 8aec495e6..6b6052825 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1357,7 +1357,8 @@ class LiveDryRoutingLab final { std::span selection, const std::string& name,float sendGain, armix::mixer::ChannelId remove={}, - bool outputsDisarmed=false) { + bool outputsDisarmed=false, + const std::function& beforePublish={}) { using namespace armix::mixer; NativeBusResult reply{}; reply.pcmRevision=nativeAccepted_.pcmRevision; @@ -1419,6 +1420,9 @@ class LiveDryRoutingLab final { }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; + // Keep old PCM running throughout candidate validation/FX lease + // reuse, and briefly gate hardware only at native publication. + if(beforePublish)beforePublish(); const auto published=nativePublisher_.commit( next,nativeAccepted_.graph.request,expectedPcmRevision, expectedEpoch,epoch(),true,std::move(fx)); diff --git a/src/Main.cpp b/src/Main.cpp index 9c15fd3f2..46fe3bdcb 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2007,6 +2007,68 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return; } + // Real DAW + BUS from the approved Windows GUI. The engine creates + // and publishes a stereo GROUP directly in its sole ChannelId PCM + // owner; no browser-only track or legacy M4 shadow is created. + if(action=="routingNativeBusCreate") { + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawEp=args.getProperty("deviceEpoch",{}); + const auto rawRev=args.getProperty("graphRevision",{}); + const auto rawRoster=args.getProperty("rosterRevision",{}); + std::uint64_t ep=0,rev=0,roster=0; + const auto live=engine_.status(); + const auto lab=live.getProperty("dryRoutingLab",{}); + const auto native=lab.getProperty("nativeBus",{}); + const auto before=approvedNativeSnapshot(live); + const auto caps=before.getProperty("graph",{}) + .getProperty("capabilities",{}).getProperty("supportedOps",{}); + const bool admitted=caps.isArray()&& + caps.getArray()->contains("CREATE_GROUP"); + const bool valid=request.startsWith("bus-")&& + request.length()<=64 && + !acceptedControlRequests_.contains(request)&& + armix::console::approvedNativeId(rawEp,ep)&& + armix::console::approvedNativeId(rawRev,rev)&& + armix::console::approvedNativeId(rawRoster,roster)&& + ep==engine_.dryRoutingLabEpoch() && + native.getProperty("graphRevision","").toString()==rawRev.toString() && + native.getProperty("rosterRevision","").toString()==rawRoster.toString() && + admitted && !nativeShowBusy_ && !studioBackupBusy_; + LiveDryRoutingLab::NativeBusResult result; + result.error="NATIVE_BUS_NOT_ADMITTED_OR_STALE"; + if(valid) { + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + int count=0; + const auto channels=native.getProperty("channels",{}); + if(const auto* rows=channels.getArray()) + for(const auto& row:*rows) + if(row.getProperty("role","").toString()=="GROUP")++count; + const std::string name="Bus "+std::to_string(count+1); + result=engine_.editNativeBus(ep,rev,roster, + armix::mixer::ChannelRole::group, + std::span{},name,1.f); + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("ok",valid&&result.accepted); + ack->setProperty("error",result.error?result.error:"NATIVE_BUS_UNKNOWN"); + ack->setProperty("createdId",result.accepted? + juce::String(std::to_string(result.created.value)):juce::String()); + ack->setProperty("graphRevision", + juce::String(std::to_string(result.pcmRevision))); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible( + "arMixNativeBusAck",juce::var(ack.release())); + if(valid&&result.accepted) + diagnostics_.record("NATIVE_DAW_BUS", + "Created real ChannelId GROUP with MAIN output"); + else emitNotice("Add BUS rejected: "+ + juce::String(result.error?result.error:"native error"),true); + return; + } + // G5C native per-instance BYPASS never recompiles the graph and // does not require muting the output. All identity gates must agree. if (action == "routingFxBypass") { diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 6b2dcdffd..8ff587c62 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -230,6 +230,23 @@ test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",( assert.doesNotMatch(bridge,/routingSourceSwitch[^;]+monitor\(false\)/); }); +test("P0 actual Add BUS reaches the live ChannelId graph",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const host=read("src/Main.cpp"); + const engine=read("src/LiveAudioEngine.h"); + const lab=read("src/LiveDryRoutingLab.h"); + const projection=read("integration/ApprovedNativeRuntimeSnapshot.h"); + assert.match(bridge,/function requestNativeBusCreate\(\)/); + assert.match(bridge,/action:"routingNativeBusCreate"/); + assert.match(bridge,/target.id==="addBus"/); + assert.match(bridge,/arMixNativeBusAck/); + assert.match(bridge,/addBus.hidden=!nativeAdmitted/); + assert.match(host,/if\(action=="routingNativeBusCreate"\)/); + assert.match(host,/engine_\.editNativeBus\(ep,rev,roster,/); + assert.match(engine,/topologyPublicationMute_\.store\(/); + assert.match(lab,/if\(beforePublish\)beforePublish\(\)/); + assert.match(projection,/available\.add\(juce::String\("CREATE_GROUP"\)\)/); +}); test("P0 installed ChannelId WIRE capability reaches the GUI",()=>{ const projection=read("integration/ApprovedNativeRuntimeSnapshot.h"); const native=read("src/LiveDryRoutingLab.h"); diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index ae5b1b361..11a7cded0 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -492,6 +492,12 @@ static void installedCallbackAdmissionRegression(const juce::var& rawBus) { .getProperty("capabilities",{}).getProperty("supportedOps",{}); assert(wireCaps.getArray()&& wireCaps.getArray()->contains("APPLY_WIRE_TRANSACTION")); + nativeWireOps.add("NATIVE_CREATE_GROUP_SELECTED"); + wiredBus.getDynamicObject()->setProperty( + "supportedOps",juce::var(nativeWireOps)); + assert(projectInstalledNativeChannelIdGraph(wiredSnap,wiredLive)); + assert(wiredSnap.getProperty("graph",{}).getProperty("capabilities",{}) + .getProperty("supportedOps",{}).getArray()->contains("CREATE_GROUP")); assert(!static_cast(wiredSnap.getProperty("productionCallbackLive",false))); assert(!static_cast(snap.getProperty("productionCallbackLive",false))); } diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 4b2b012d9..8e20ebfbe 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -344,14 +344,18 @@ if(!current?.admitted || !channelId || !ch || !main || !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION") || !["INPUT","GROUP","FX_RETURN"].includes(ch.role) || - (target!=="MAIN"&&target!=="NONE"))return false; + !target)return false; + const group=current.graph.channels.find(row=> + row.role==="GROUP"&&row.name===target); + const to=target==="MAIN"?main:group?.id||null; + if(target!=="NONE"&&!to)return false; const dest=ch.primaryOutId||null; - if((target==="MAIN"&&dest===main)||(target==="NONE"&&!dest)){ + if((to&&dest===to)||(target==="NONE"&&!dest)){ controller.subscribe();return true; } let change; - if(target==="MAIN"){ - change={op:"ROUTE_ONLY",from:channelId,to:main, + if(to){ + change={op:"ROUTE_ONLY",from:channelId,to, tap:"POST_FADER",gainLinear:1}; }else{ // Exact EdgeId from the independent native readback; never invent a @@ -366,7 +370,7 @@ {changes:[change]}); if(!accepted.ok){status("Native OUT rejected · "+accepted.error);return false;} window.setTimeout(()=>controller?.expire(accepted.requestId),8000); - status(t.name+" OUT → "+(target==="MAIN"?"MAIN":"NONE")+ + status(t.name+" OUT → "+(target==="NONE"?"SOURCE ONLY":target)+ " · native PCM readback pending"); return true; } @@ -402,6 +406,33 @@ },8000); return true; } + let pendingBusCreate=null,busRequestSerial=0; + function requestNativeBusCreate(){ + const accepted=controller?.state()?.current; + const session=mixerSession(); + const capabilities=accepted?.graph?.capabilities?.supportedOps; + if(pendingBusCreate||session?.authority!=="CHANNEL_ID"|| + !accepted?.admitted||!Array.isArray(capabilities)|| + !capabilities.includes("CREATE_GROUP")){ + nativeToast("BUS needs the verified native ChannelId graph"); + return false; + } + const requestId="bus-"+(++busRequestSerial); + pendingBusCreate={requestId}; + backend.emitEvent("arMixAction",{ + action:"routingNativeBusCreate",requestId, + deviceEpoch:accepted.device.epoch, + graphRevision:accepted.graph.revision, + rosterRevision:accepted.graph.rosterRevision}); + status("Adding a real stereo BUS → MAIN · native PCM pending"); + window.setTimeout(()=>{ + if(pendingBusCreate?.requestId!==requestId)return; + pendingBusCreate=null; + status("Add BUS timed out · old PCM kept"); + controller?.subscribe(); + },8000); + return true; + } let pendingFxInsert=null,fxRequestSerial=0,nativeCatalog=new Map(); let nativeFxDiscoveryRequested=false,nativeFxCatalogScanning=false; // Lazy USER-triggered discovery: the first Add FX opens immediately and @@ -1345,6 +1376,12 @@ const caps=next?.graph?.capabilities; const nativeAdmitted=session.authority==="CHANNEL_ID" && next.admitted && caps?.callbackOwnsChannelIds===true; + const addBus=document.getElementById("addBus"); + if(addBus){ + addBus.hidden=!nativeAdmitted || + !caps?.supportedOps?.includes("CREATE_GROUP"); + addBus.disabled=!!pendingBusCreate; + } if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; lastPaintedSignature="";lastNativeTopologySignature=""; @@ -1422,6 +1459,15 @@ finally{profiler.sample("nativeSnapshotJsMs",performance.now()-started);} }); backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); + backend.addEventListener("arMixNativeBusAck",ack=>{ + if(!pendingBusCreate||pendingBusCreate.requestId!==ack?.requestId)return; + pendingBusCreate=null; + if(ack.ok===true && typeof ack.createdId==="string" && + /^[1-9]\\d*$/.test(ack.createdId)) + status("BUS accepted by native PCM · verifying later graph readback"); + else nativeToast("Add BUS rejected · "+(ack?.error||"native graph error")); + controller?.subscribe(); + }); backend.addEventListener("arMixNativeFxPowerAck",ack=>{ const p=pendingNativeFxPower; if(!p||ack?.requestId!==p.requestId)return; @@ -1637,7 +1683,12 @@ // M4 accepts MAIN or source-only. Bus routing is via native WIRE, // never pretend the demo's other destinations have native PCM. const options=["Master","SOURCE ONLY (No Main)"]; - if(t.output && !options.includes(t.output))options.push(t.output); + const graph=controller?.state()?.current?.graph; + if(mixerSession()?.authority==="CHANNEL_ID"&&graph?.channels) + for(const bus of graph.channels) + if(bus.role==="GROUP"&&bus.name && + !options.includes(bus.name))options.push(bus.name); + if(t.output&&!options.includes(t.output))options.push(t.output); return options; } return [t?.output||"None"]; @@ -1679,8 +1730,12 @@ if(t.kind==="master"){ el.value=t.output;openNativeAudioIO();return true; } + const graph=controller?.state()?.current?.graph; + const bus=graph?.channels?.find(ch=> + ch.role==="GROUP"&&ch.name===el.value); const target=el.value==="Master"?"MAIN": - el.value==="SOURCE ONLY (No Main)"?"NONE":null; + el.value==="SOURCE ONLY (No Main)"?"NONE": + bus?bus.name:null; // No optimistic GUI state. Both this menu and the WIRE jack use // the same ID/epoch-guarded, acknowledged native route transaction. if(el.value!==t.output && !requestPrimaryOut(t,target)){ @@ -1991,6 +2046,9 @@ status("PLUGIN MANAGER · "+action+" requested from native JUCE"); return; } + if(target.id==="addBus"){ + requestNativeBusCreate();return; + } status("NATIVE: "+target.id+" requires admitted engine operation"); },true); // Native fader is committed exactly once INSIDE the original GUI's From f256124d239ace354f685d099d7ee32301c7d92b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 10:54:54 +0700 Subject: [PATCH 077/219] test(P0): enforce BUS-specific WIRE destination and exact native bus ACK ID --- tests/approved_native_m2_contract.test.cjs | 3 ++- web/approved-native-bridge.js | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 8ff587c62..f80416e1a 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -265,7 +265,8 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(bridge,/function requestPrimaryOut\(t,target\)/); assert.match(bridge,/session\?\.authority==="CHANNEL_ID"/); assert.match(bridge,/controller\.intent\("APPLY_WIRE_TRANSACTION",channelId,/); - assert.match(bridge,/change=\{op:"ROUTE_ONLY",from:channelId,to:main,/); + assert.match(bridge,/const to=target==="MAIN"\?main:group\?\.id\|\|null/); + assert.match(bridge,/change=\{op:"ROUTE_ONLY",from:channelId,to,/); assert.match(bridge,/change=\{op:"REMOVE",from:channelId,edgeId:edge\.edgeId\}/); // Only the accepted PRIMARY edge may be detached. A parallel SEND to // MAIN must not be misclassified as a physical OUT. diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 8e20ebfbe..829122fc1 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1463,7 +1463,7 @@ if(!pendingBusCreate||pendingBusCreate.requestId!==ack?.requestId)return; pendingBusCreate=null; if(ack.ok===true && typeof ack.createdId==="string" && - /^[1-9]\\d*$/.test(ack.createdId)) + /^[1-9]\d*$/.test(ack.createdId)) status("BUS accepted by native PCM · verifying later graph readback"); else nativeToast("Add BUS rejected · "+(ack?.error||"native graph error")); controller?.subscribe(); From 882ad9ee9781bab2ce15edd8921d70341a8bd47b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 10:58:35 +0700 Subject: [PATCH 078/219] feat(engine): prepare VST3 once and atomically publish live ChannelId FX without MONITOR off --- engine/core/DynamicNativeSessionPublisher.h | 15 +++++-- integration/ApprovedNativeControlIntent.h | 44 +++++++++++++++++++++ integration/ApprovedNativeRuntimeSnapshot.h | 2 + src/LiveAudioEngine.h | 2 +- src/LiveDryRoutingLab.h | 8 ++-- 5 files changed, 63 insertions(+), 8 deletions(-) diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index c767600af..b9e4f66cf 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -68,7 +68,8 @@ class DynamicNativeSessionPublisher final { std::uint64_t proposedDeviceEpoch, std::uint64_t activeDeviceEpoch, bool allOutputsDisarmed, - FxPlan fx={},bool verifiedInternalWireOnly=false) { + FxPlan fx={},bool verifiedInternalWireOnly=false, + bool verifiedInternalFxOnly=false) { CommitResult report;report.revision=publisher_.lastRevision(); if(!fx.valid() || (fx.owner && (fx.deviceEpoch!=proposedDeviceEpoch || @@ -83,9 +84,15 @@ class DynamicNativeSessionPublisher final { expectedRevision==std::numeric_limits::max()) { report.fault=Fault::staleRevision;return report; } - // Only the canonical native WIRE owner may attest unchanged - // physical patch / device epoch. Other structural edits disarm. - if(!allOutputsDisarmed && !verifiedInternalWireOnly) { + // A zero-latency vendor FX lease can be prepared off-RT and + // published on the SAME physical device/patch as the existing + // ChannelId graph. Neither WIRE nor this in-place FX edit can + // change physical pins. Other structural edits still disarm. + if(verifiedInternalFxOnly && !fx.owner) { + report.fault=Fault::invalidCandidate;return report; + } + if(!allOutputsDisarmed && !verifiedInternalWireOnly && + !verifiedInternalFxOnly) { report.fault=Fault::outputArmed;return report; } auto next=std::make_unique(); diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index 8583585cd..fb47e9386 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -171,6 +171,50 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( converted->setProperty("payload",juce::var(payload.release())); return {juce::var(converted.release()),{}}; } + if(op=="LOAD_INSERT") { + // Native-accepted ChannelId + catalog identity + exact next slot. + // Device/graph/roster were already independently compared above. + if(!approvedHasOperation(caps.getProperty("supportedOps",{}),"LOAD_INSERT") || + !approvedHasOperation(installedBus.getProperty("supportedOps",{}), + "NATIVE_LOAD_INSERT")) + return reject("NATIVE_VST3_NOT_ADMITTED"); + juce::var ch,nativeCh; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())ch=row; + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())nativeCh=row; + const auto role=ch.getProperty("role","").toString(); + if(!ch.isObject()||!nativeCh.isObject()|| + role!=nativeCh.getProperty("role","").toString()|| + (role!="INPUT"&&role!="GROUP")) + return reject("NATIVE_VST3_TARGET_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto catalog=payload.getProperty("catalogId",{}); + const auto slot=payload.getProperty("slot",{}); + const auto publicFx=ch.getProperty("inserts",{}); + const auto nativeFx=nativeCh.getProperty("inserts",{}); + if(!payload.isObject()||!catalog.isString()|| + catalog.toString().isEmpty()|| + catalog.toString().getNumBytesAsUTF8()>256|| + !slot.isInt()||static_cast(slot)<0|| + static_cast(slot)>=8|| + !publicFx.isArray()||!nativeFx.isArray()|| + publicFx.getArray()->size()!=static_cast(slot)|| + nativeFx.getArray()->size()!=static_cast(slot)) + return reject("NATIVE_VST3_SLOT_OR_CATALOG_INVALID"); + auto args=std::make_unique(); + args->setProperty("catalogId",catalog); + args->setProperty("slot",slot); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_LOAD_INSERT"); + converted->setProperty("payload",juce::var(args.release())); + return {juce::var(converted.release()),{}}; + } if(op!="SET_FADER" && op!="SET_PAN" && op!="SET_MUTE" && op!="SET_SOLO")return reject("UNSUPPORTED_APPROVED_CONTROL"); // Both native *and* GUI-side capabilities must be explicitly advertised diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 39c9a29bd..69753dcd6 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -282,6 +282,8 @@ inline bool projectInstalledNativeChannelIdGraph( // gesture as NOT_ADMITTED. Admit only the actual installed operation. if(has("NATIVE_APPLY_WIRE_TRANSACTION")) available.add(juce::String("APPLY_WIRE_TRANSACTION")); + if(has("NATIVE_LOAD_INSERT")) + available.add(juce::String("LOAD_INSERT")); if(has("NATIVE_CREATE_GROUP_SELECTED")) available.add(juce::String("CREATE_GROUP")); const auto graph=snapshot.getProperty("graph",{}); diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 2345eb033..b9cc701b2 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1442,7 +1442,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback fail.error="NATIVE_VST3_HOST_UNAVAILABLE"; auto* device=deviceManager_.getCurrentAudioDevice(); if(independent_.active()||!attached_||!device|| - !directFence_.permitted()||!allOutputsDisarmed()|| + !directFence_.permitted()||secondaryOutput_.armed()|| handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0|| routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire)!= diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 6b6052825..5fe0fdbda 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1251,7 +1251,7 @@ class LiveDryRoutingLab final { std::uint64_t expectedRosterRevision,armix::mixer::ChannelId target, const juce::String& catalogId, armix::mixer::DynamicChannelFxLeaseBank::Lease processor, - bool outputsDisarmed=false) { + bool verifiedPreparedLiveInsert=false) { using namespace armix::mixer; NativeBusResult out{}; out.pcmRevision=nativeAccepted_.pcmRevision; @@ -1262,7 +1262,9 @@ class LiveDryRoutingLab final { expectedPcmRevision!=nativeAccepted_.pcmRevision|| expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) return out; - if(!outputsDisarmed) {out.error="OUTPUT_MUST_BE_DISARMED";return out;} + if(!verifiedPreparedLiveInsert) { + out.error="NATIVE_INSERT_REQUIRES_PREPARED_INTERNAL_FX";return out; + } const auto* current=nativeAccepted_.graph.roster.find(target); if(!current || (current->role!=ChannelRole::input && current->role!=ChannelRole::group)) { @@ -1308,7 +1310,7 @@ class LiveDryRoutingLab final { fx.graphRevision=expectedPcmRevision+1; const auto published=nativePublisher_.commit( next,nativeAccepted_.graph.request,expectedPcmRevision, - expectedEpoch,epoch(),true,std::move(fx)); + expectedEpoch,epoch(),false,std::move(fx),false,true); if(!published.ok()) { out.error="NATIVE_VST3_PCM_COMMIT_REJECTED";return out; } From 346c5a51c70b79e8e532d75de0b08fe854d6a10d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 11:00:02 +0700 Subject: [PATCH 079/219] feat(mixer): connect Add FX to native ChannelId publisher and exact VST3 ACK/readback --- src/Main.cpp | 39 ++++++++++++++++++-- tests/approved_native_m2_contract.test.cjs | 25 +++++++++++++ web/approved-native-bridge.js | 42 +++++++++++++++++++++- web/approved-native-contract.js | 7 ++++ 4 files changed, 110 insertions(+), 3 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 46fe3bdcb..db2d81252 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -890,8 +890,42 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } const auto translated=armix::console::translateApprovedNativeControl( request,before,installedBus); - const bool applied=!replay&&translated.ok()&& - armix::console::executeApprovedNativeControl(engine_,translated.translated); + bool applied=false; + juce::String nativeError; + if(!replay&&translated.ok()) { + const auto command=translated.translated; + if(command.getProperty("operation","").toString()=="NATIVE_LOAD_INSERT") { + // Exactly one catalog-resolved vendor processor from the + // installed native library. No browser path, ordinal M4 + // fallback, secondary DSP or user-visible MONITOR ritual. + const auto args=command.getProperty("payload",{}); + const auto catalogId=args.getProperty("catalogId","").toString(); + const auto* plugin=catalog_.find(catalogId); + std::uint64_t ep=0,rev=0,roster=0,target=0; + if(!plugin||catalog_.busy()||nativeShowBusy_|| + studioBackupBusy_||engine_.isGraphSwitchPending()) { + nativeError="NATIVE_VST3_CATALOG_OR_HOST_BUSY"; + } else if(!armix::console::approvedNativeId( + command.getProperty("deviceEpoch",{}),ep) || + !armix::console::approvedNativeId( + command.getProperty("baseGraphRevision",{}),rev) || + !armix::console::approvedNativeId( + command.getProperty("baseRosterRevision",{}),roster) || + !armix::console::approvedNativeId( + command.getProperty("targetChannelId",{}),target)) { + nativeError="NATIVE_VST3_INVALID_SESSION_ID"; + } else { + const auto result=engine_.installNativeVst3( + ep,rev,roster,armix::mixer::ChannelId{target}, + plugin->path,plugin->uid,plugin->key()); + applied=result.accepted && result.error && + result.error[0]==0; + if(!applied)nativeError=result.error; + } + } else { + applied=armix::console::executeApprovedNativeControl(engine_,command); + } + } // An engine setter ACK is not independent PCM evidence. Re-read the // same physical callback authority after mutation before claiming it // was accepted; browser then explicitly requests LATER readback. @@ -909,6 +943,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ack->setProperty("errorCode",nativeStillAdmitted?"NONE": replay?"DUPLICATE_REQUEST_ID": translated.error.isNotEmpty()?translated.error: + nativeError.isNotEmpty()?nativeError: applied?"NATIVE_CALLBACK_LOST":"NATIVE_PCM_MUTATION_REJECTED"); ack->setProperty("deviceEpoch",device.getProperty("epoch","0")); ack->setProperty("graphRevision",graph.getProperty("revision","0")); diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f80416e1a..d8fc464e5 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -187,6 +187,31 @@ test("P0 physical SOURCE switching rejects fractional and stale native session t assert.match(tokens,/std::isfinite\(n\)/); assert.match(tokens,/std::floor\(n\)==n/); }); +test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const main=read("src/Main.cpp"); + const engine=read("src/LiveAudioEngine.h"); + const pub=read("engine/core/DynamicNativeSessionPublisher.h"); + const lab=read("src/LiveDryRoutingLab.h"); + const contract=read("web/approved-native-contract.js"); + const translate=read("integration/ApprovedNativeControlIntent.h"); + const snapshot=read("integration/ApprovedNativeRuntimeSnapshot.h"); + assert.match(bridge,/controller\.intent\("LOAD_INSERT",nativeId,/); + assert.match(bridge,/pendingFxInsert=\{authority:"CHANNEL_ID"/); + assert.match(bridge,/inserted\?\.id===p\.id/); + assert.match(translate,/if\(op==="LOAD_INSERT"\)/); + assert.match(snapshot,/available\.add\(juce::String\("LOAD_INSERT"\)\)/); + assert.match(main,/engine_\.installNativeVst3\(/); + assert.match(contract,/if \(operation === "LOAD_INSERT"\)/); + assert.match(contract,/ch\.inserts\[payload\.slot\]\?\.id===payload\.catalogId/); + assert.match(lab,/epoch\(\),false,std::move\(fx\),false,true\)/); + assert.match(pub,/verifiedInternalFxOnly/); + const install=engine.slice(engine.indexOf("installNativeVst3("), + engine.indexOf("bool bypassNativeVst3(",engine.indexOf("installNativeVst3("))); + assert.doesNotMatch(install,/!allOutputsDisarmed\(\)/); + assert.match(install,/secondaryOutput_\.armed\(\)/); + assert.match(install,/getLatencySamples\(\)!=0/); +}); test("P0 first Add FX discovers real local VST3 lazily without an audio-thread scan",()=>{ const bridge=read("web/approved-native-bridge.js"); const native=read("src/Main.cpp"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 829122fc1..4a263bf09 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1407,6 +1407,16 @@ } flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); + if(pendingFxInsert?.authority==="CHANNEL_ID"){ + const p=pendingFxInsert; + const inserted=next.graph.channels.find(ch=>ch.id===p.channelId) + ?.inserts?.[p.slot]; + if(inserted?.id===p.id){ + pendingFxInsert=null; + scope?.closeNativePicker?.(); + status("VST3 loaded · "+inserted.name+" · native PCM readback verified"); + } + } if(pendingNativeFxPower?.acked){ const p=pendingNativeFxPower; const ch=next.graph.channels.find(x=>x.id===p.channelId); @@ -1434,6 +1444,10 @@ state.lastError!=="NONE" && state.lastError!=="NATIVE_NOT_SUBSCRIBED"; if(failed){ + if(pendingFxInsert?.authority==="CHANNEL_ID"){ + pendingFxInsert=null; + nativeToast("VST3 insert rejected · "+state.lastError); + } for(const [key,edit] of pendingNativeControl) if(edit.authority==="CHANNEL_ID")pendingNativeControl.delete(key); for(const [key,edit] of liveFaderVisualTargets) @@ -1600,7 +1614,8 @@ else status("Native VST3 editor opened"); }); backend.addEventListener("arMixRoutingFxInsertAck",ack=>{ - if(!pendingFxInsert||ack?.requestId!==pendingFxInsert.requestId)return; + if(!pendingFxInsert||pendingFxInsert.authority==="CHANNEL_ID"|| + ack?.requestId!==pendingFxInsert.requestId)return; const p=pendingFxInsert;pendingFxInsert=null; const actual=ack?.state?.fxInstances?.[p.channel]?.[p.slot]; if(ack?.ok===true && actual?.catalogId===p.id && @@ -1968,6 +1983,31 @@ const plugin=nativeCatalog.get(id); const track=scope?.tracks?.find(x=>x.id===target?.channelId); const channel=m4Index(track),slot=Number(target?.slot); + const accepted=controller?.state().current; + const nativeId=nativeIdFor(track); + const nativeCh=accepted?.graph?.channels?.find(ch=>ch.id===nativeId); + if(accepted?.admitted && nativeCh && channel<0) { + if(!plugin || !["INPUT","GROUP"].includes(nativeCh.role) || + !accepted.graph.capabilities.supportedOps.includes("LOAD_INSERT") || + !Number.isInteger(slot)||slot<0||slot>=8 || + !Array.isArray(nativeCh.inserts)||nativeCh.inserts.length!==slot){ + status("VST3 unavailable · select an empty native ChannelId FX slot"); + return true; + } + const request=controller.intent("LOAD_INSERT",nativeId, + {catalogId:id,slot}); + if(!request.ok){status("VST3 rejected · "+request.error);return true;} + pendingFxInsert={authority:"CHANNEL_ID",requestId:request.requestId, + id,channelId:nativeId,slot}; + status(track.name+" · preparing VST3 without stopping MAIN"); + window.setTimeout(()=>{ + if(pendingFxInsert?.requestId!==request.requestId)return; + pendingFxInsert=null; + status("Native VST3 timed out · accepted audio left unchanged"); + controller.subscribe(); + },15000); + return true; + } const ep=safeNativeCounter(hardware?.device?.epoch); const rev=safeNativeCounter(legacy()?.routingRevision); const existing=legacy()?.fxInstances?.[channel]||[]; diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 264fb72b1..ad2b8b6f0 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -116,6 +116,13 @@ if (operation === "SET_MUTE" || operation === "SET_SOLO") return typeof payload.value==="boolean" && ch.controls[operation==="SET_MUTE"?"mute":"solo"]===payload.value; + if (operation === "LOAD_INSERT") + return cmp(next.graph.revision,pending.baseGraphRevision)>0 && + cmp(next.graph.rosterRevision,pending.baseRosterRevision)>0 && + Number.isInteger(payload.slot)&&payload.slot>=0 && + typeof payload.catalogId==="string" && + Array.isArray(ch.inserts)&&ch.inserts.length===payload.slot+1 && + ch.inserts[payload.slot]?.id===payload.catalogId; if (operation !== "APPLY_WIRE_TRANSACTION" || !Array.isArray(payload.changes) || !payload.changes.length) return false; // A structural WIRE transaction must advance the actual PCM graph. From f2e5f5ad66a62a4f3387b9e513dc49c529a7300d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 11:03:16 +0700 Subject: [PATCH 080/219] fix(engine): keep FX inserts live on original CH strips after ChannelId WIRE takeover --- src/LiveDryRoutingLab.h | 13 ++++++++++--- tests/approved_native_m2_contract.test.cjs | 2 ++ web/approved-native-bridge.js | 3 ++- 3 files changed, 14 insertions(+), 4 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 5fe0fdbda..9ef375128 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1270,10 +1270,17 @@ class LiveDryRoutingLab final { current->role!=ChannelRole::group)) { out.error="NATIVE_INSERT_TARGET_UNAVAILABLE";return out; } - // The fixed 10 CH/4 AUX rack remains owned by M4/Show while migrating. - // Never replace or double-render one of its vendor instances. + // Original ten strips use their existing M4 VST rack until native + // BUS/WIRE makes the ChannelId graph structurally authoritative. + // Thereafter new native inserts must attach to the SAME prepared + // ChannelId lease (not to an inactive M4 graph). Special CH1 external + // vendor chain stays isolated until an explicit combined-chain gate: + // appending there would otherwise double-render or hide the old FX. for(const auto id:nativeAccepted_.graph.ids.inputs) - if(id==target){out.error="M4_INSERT_USE_EXISTING_RACK";return out;} + if(id==target && (!nativeStructureLive_ || + nativeAccepted_.fxOwners->externalChannel()==target)) { + out.error="M4_INSERT_USE_EXISTING_RACK";return out; + } if(originalM4Aux(target)){ out.error="M4_INSERT_USE_EXISTING_RACK";return out; } diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index d8fc464e5..36ecdfc7e 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -197,6 +197,8 @@ test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual const translate=read("integration/ApprovedNativeControlIntent.h"); const snapshot=read("integration/ApprovedNativeRuntimeSnapshot.h"); assert.match(bridge,/controller\.intent\("LOAD_INSERT",nativeId,/); + assert.match(bridge,/legacy\(\)\?\.nativeBusStructural===true/); + assert.match(lab,/nativeAccepted_\.fxOwners->externalChannel\(\)==target/); assert.match(bridge,/pendingFxInsert=\{authority:"CHANNEL_ID"/); assert.match(bridge,/inserted\?\.id===p\.id/); assert.match(translate,/if\(op==="LOAD_INSERT"\)/); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 4a263bf09..c9d19de9c 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1986,7 +1986,8 @@ const accepted=controller?.state().current; const nativeId=nativeIdFor(track); const nativeCh=accepted?.graph?.channels?.find(ch=>ch.id===nativeId); - if(accepted?.admitted && nativeCh && channel<0) { + if(accepted?.admitted && nativeCh && + (channel<0 || legacy()?.nativeBusStructural===true)) { if(!plugin || !["INPUT","GROUP"].includes(nativeCh.role) || !accepted.graph.capabilities.supportedOps.includes("LOAD_INSERT") || !Number.isInteger(slot)||slot<0||slot>=8 || From 50d8c7af31258ec3265fed5a1288fc496447f98b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 11:04:26 +0700 Subject: [PATCH 081/219] test(audio): verify native VST3 ChannelId admission rejects stale, invalid or noncontiguous installs --- tests/approved_native_v8_projection_test.cpp | 57 ++++++++++++++++++++ 1 file changed, 57 insertions(+) diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 11a7cded0..db7b7022e 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -257,6 +257,62 @@ struct NativeWireProbe : NativeControlProbe { return {true,""}; } }; +static void approvedNativeVst3LoadContractRegression( + const juce::var& canonical,const juce::var& producer) { + // Native VST3 command admission is independent of a fabricated vendor + // fixture. No processor is created here: the real JUCE host resolves + // the opaque catalog key and the live publisher proves PCM after ACK. + auto accepted=juce::JSON::parse(juce::JSON::toString(canonical,false)); + auto bus=juce::JSON::parse(juce::JSON::toString(producer,false)); + juce::Array pubOps,nativeOps; + pubOps.add("LOAD_INSERT"); + nativeOps.add("NATIVE_LOAD_INSERT"); + accepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(pubOps)); + bus.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + auto payload=std::make_unique(); + payload->setProperty("catalogId","test.vendor.vst3"); + payload->setProperty("slot",0); + auto intent=std::make_unique(); + intent->setProperty("operation","LOAD_INSERT"); + intent->setProperty("requestId","fx-canonical-test"); + intent->setProperty("targetChannelId","9007199254740993"); + intent->setProperty("deviceEpoch","91"); + intent->setProperty("baseGraphRevision","25"); + intent->setProperty("baseRosterRevision","9"); + intent->setProperty("payload",juce::var(payload.release())); + const juce::var request(intent.release()); + const auto translated=translateApprovedNativeControl(request,accepted,bus); + assert(translated.ok()); + assert(translated.translated.getProperty("operation","").toString() + =="NATIVE_LOAD_INSERT"); + assert(translated.translated.getProperty("payload",{}) + .getProperty("catalogId","").toString()=="test.vendor.vst3"); + const auto noChange=[&](juce::var cmd,juce::var live,juce::var native){ + const auto before=juce::JSON::toString(native,false); + const auto result=translateApprovedNativeControl(cmd,live,native); + assert(!result.ok()&&!result.translated.isObject()); + assert(juce::JSON::toString(native,false)==before); + }; + auto stale=juce::JSON::parse(juce::JSON::toString(request,false)); + stale.getDynamicObject()->setProperty("baseGraphRevision","24"); + noChange(stale,accepted,bus); + auto gap=juce::JSON::parse(juce::JSON::toString(request,false)); + gap.getProperty("payload",{}).getDynamicObject()->setProperty("slot",1); + noChange(gap,accepted,bus); + auto empty=juce::JSON::parse(juce::JSON::toString(request,false)); + empty.getProperty("payload",{}).getDynamicObject() + ->setProperty("catalogId",""); + noChange(empty,accepted,bus); + auto unsupported=juce::JSON::parse(juce::JSON::toString(bus,false)); + unsupported.getDynamicObject()->setProperty( + "supportedOps",juce::var(juce::Array{})); + noChange(request,accepted,unsupported); + auto falseRole=juce::JSON::parse(juce::JSON::toString(accepted,false)); + falseRole.getProperty("graph",{}).getProperty("channels",{})[0] + .getDynamicObject()->setProperty("role","MAIN"); + noChange(request,falseRole,bus); +} static void approvedWireTranslationRegression(const juce::var& canonical, const juce::var& producer) { auto accepted=juce::JSON::parse(juce::JSON::toString(canonical,false)); @@ -767,6 +823,7 @@ int main() { assert(!static_cast(snap.getProperty("productionCallbackLive",false))); controlIntentTranslationCases(snap,bus); + approvedNativeVst3LoadContractRegression(snap,bus); approvedWireTranslationRegression(snap,bus); installedCallbackAdmissionRegression(bus); firstSoundRouteAdmissionRegression(); From 9cef639837be51c401ed93bc32456bc521741324 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 11:06:25 +0700 Subject: [PATCH 082/219] test(P0): match actual C++ LOAD_INSERT branch and keep native FX contract strict --- tests/approved_native_m2_contract.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 36ecdfc7e..ed34b6436 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -201,7 +201,7 @@ test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual assert.match(lab,/nativeAccepted_\.fxOwners->externalChannel\(\)==target/); assert.match(bridge,/pendingFxInsert=\{authority:"CHANNEL_ID"/); assert.match(bridge,/inserted\?\.id===p\.id/); - assert.match(translate,/if\(op==="LOAD_INSERT"\)/); + assert.match(translate,/if\(op=="LOAD_INSERT"\)/); assert.match(snapshot,/available\.add\(juce::String\("LOAD_INSERT"\)\)/); assert.match(main,/engine_\.installNativeVst3\(/); assert.match(contract,/if \(operation === "LOAD_INSERT"\)/); From 40c22dc46dbdc7c060e413bd48007f71cae95b68 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 11:08:28 +0700 Subject: [PATCH 083/219] feat(P0): keep physical IN editable after native BUS/WIRE, including NONE, with late-gated PCM publication --- src/LiveAudioEngine.h | 36 +++++++++++-- src/LiveDryRoutingLab.h | 38 ++++++++------ src/Main.cpp | 59 ++++++++++++++++++++++ tests/approved_native_m2_contract.test.cjs | 15 ++++++ web/approved-native-bridge.js | 51 +++++++++++++++++++ 5 files changed, 179 insertions(+), 20 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index b9cc701b2..e140ac137 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1533,16 +1533,42 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback std::uint64_t rosterRevision,armix::mixer::ChannelId channel, int left,int right,bool stereo) { LiveDryRoutingLab::NativeBusResult fail; - fail.error="HARDWARE_NOT_DISARMED"; + fail.error="NATIVE_SOURCE_DEVICE_UNAVAILABLE"; if(independent_.active()||!attached_||!directFence_.permitted()|| + secondaryOutput_.armed()|| routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal || - !allOutputsDisarmed()||handoff_.busy()|| - fxMovePhase_.load(std::memory_order_acquire)!=0) + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0) return fail; - return dryRoutingLab_.patchNativeInputSource( - epoch,pcmRevision,rosterRevision,channel,left,right,stereo,true); + const bool wasMonitoring=isMonitorEnabled(); + bool publishing=false; + try{ + const auto result=dryRoutingLab_.patchNativeInputSource( + epoch,pcmRevision,rosterRevision,channel,left,right,stereo, + true,[&]{ + publishing=true; + if(wasMonitoring)topologyPublicationMute_.store( + true,std::memory_order_release); + }); + if(publishing){ + if(wasMonitoring && + !armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + wasMonitoring,epoch==dryRoutingLab_.epoch(), + liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed())) + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + return result; + }catch(...){ + if(publishing){ + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + fail.error="NATIVE_SOURCE_PUBLICATION_EXCEPTION"; + return fail; + } } LiveDryRoutingLab::NativeBusResult setNativePrimaryOutput( std::uint64_t ep,std::uint64_t pcmRev,std::uint64_t rosterRev, diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 9ef375128..ab5e14abf 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1543,7 +1543,8 @@ class LiveDryRoutingLab final { NativeBusResult patchNativeInputSource(std::uint64_t expectedEpoch, std::uint64_t expectedPcmRevision,std::uint64_t expectedRosterRevision, armix::mixer::ChannelId channel,int physicalLeft, - int physicalRight,bool stereo,bool outputsDisarmed=false) { + int physicalRight,bool stereo,bool outputsDisarmed=false, + const std::function& beforePublish={}) { using namespace armix::mixer; NativeBusResult reply{}; reply.pcmRevision=nativeAccepted_.pcmRevision; @@ -1556,28 +1557,32 @@ class LiveDryRoutingLab final { expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) return reply; const auto* target=nativeAccepted_.graph.roster.find(channel); - if(!target||target->role!=ChannelRole::input||!nativeStructureLive_) { - reply.error="NOT_DYNAMIC_INPUT";return reply; + if(!target||target->role!=ChannelRole::input){ + reply.error="NATIVE_INPUT_ID_UNAVAILABLE";return reply; } - for(const auto id:nativeAccepted_.graph.ids.inputs) - if(channel==id) {reply.error="M4_INPUT_NOT_DYNAMIC";return reply;} + const bool disconnect=!stereo&&physicalLeft==-1&&physicalRight==-1; int l=-1,r=-1; - for(int i=0;i(ctx))(id,left,right,n); }; fx.deviceEpoch=expectedEpoch;fx.graphRevision=expectedPcmRevision+1; + if(beforePublish)beforePublish(); // late PCM publication gate const auto published=nativePublisher_.commit( nativeAccepted_.graph.roster,request,expectedPcmRevision, expectedEpoch,epoch(),true,std::move(fx)); @@ -1602,6 +1608,8 @@ class LiveDryRoutingLab final { nativeAccepted_.graph.request=std::move(request); nativeAccepted_.fxOwners=std::move(owner); nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; // M4 source roster no longer authoritative + nativeMeterEpoch_.store(0,std::memory_order_release); reply.accepted=true;reply.error=""; reply.pcmRevision=published.revision; reply.rosterRevision=nativeAccepted_.graph.roster.revision(); diff --git a/src/Main.cpp b/src/Main.cpp index db2d81252..1b36d023d 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2045,6 +2045,65 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Real DAW + BUS from the approved Windows GUI. The engine creates // and publishes a stereo GROUP directly in its sole ChannelId PCM // owner; no browser-only track or legacy M4 shadow is created. + // Normal GUI physical IN remains available after a native BUS/WIRE + // publication. The ChannelId producer, not stale M4, owns the patch. + if(action=="routingNativeSourcePatch"){ + const auto request=args.getProperty("requestId",{}).toString(); + const auto rawId=args.getProperty("channelId",{}); + const auto rawEp=args.getProperty("deviceEpoch",{}); + const auto rawRev=args.getProperty("graphRevision",{}); + const auto rawRoster=args.getProperty("rosterRevision",{}); + const auto mode=args.getProperty("mode",{}).toString(); + const int left=static_cast(args.getProperty("left",-1)); + const int right=static_cast(args.getProperty("right",-1)); + std::uint64_t id=0,ep=0,rev=0,roster=0; + const auto snap=approvedNativeSnapshot(); + const auto graph=snap.getProperty("graph",{}); + bool input=false; + const auto channels=graph.getProperty("channels",{}); + if(const auto* rows=channels.getArray()) + for(const auto& row:*rows) + if(row.getProperty("id","").toString()==rawId.toString()&& + row.getProperty("role","").toString()=="INPUT") + input=true; + const bool valid=request.startsWith("source-native-")&& + request.length()<=64&&!acceptedControlRequests_.contains(request)&& + armix::console::approvedNativeId(rawId,id)&& + armix::console::approvedNativeId(rawEp,ep)&& + armix::console::approvedNativeId(rawRev,rev)&& + armix::console::approvedNativeId(rawRoster,roster)&& + (mode=="NONE"||mode=="MONO"||mode=="STEREO")&& + (mode!="NONE"||(left==-1&&right==-1))&& + (mode!="MONO"||right==-1)&&input&& + snap.getProperty("device",{}).getProperty("epoch","").toString()==rawEp.toString()&& + graph.getProperty("revision","").toString()==rawRev.toString()&& + graph.getProperty("rosterRevision","").toString()==rawRoster.toString()&& + !nativeShowBusy_&&!studioBackupBusy_; + LiveDryRoutingLab::NativeBusResult result; + result.error="NATIVE_SOURCE_NOT_ADMITTED_OR_STALE"; + if(valid){ + acceptedControlRequests_.add(request); + if(acceptedControlRequests_.size()>512) + acceptedControlRequests_.remove(0); + result=engine_.patchNativeInputSource(ep,rev,roster, + armix::mixer::ChannelId{id},left,right,mode=="STEREO"); + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",rawId); + ack->setProperty("ok",valid&&result.accepted); + ack->setProperty("error",result.error?result.error:"NATIVE_SOURCE_UNKNOWN"); + ack->setProperty("graphRevision", + juce::String(std::to_string(result.pcmRevision))); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixNativeSourceAck",juce::var(ack.release())); + if(valid&&result.accepted) + diagnostics_.record("DAW_NATIVE_SOURCE", + "ChannelId "+rawId.toString()+" → "+mode); + else emitNotice("Channel IN rejected: "+ + juce::String(result.error?result.error:"native error"),true); + return; + } if(action=="routingNativeBusCreate") { const auto request=args.getProperty("requestId",{}).toString(); const auto rawEp=args.getProperty("deviceEpoch",{}); diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index ed34b6436..3bba2661d 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -257,6 +257,21 @@ test("P0 MAIN remains enabled through verified STEREO -> NONE -> STEREO edits",( assert.doesNotMatch(bridge,/routingSourceSwitch[^;]+monitor\(false\)/); }); +test("P0 post-BUS native IN routes NONE MONO STEREO via one PCM owner",()=>{ + const bridge=read("web/approved-native-bridge.js"); + const host=read("src/Main.cpp"); + const engine=read("src/LiveAudioEngine.h"); + const lab=read("src/LiveDryRoutingLab.h"); + assert.match(bridge,/function dispatchNativeSource\(\)/); + assert.match(bridge,/action:"routingNativeSourcePatch"/); + assert.match(bridge,/arMixNativeSourceAck/); + assert.match(bridge,/pendingNativeSources.set\(id,choice\)/); + assert.match(host,/if\(action=="routingNativeSourcePatch"\)/); + assert.match(host,/engine_\.patchNativeInputSource\(ep,rev,roster,/); + assert.match(lab,/const bool disconnect=!stereo&&physicalLeft==-1&&physicalRight==-1/); + assert.match(lab,/nativeStructureLive_=true; \/\/ M4 source roster no longer authoritative/); + assert.match(engine,/NATIVE_SOURCE_PUBLICATION_EXCEPTION/); +}); test("P0 actual Add BUS reaches the live ChannelId graph",()=>{ const bridge=read("web/approved-native-bridge.js"); const host=read("src/Main.cpp"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index c9d19de9c..83bfcb3fa 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -406,6 +406,31 @@ },8000); return true; } + const pendingNativeSources=new Map(); + let activeNativeSource=null,nativeSourceSerial=0; + function dispatchNativeSource(){ + if(activeNativeSource||!pendingNativeSources.size)return; + const current=controller?.state()?.current; + if(!current?.admitted||mixerSession()?.authority!=="CHANNEL_ID")return; + const [id,choice]=pendingNativeSources.entries().next().value; + pendingNativeSources.delete(id); + if(!current.graph.channels.some(ch=>ch.id===id&&ch.role==="INPUT")) + return nativeToast("Source identity changed · refresh native mixer"); + const requestId="source-native-"+(++nativeSourceSerial); + activeNativeSource={requestId,id,choice}; + backend.emitEvent("arMixAction",{ + action:"routingNativeSourcePatch",requestId,channelId:id, + deviceEpoch:current.device.epoch,graphRevision:current.graph.revision, + rosterRevision:current.graph.rosterRevision, + mode:choice.mode,left:choice.left,right:choice.right}); + status("Input "+choice.label+" · native PCM readback pending"); + window.setTimeout(()=>{ + if(activeNativeSource?.requestId!==requestId)return; + activeNativeSource=null; + nativeToast("Source ACK timed out · previous PCM preserved"); + controller?.subscribe(); + },8000); + } let pendingBusCreate=null,busRequestSerial=0; function requestNativeBusCreate(){ const accepted=controller?.state()?.current; @@ -1407,6 +1432,8 @@ } flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); + if(!activeNativeSource&&pendingNativeSources.size) + window.queueMicrotask(dispatchNativeSource); if(pendingFxInsert?.authority==="CHANNEL_ID"){ const p=pendingFxInsert; const inserted=next.graph.channels.find(ch=>ch.id===p.channelId) @@ -1473,6 +1500,14 @@ finally{profiler.sample("nativeSnapshotJsMs",performance.now()-started);} }); backend.addEventListener("arMixConsoleAck", ack=>controller.onAck(ack)); + backend.addEventListener("arMixNativeSourceAck",ack=>{ + if(!activeNativeSource||activeNativeSource.requestId!==ack?.requestId)return; + activeNativeSource=null; + if(ack.ok!==true) + nativeToast("Native input rejected · "+(ack?.error||"stale PCM")); + else status("Native input accepted · checking subsequent PCM readback"); + controller?.subscribe(); + }); backend.addEventListener("arMixNativeBusAck",ack=>{ if(!pendingBusCreate||pendingBusCreate.requestId!==ack?.requestId)return; pendingBusCreate=null; @@ -1721,6 +1756,22 @@ if(event.type!=="change")return true; const channel=m4Index(t); const choice=inputChoicesFor().find(x=>x.label===el.value); + // After BUS/WIRE the installed ChannelId graph is sole PCM owner. + // Original ten channels must not send source edits to stale M4. + if(mixerSession()?.authority==="CHANNEL_ID"){ + const current=controller?.state()?.current; + const id=nativeIdFor(t); + if(!choice||!id||!current?.admitted||!deviceReady()){ + nativeToast("Select a verified physical input"); + el.value=t.input;return true; + } + if(choice.label!==t.input){ + pendingNativeSources.set(id,choice); + dispatchNativeSource(); + } + el.value=t.input; // no optimistic browser patch + return true; + } const ep=safeNativeCounter(hardware?.device?.epoch); const rev=safeNativeCounter(legacy()?.routingRevision); if(channel<0||channel>=10||!choice||!deviceReady()|| From b69e0b6fcf35e090ea5aa800530192db00a78929 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 11:13:35 +0700 Subject: [PATCH 084/219] test(audio): prove SOURCE ONLY silences MAIN without losing the physical source, then WIRE reconnects --- tests/dynamic_accepted_session_test.cpp | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index 72621d58e..7f53c32e7 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -389,6 +389,26 @@ static void verifyAtomicWireTransactionAndZeroSampleHops() { assert(staleMain.fault==DynamicAcceptedSession::Fault::staleRoster); assert(session.acceptedGraphRevision()==11); assert(render() && near(left[11],.3f*center,1e-4f)); + + // GUI SOURCE ONLY: unplug only the actual accepted primary MAIN edge. + // The capture source and other channels stay in the same installed + // graph; MAIN is silent until a later explicit WIRE reconnect. + const std::array sourceOnly{remove(one,parallelEdge)}; + a=session.wireTransaction(11,11,sourceOnly,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==12); + assert(!session.acceptedRouting(epoch,12)->find(one)->primaryOutput.value); + assert(!findEdge(one,main,12)); + assert(session.acceptedPhysicalRequest().sources.size()==1); + assert(session.acceptedPhysicalRequest().sources.front().id==one); + assert(render() && near(left[11],0.f,1e-5f) && + near(right[11],0.f,1e-5f)); + // Replug MAIN via the same menu/socket. No external monitor ARM or + // hardware source patch is required, and exactly one path resumes PCM. + a=session.wireTransaction(12,12,backToMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==13); + assert(findEdge(one,main,13)!=0); + assert(session.acceptedRouting(epoch,13)->find(one)->primaryOutput==main); + assert(render() && near(left[11],.3f*center,1e-4f)); session.unpublish(); session.pollRetirement(); } From 571da225b091c8058dd0eb5c6e0a687c49dc9dde Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 11:14:20 +0700 Subject: [PATCH 085/219] refactor(CI): remove ownership and cross-PR admission blockers; keep real audio/UI tests --- .github/workflows/p1-windows.yml | 6 ------ .github/workflows/ui-smoke.yml | 18 ++++++++++-------- scripts/ci_select_changed_paths.mjs | 18 ++++++++++++++++++ tests/ci_workflow_efficiency_test.mjs | 6 ++++-- 4 files changed, 32 insertions(+), 16 deletions(-) create mode 100644 scripts/ci_select_changed_paths.mjs diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 195b73707..5a4ffb9a4 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -60,11 +60,6 @@ jobs: timeout-minutes: 50 steps: - uses: actions/checkout@v4 - - name: Cheap one-owner / overlapping-PR preflight (read-only) - if: ${{ github.event_name == 'pull_request' }} - env: - GH_TOKEN: ${{ github.token }} - run: node scripts/check_workstream_coordination.mjs --pr ${{ github.event.pull_request.number }} - name: Cheap canonical Console v6 puzzle socket gate (no JUCE) run: node scripts/check_console_puzzle.mjs - name: Stop incomplete integrated product promotion before JUCE checkout @@ -99,7 +94,6 @@ jobs: if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } } $contracts = @( - 'tests/workstream_coordination_contract.test.mjs' 'tests/gui_workflow_contract_test.mjs' 'tests/approved_native_m2_contract.test.cjs' 'tests/native_ui_contract_test.mjs' diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index d2d777d94..115ef0e44 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -23,7 +23,7 @@ on: - 'scripts/build_ui_css.py' - '.github/workflows/ui-smoke.yml' - '.github/workflows/pages-publish.yml' - # All PRs receive fast admission; Chromium is conditional on checked files. + # Every PR gets direct test selection; no ownership or PR collision audit. pull_request: types: [opened, reopened, synchronize, edited, ready_for_review] # Manual full suite (including immutable CSS migration tests) or release-integration PR. @@ -41,7 +41,7 @@ permissions: jobs: coordination: - name: PR coordination admission + name: Changed files only runs-on: ubuntu-latest timeout-minutes: 5 outputs: @@ -49,19 +49,21 @@ jobs: run_native: ${{ steps.pr_scope.outputs.run_native }} steps: - uses: actions/checkout@v4 - - name: Audit PR metadata, file ownership and runtime collisions + - name: Select UI and Windows tests from changed files, not owners id: pr_scope if: ${{ github.event_name == 'pull_request' }} + shell: bash env: - GH_TOKEN: ${{ github.token }} - run: node scripts/check_workstream_coordination.mjs --pr ${{ github.event.pull_request.number }} + BASE_SHA: ${{ github.event.pull_request.base.sha }} + run: | + set -euo pipefail + git fetch --no-tags --depth=1 origin "$BASE_SHA" + node scripts/ci_select_changed_paths.mjs "$BASE_SHA" - name: Main push retains Chromium verification id: push_scope if: ${{ github.event_name != 'pull_request' }} shell: bash run: echo "run_ui=true" >> "$GITHUB_OUTPUT" - - name: Fast offline coordination contract regression - run: node --test tests/workstream_coordination_contract.test.mjs native: needs: coordination if: ${{ github.event_name == 'pull_request' && needs.coordination.outputs.run_native == 'true' }} @@ -140,7 +142,7 @@ jobs: node --check web/plugin-ui.js node --check web/mixer-io.js node --check web/mixer-layout.js - node --test tests/workstream_coordination_contract.test.mjs tests/gui_workflow_contract_test.mjs tests/plugin_ui_contract_test.mjs tests/ci_workflow_efficiency_test.mjs tests/fx_drag_reorder_contract_test.mjs tests/mixer_io_operator_contract_test.mjs tests/mixer_shell_contract_test.mjs tests/approved_native_m2_contract.test.cjs + node --test tests/gui_workflow_contract_test.mjs tests/plugin_ui_contract_test.mjs tests/ci_workflow_efficiency_test.mjs tests/fx_drag_reorder_contract_test.mjs tests/mixer_io_operator_contract_test.mjs tests/mixer_shell_contract_test.mjs tests/approved_native_m2_contract.test.cjs - name: Validate approved GUI checkpoint and single publisher run: python tests/gui_baseline_lock_test.py - name: CSS V28 zero-regression source-order recovery (every GUI CI run) diff --git a/scripts/ci_select_changed_paths.mjs b/scripts/ci_select_changed_paths.mjs new file mode 100644 index 000000000..51a16b457 --- /dev/null +++ b/scripts/ci_select_changed_paths.mjs @@ -0,0 +1,18 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Only select real test suites. No PR owner, labels, collision or GitHub API. +import {execFileSync} from 'node:child_process'; +import {appendFileSync} from 'node:fs'; +import {requiresUiSmoke,requiresNativeQualification} from './check_workstream_coordination.mjs'; +const base=process.argv[2]; +if(!base || !/^[a-f0-9]{40}$/.test(base)) + throw Error('Expected exact Git base SHA'); +const changed=execFileSync('git', + ['diff','--name-only','--diff-filter=ACMRT',base,'HEAD'], + {encoding:'utf8',maxBuffer:8*1024*1024}) + .split(/\r?\n/).filter(Boolean); +const ui=requiresUiSmoke(changed),native=requiresNativeQualification(changed); +if(process.env.GITHUB_OUTPUT) + appendFileSync(process.env.GITHUB_OUTPUT, + 'run_ui='+(ui?'true':'false')+'\n'+ + 'run_native='+(native?'true':'false')+'\n'); +console.log('Changed '+changed.length+' paths: Chromium '+ui+', Windows CTest '+native); diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index a2bfbdf5f..5d0b7d548 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -168,10 +168,12 @@ test('M2.6 always-on coordination job has a stable name and skips unrelated Chro const prBlock=ui.split('\n pull_request:\n')[1]?.split('\n # Manual full suite')[0] || ''; assert.match(prBlock,/types: \[opened, reopened, synchronize, edited, ready_for_review\]/); assert.doesNotMatch(prBlock,/^\s+paths:/m); - assert.match(ui,/name: PR coordination admission/); + assert.match(ui,/name: Changed files only/); assert.match(ui,/needs: coordination/); assert.match(ui,/needs\.coordination\.outputs\.run_ui == 'true'/); - assert.match(ui,/node --test tests\/workstream_coordination_contract\.test\.mjs/); + assert.match(ui,/node scripts\/ci_select_changed_paths\.mjs/); + assert.doesNotMatch(ui,/scripts\/check_workstream_coordination\.mjs --pr/); + assert.doesNotMatch(native,/scripts\/check_workstream_coordination\.mjs --pr/); }); test('P0 single product qualification fans in exact scoped native and UI jobs',()=>{ From 55cc7e130d79d4cec6bc6c36062b51715dfd86e7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 12:29:46 +0700 Subject: [PATCH 086/219] fix(p0): reconcile VST3 catalog vs instance identity in live native PCM readback Preserve the installed processor instance token for bypass/editor and expose its distinct vendor catalog identity. Require both in the approved ACK readback and native GUI; add deterministic JS ACK/readback and C++ native projection regressions. No GUI/CSS or callback changes. --- src/ApprovedNativeV8Projection.h | 12 +++++- tests/approved_native_m2_contract.test.cjs | 41 +++++++++++++++++++- tests/approved_native_v8_projection_test.cpp | 29 ++++++++++++++ web/approved-native-bridge.js | 5 ++- web/approved-native-contract.js | 6 ++- 5 files changed, 87 insertions(+), 6 deletions(-) diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index b5f4b4cc5..c09a81f97 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -73,11 +73,19 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { ch->setProperty("controls",juce::var(controls.release())); juce::Array fx; for(const auto& item:*inserts.getArray()){ + // Catalog identity selects the vendor binary; instance identity + // addresses the live DSP processor and per-slot bypass/editor. + // They must NEVER be compared as if they were interchangeable. const auto token=item.getProperty("instanceId",{}),label=item.getProperty("name",{}); + const auto catalog=item.getProperty("id",{}); const auto bypass=item.getProperty("bypassed",{}); - if(!token.isString()||!label.isString()||!bypass.isBool())return false; + if(!token.isString()||token.toString().isEmpty()|| + !catalog.isString()||catalog.toString().isEmpty()|| + catalog.toString().getNumBytesAsUTF8()>256|| + !label.isString()||!bypass.isBool())return false; auto insert=std::make_unique(); - insert->setProperty("id",token);insert->setProperty("name",label); + insert->setProperty("id",token);insert->setProperty("catalogId",catalog); + insert->setProperty("name",label); insert->setProperty("bypassed",bypass); fx.add(juce::var(insert.release())); } diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 3bba2661d..b5563c8b1 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -200,12 +200,12 @@ test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual assert.match(bridge,/legacy\(\)\?\.nativeBusStructural===true/); assert.match(lab,/nativeAccepted_\.fxOwners->externalChannel\(\)==target/); assert.match(bridge,/pendingFxInsert=\{authority:"CHANNEL_ID"/); - assert.match(bridge,/inserted\?\.id===p\.id/); + assert.match(bridge,/inserted\?\.catalogId===p\.id/); assert.match(translate,/if\(op=="LOAD_INSERT"\)/); assert.match(snapshot,/available\.add\(juce::String\("LOAD_INSERT"\)\)/); assert.match(main,/engine_\.installNativeVst3\(/); assert.match(contract,/if \(operation === "LOAD_INSERT"\)/); - assert.match(contract,/ch\.inserts\[payload\.slot\]\?\.id===payload\.catalogId/); + assert.match(contract,/ch\.inserts\[payload\.slot\]\?\.catalogId===payload\.catalogId/); assert.match(lab,/epoch\(\),false,std::move\(fx\),false,true\)/); assert.match(pub,/verifiedInternalFxOnly/); const install=engine.slice(engine.indexOf("installNativeVst3("), @@ -214,6 +214,43 @@ test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual assert.match(install,/secondaryOutput_\.armed\(\)/); assert.match(install,/getLatencySamples\(\)!=0/); }); +test("Native VST3 insert ACK + readback distinguishes vendor catalog key from live instance token",()=>{ + const base=acceptedFixture(); + base.graph.capabilities.supportedOps.push("LOAD_INSERT"); + const sent=[],accepted=[]; + const controller=protocol.createController({emit:(name,payload)=>sent.push({name,payload}), + onAccepted:s=>accepted.push(s)}); + assert.equal(controller.onSnapshot(base),true); + const source=base.graph.channels[0].id; + const cmd=controller.intent("LOAD_INSERT",source,{catalogId:"vendor.eq.catalog",slot:0}); + assert.equal(cmd.ok,true); + const after=clone(base); + after.graph.revision="6";after.graph.rosterRevision="8"; + after.graph.channels[0].inserts=[{id:"vst3-instance-unique-7", + catalogId:"vendor.eq.catalog",name:"Vendor EQ",bypassed:false}]; + const next=protocol.normalizeSnapshot(after); + const pending={operation:"LOAD_INSERT",targetChannelId:source, + payload:{catalogId:"vendor.eq.catalog",slot:0}, + baseGraphRevision:"5",baseRosterRevision:"7"}; + assert.ok(next?.admitted); + assert.equal(protocol.readbackProvesIntent(next,pending),true, + "live instance token differs from catalog ID but effect is verified"); + for(const spoof of [ + {id:"vst3-instance-unique-7",name:"Vendor EQ",bypassed:false}, + {id:"vst3-instance-unique-7",catalogId:"different.plugin",name:"Vendor EQ",bypassed:false}, + {id:"",catalogId:"vendor.eq.catalog",name:"Vendor EQ",bypassed:false} + ]){ + const bad=clone(after);bad.graph.channels[0].inserts=[spoof]; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(bad),pending),false); + } + assert.equal(controller.onAck({requestId:cmd.requestId,status:"ACCEPTED", + deviceEpoch:base.device.epoch,graphRevision:"6",rosterRevision:"8",errorCode:"NONE"}),true); + assert.equal(controller.state().lastError,"PENDING_ACCEPTED_SNAPSHOT"); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK"); + assert.equal(accepted.at(-1).graph.channels[0].inserts[0].id,"vst3-instance-unique-7"); + assert.ok(sent.some(evt=>evt.name==="arMixConsoleSubscribe")); +}); test("P0 first Add FX discovers real local VST3 lazily without an audio-thread scan",()=>{ const bridge=read("web/approved-native-bridge.js"); const native=read("src/Main.cpp"); diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index db7b7022e..67f7fc48b 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -70,6 +70,34 @@ static juce::var realBusReadbackFixture() { ] })JSON"); } +static void nativeInsertCatalogInstanceProjectionRegression() { + auto source=realBusReadbackFixture(); + auto item=std::make_unique(); + item->setProperty("instanceId","vst3-instance-unique-7"); + item->setProperty("id","vendor.eq.catalog"); + item->setProperty("name","Vendor EQ"); + item->setProperty("bypassed",false); + juce::Array inserts; + inserts.add(juce::var(item.release())); + source.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("inserts",juce::var(inserts)); + auto snapshot=canonicalSnapshot(); + assert(projectApprovedNativeV8(snapshot,source,true)); + const auto live=snapshot.getProperty("graph",{}) + .getProperty("channels",{})[0].getProperty("inserts",{})[0]; + assert(live.getProperty("id","").toString()=="vst3-instance-unique-7"); + assert(live.getProperty("catalogId","").toString()=="vendor.eq.catalog"); + assert(!static_cast(live.getProperty("bypassed",true))); + // A missing catalog token must not be projected as a verified processor. + auto invalid=juce::JSON::parse(juce::JSON::toString(source,false)); + invalid.getProperty("channels",{})[0].getProperty("inserts",{})[0] + .getDynamicObject()->removeProperty("id"); + auto untouched=canonicalSnapshot(); + const auto before=juce::JSON::toString(untouched,false); + assert(!projectApprovedNativeV8(untouched,invalid,true)); + assert(juce::JSON::toString(untouched,false)==before); +} + static void noMutationOnReject(juce::var snapshot,juce::var bus,bool admitted) { const auto before=juce::JSON::toString(snapshot,false); assert(!projectApprovedNativeV8(snapshot,bus,admitted)); @@ -823,6 +851,7 @@ int main() { assert(!static_cast(snap.getProperty("productionCallbackLive",false))); controlIntentTranslationCases(snap,bus); + nativeInsertCatalogInstanceProjectionRegression(); approvedNativeVst3LoadContractRegression(snap,bus); approvedWireTranslationRegression(snap,bus); installedCallbackAdmissionRegression(bus); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 83bfcb3fa..c6872b1b5 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1438,7 +1438,10 @@ const p=pendingFxInsert; const inserted=next.graph.channels.find(ch=>ch.id===p.channelId) ?.inserts?.[p.slot]; - if(inserted?.id===p.id){ + // The selected catalog key is NOT the live VST3 instance token. + // Match catalog against catalog, while requiring a real processor ID. + if(inserted?.catalogId===p.id && + typeof inserted.id==="string" && inserted.id.length>0){ pendingFxInsert=null; scope?.closeNativePicker?.(); status("VST3 loaded · "+inserted.name+" · native PCM readback verified"); diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index ad2b8b6f0..0ef623c7f 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -122,7 +122,11 @@ Number.isInteger(payload.slot)&&payload.slot>=0 && typeof payload.catalogId==="string" && Array.isArray(ch.inserts)&&ch.inserts.length===payload.slot+1 && - ch.inserts[payload.slot]?.id===payload.catalogId; + ch.inserts[payload.slot]?.catalogId===payload.catalogId && + typeof ch.inserts[payload.slot]?.id==="string" && + ch.inserts[payload.slot].id.length>0 && + !ch.inserts.slice(0,payload.slot).some(insert=> + insert.id===ch.inserts[payload.slot].id); if (operation !== "APPLY_WIRE_TRANSACTION" || !Array.isArray(payload.changes) || !payload.changes.length) return false; // A structural WIRE transaction must advance the actual PCM graph. From 9732736df1693ac96b9883961568ac6a4d2ce25c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 12:34:42 +0700 Subject: [PATCH 087/219] fix(p0): separate native parallel MAIN sends from exclusive primary OUT Do not promote CONNECT to MAIN into a primary: only ROUTE_ONLY owns primary destination. Preserve normal MAIN jack primary semantics, allow explicitly tagged MAIN parallel send in canonical WIRE model, project true native tap/mode, and assert measured 64-frame PCM for source-only, 40% parallel, exclusive promotion, stale EdgeId rejection. No GUI/CSS or audio-callback changes. --- engine/core/DynamicChannelRoster.h | 9 +-- site/preview-v2/assets/wire-graph-model.js | 10 ++- tests/dynamic_accepted_session_test.cpp | 73 +++++++++++++++++++++- tests/wire_graph_canonical_model.test.cjs | 14 +++++ web/approved-native-bridge.js | 9 ++- 5 files changed, 105 insertions(+), 10 deletions(-) diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index c8712ef62..e6b8f118b 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -419,10 +419,11 @@ class DynamicChannelRoster final { if(sends.size()>=budget_.maximumSendsPerChannel){ result.fault=ChannelEditFault::budgetExceeded;break; } - const bool hasPrimary=std::any_of(sends.begin(),sends.end(), - [](const auto& s){return s.primaryOutput;}); - const bool primary=!hasPrimary && - (op.to==mainId || op.kind==WireChange::Kind::routeOnly); + // CONNECT means a deliberate parallel POST-fader send, even to + // MAIN and even when primary OUT is NONE. Only ROUTE_ONLY may + // establish a primary. This prevents silent promotion of a send + // into an exclusive route and preserves SOURCE ONLY readback. + const bool primary=op.kind==WireChange::Kind::routeOnly; sends.push_back({op.to,op.gain,false,0.f,primary,0}); } if(result.ok()){ diff --git a/site/preview-v2/assets/wire-graph-model.js b/site/preview-v2/assets/wire-graph-model.js index 6d8a2d49d..87a500503 100644 --- a/site/preview-v2/assets/wire-graph-model.js +++ b/site/preview-v2/assets/wire-graph-model.js @@ -37,8 +37,11 @@ const key=edgeKey(e); if(unique.has(key))return {ok:false,error:'DUPLICATE_ROUTE'}; unique.add(key); + // MAIN accepts one unity-gain primary and, independently, an explicit + // post-fader parallel SEND. An unrequested duplicate edge stays invalid. if(e.destId===mainId&& - (e.mode!=='postFader'||e.kind!=='primary'||e.levelDb!==0)) + !((e.kind==='primary'&&e.mode==='postFader'&&e.levelDb===0)|| + (e.kind==='send'&&e.mode==='send'))) return {ok:false,error:'INVALID_MAIN_TAP'}; if(e.kind==='primary'&&e.destId!==mainId&&e.mode!=='routeOnly') return {ok:false,error:'INVALID_PRIMARY_TAP'}; @@ -97,10 +100,11 @@ if(edges.some(e=>e.sourceId===sourceId&&e.destId===op.destId)) return {ok:false,error:'DUPLICATE_ROUTE'}; const isMain=op.destId===mainId; + const isParallelMain=isMain&&op.mode==='send'; const isSplit=op.mode==='splitPre'||op.mode==='splitPost'; - const mode=isMain?'postFader':isSplit?op.mode:op.mode==='split'?'split':'send'; + const mode=isMain&&!isParallelMain?'postFader':isSplit?op.mode:op.mode==='split'?'split':'send'; edges.push({id:nextId++,sourceId,destId:op.destId,enabled:true, - kind:isMain?'primary':isSplit?'split':'send',mode,levelDb:0}); + kind:isMain&&!isParallelMain?'primary':isSplit?'split':'send',mode,levelDb:0}); } }else if(op.type==='REMOVE'||op.type==='RETARGET'||op.type==='GAIN'||op.type==='MODE'){ index=edges.findIndex(e=>e.id===op.edgeId&&e.sourceId===sourceId); diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index 7f53c32e7..7333fadaf 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -235,7 +235,7 @@ static void verifyAtomicWireTransactionAndZeroSampleHops() { w.from=from;w.edgeId=id;return w; }; const std::array initial{ - connect(one,main),connect(two,main),connect(three,main) + routeOnly(one,main),routeOnly(two,main),routeOnly(three,main) }; a=session.wireTransaction(1,1,initial,physical,epoch,epoch,true); assert(a.ok()&&a.graphRevision==2&&a.edit.createdEdgeIds.size()==3); @@ -653,7 +653,78 @@ static void verifyOriginalAndAddedInputsShareNativePcmControls() { pcm.pollRetirement(); } +// Real sample-block regression for DAW semantics: SOURCE ONLY retains its +// physical input, independent CONNECT to MAIN is a parallel SEND, and the +// subsequent explicit ROUTE_ONLY promotes that exact edge to primary. +static void verifySourceOnlyParallelMainVsExclusivePrimaryPcm() { + constexpr std::uint64_t ep=99221; + constexpr float center=.7071067811865475f; + DynamicAcceptedSession pcm; + DynamicGraphRequest io;io.physicalInputs=1;io.maxFrames=64; + const std::array create{ + add(0,ChannelRole::input,"VOCAL"), + add(1,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto state=pcm.edit(0,0,create,io,ep,ep,true); + assert(state.ok()&&state.edit.createdIds.size()==2); + const auto vocal=state.edit.createdIds[0],main=state.edit.createdIds[1]; + io.sources={{vocal,0,-1,false}}; + WireChange primary;primary.kind=WireChange::Kind::routeOnly; + primary.from=vocal;primary.to=main;primary.gain=1.f; + const std::array toMain{primary}; + state=pcm.wireTransaction(1,1,toMain,io,ep,ep,true); + assert(state.ok()&&pcm.acceptedGraphRevision()==2); + const auto* first=pcm.acceptedRouting(ep,2); + assert(first&&first->edges.size()==1); + const auto primaryEdge=first->edges[0].edgeId; + std::array impulse{},l{},r{}; + impulse[9]=.25f; + const float* pins[]{impulse.data()}; + const auto render=[&]{ + return pcm.render(ep,pins,1,l.data(),r.data(),64,false, + +[](ChannelId,float*,float*,int) noexcept {}); + }; + assert(render()&&near(l[9],.25f*center)&&near(r[9],.25f*center)); + WireChange unplug;unplug.kind=WireChange::Kind::remove; + unplug.from=vocal;unplug.edgeId=primaryEdge; + const std::array remove{unplug}; + state=pcm.wireTransaction(2,2,remove,io,ep,ep,false); + assert(state.ok()&&pcm.acceptedGraphRevision()==3); + assert(pcm.acceptedRouting(ep,3)->find(vocal)->primaryOutput.value==0); + assert(render()&&near(l[9],0.f)&&near(r[9],0.f)); + // No source deletion: physical impulse remains available after unplug. + WireChange parallel;parallel.kind=WireChange::Kind::connect; + parallel.from=vocal;parallel.to=main;parallel.gain=.4f; + const std::array sendToMain{parallel}; + state=pcm.wireTransaction(3,3,sendToMain,io,ep,ep,false); + assert(state.ok()&&pcm.acceptedGraphRevision()==4); + const auto* withSend=pcm.acceptedRouting(ep,4); + assert(withSend&&withSend->find(vocal)->primaryOutput.value==0); + assert(withSend->find(vocal)->parallelSends.size()==1); + assert(withSend->edges.size()==1&&!withSend->edges[0].primaryOutput); + const auto parallelEdge=withSend->edges[0].edgeId; + assert(render()&&near(l[9],.25f*.4f*center)&& + near(r[9],.25f*.4f*center)); + // Exclusive routing promotes existing EdgeId; no double dry mix. + state=pcm.wireTransaction(4,4,toMain,io,ep,ep,false); + assert(state.ok()&&pcm.acceptedGraphRevision()==5); + const auto* exclusive=pcm.acceptedRouting(ep,5); + assert(exclusive&&exclusive->edges.size()==1); + assert(exclusive->edges[0].edgeId==parallelEdge); + assert(exclusive->edges[0].primaryOutput); + assert(exclusive->find(vocal)->parallelSends.empty()); + assert(exclusive->find(vocal)->primaryOutput==main); + assert(render()&&near(l[9],.25f*center)&&near(r[9],.25f*center)); + // A stale EdgeId must never disconnect the promoted primary. + const std::array staleRemove{unplug}; + const auto rejected=pcm.wireTransaction(5,5,staleRemove,io,ep,ep,false); + assert(rejected.fault==DynamicAcceptedSession::Fault::editRejected); + assert(pcm.acceptedGraphRevision()==5); + assert(render()&&near(l[9],.25f*center)); +} + int main() { + verifySourceOnlyParallelMainVsExclusivePrimaryPcm(); verifyHeldDragIntermediatePcmOnOriginalChannels(); verifyOriginalAndAddedInputsShareNativePcmControls(); verifyPrimaryOutKeepsCanonicalEdgeIdentity(); diff --git a/tests/wire_graph_canonical_model.test.cjs b/tests/wire_graph_canonical_model.test.cjs index a8a5a2aeb..22968b8e5 100644 --- a/tests/wire_graph_canonical_model.test.cjs +++ b/tests/wire_graph_canonical_model.test.cjs @@ -13,6 +13,20 @@ const main1=state.edges.find(e=>e.sourceId===1); const unplug=graph.applyWireTransaction(state,[{type:'REMOVE',sourceId:1,edgeId:main1.id}]); assert.equal(unplug.ok,true); assert.equal(unplug.edges.filter(e=>e.destId===9).length,2); +// An explicit parallel MAIN send does not secretly replace SOURCE ONLY. +const parallelMain=graph.applyWireTransaction( + {...state,edges:unplug.edges,nextId:unplug.nextId}, + [{type:'CONNECT',sourceId:1,destId:9,mode:'send'}]); +assert.equal(parallelMain.ok,true); +const sendToMain=parallelMain.edges.find(e=>e.sourceId===1&&e.destId===9); +assert.equal(sendToMain.kind,'send');assert.equal(sendToMain.mode,'send'); +assert.equal(parallelMain.edges.filter(e=>e.sourceId===1&&e.kind==='primary').length,0); +// Default WIRE to MAIN remains a primary; explicit mode is required for SEND. +const defaultMain=graph.applyWireTransaction( + {...state,edges:unplug.edges,nextId:unplug.nextId}, + [{type:'CONNECT',sourceId:1,destId:9}]); +assert.equal(defaultMain.ok,true); +assert.equal(defaultMain.edges.find(e=>e.sourceId===1&&e.destId===9)?.kind,'primary'); const unchanged=JSON.stringify(state); const connected=graph.applyWireTransaction({...state,edges:unplug.edges,nextId:unplug.nextId}, [{type:'CONNECT',sourceId:1,destId:3}]); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index c6872b1b5..c7f6a9b36 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -121,7 +121,7 @@ const isPrimary=source?.primaryOutId===edge.to; // An independent SEND to MAIN is not the source's primary OUT. const kind=isPrimary?"primary":edge.tap==="SPLIT_PRE"||edge.tap==="SPLIT_POST"?"split":"send"; - const mode=isMain?"postFader":kind==="primary"?"routeOnly": + const mode=isMain?(isPrimary?"postFader":"send"):kind==="primary"?"routeOnly": kind==="split"?(edge.tap==="SPLIT_PRE"?"splitPre":"splitPost"):"send"; if (isPrimary && edge.gainLinear!==1) return false; const gainDb=isPrimary?0:Math.round(Math.max(-60,Math.min(6, @@ -1950,7 +1950,12 @@ const op=ops[0]; const t=scope?.tracks?.find(x=>x.id===op.sourceId); const sourceId=t?nativeByUiId.get(t.id):null; - const isMainConnect=(op.type==="CONNECT"||op.type==="ROUTE_ONLY") && + // Ordinary MAIN jack is a primary ROUTE_ONLY. An explicitly selected + // send mode must pass through native CONNECT instead, preserving the + // old primary BUS (or the absence of a primary in SOURCE ONLY). + const isMainConnect=(op.type==="ROUTE_ONLY" || + (op.type==="CONNECT" && (!op.mode || + op.mode==="postFader" || op.mode==="routeOnly"))) && op.destId===scope?.master?.id; // WIRE gesture carries a UI edge id. wireByUiId is UI→native; // uiByWireId is the inverse. The old inverse lookup always returned From 7e7de6f2882a0b183e4bb4b40636f39edbd99057 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 12:42:38 +0700 Subject: [PATCH 088/219] feat(p0): wire GROUP mute/solo to native ChannelId PCM without graph rebuild Use the existing realtime group mute/solo control target, validate GROUP/FX_RETURN vs legacy M4 AUX and device epoch/revision, persist accepted mute/solo in canonical roster, and add direct 64-frame GROUP mute PCM and native control ABI regressions. No alternate callback, visual redesign or speculative UI update. --- integration/ApprovedNativeControlIntent.h | 24 +++++--- src/LiveAudioEngine.h | 9 +++ src/LiveDryRoutingLab.h | 23 ++++++++ tests/approved_native_v8_projection_test.cpp | 62 ++++++++++++++++++++ tests/dynamic_accepted_session_test.cpp | 42 +++++++++++++ 5 files changed, 153 insertions(+), 7 deletions(-) diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index fb47e9386..16f2f1799 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -242,8 +242,8 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( const bool input=role=="INPUT"; const bool bus=role=="GROUP" || role=="FX_RETURN"; if(!input && !bus)return reject("CHANNEL_ROLE_NOT_MUTABLE"); - if(bus && (op=="SET_MUTE" || op=="SET_SOLO")) - return reject("BUS_MUTE_SOLO_NOT_ADMITTED"); + // A native GROUP has exactly the same ChannelId mute/solo atomics as + // an INPUT. Keep the legacy AUX distinction in the engine role gate. const auto controls=channel.getProperty("controls",{}); if(!controls.isObject())return reject("INVALID_NATIVE_CONTROLS"); const auto fader=controls.getProperty("faderDb",{}); @@ -302,7 +302,8 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( translatedPayload->setProperty("pan",acceptedPan); } else { if(!value.isBool())return reject("INVALID_MUTE_SOLO_VALUE"); - nativeOperation="NATIVE_SET_CHANNEL_MUTE_SOLO"; + nativeOperation=bus?"NATIVE_SET_BUS_MUTE_SOLO": + "NATIVE_SET_CHANNEL_MUTE_SOLO"; translatedPayload->setProperty("mute",op=="SET_MUTE"?value:mute); translatedPayload->setProperty("solo",op=="SET_SOLO"?value:solo); } @@ -419,13 +420,22 @@ inline bool executeApprovedNativeControl(Engine& engine, return engine.setNativeBusMix(epoch,revision,channel, static_cast(gain),static_cast(pan)); } - if(operation=="NATIVE_SET_CHANNEL_MUTE_SOLO") { + if(operation=="NATIVE_SET_CHANNEL_MUTE_SOLO" || + operation=="NATIVE_SET_BUS_MUTE_SOLO") { const auto mute=payload.getProperty("mute",{}); const auto solo=payload.getProperty("solo",{}); if(!mute.isBool()||!solo.isBool())return false; - return engine.setNativeInputMuteSolo(epoch,revision,channel, - static_cast(mute), - static_cast(solo)); + if(operation=="NATIVE_SET_CHANNEL_MUTE_SOLO") + return engine.setNativeInputMuteSolo(epoch,revision,channel, + static_cast(mute), + static_cast(solo)); + if constexpr(requires(Engine& e){ + e.setNativeBusMuteSolo(epoch,revision,channel,true,false); + }) + return engine.setNativeBusMuteSolo(epoch,revision,channel, + static_cast(mute), + static_cast(solo)); + return false; } return false; } diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index e140ac137..6b766fc88 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1618,6 +1618,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::diagnostics::Route::normal)return false; return dryRoutingLab_.setNativeInputMuteSolo(epoch,rev,id,mute,solo); } + bool setNativeBusMuteSolo(std::uint64_t epoch,std::uint64_t rev, + armix::mixer::ChannelId id, + bool mute,bool solo) noexcept { + if(independent_.active()||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeBusMuteSolo(epoch,rev,id,mute,solo); + } bool nativeBusTopologyLive() const noexcept { return dryRoutingLab_.nativeBusTopologyLive(); } diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index ab5e14abf..53b87b699 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1813,6 +1813,28 @@ class LiveDryRoutingLab final { return nativeAccepted_.graph.roster.rememberLiveMix(id,gain,pan); } + // Realtime GROUP/FX_RETURN mute and solo have the same verified + // ChannelId PCM target as INPUT, but NEVER mutate an original M4 AUX. + bool setNativeBusMuteSolo(std::uint64_t epochAtEdit, + std::uint64_t expectedPcmRevision, + armix::mixer::ChannelId id, + bool mute,bool solo) noexcept { + if(!channelIdPhysicalPcmActive()||epochAtEdit!=epoch()|| + expectedPcmRevision!=nativeAccepted_.pcmRevision)return false; + const auto* channel=nativeAccepted_.graph.roster.find(id); + if(!channel || (channel->role!=armix::mixer::ChannelRole::group && + channel->role!=armix::mixer::ChannelRole::fxReturn) || + originalM4Aux(id))return false; + if(!nativePublisher_.setChannelMuteSolo( + epochAtEdit,expectedPcmRevision,id,mute,solo))return false; + if(!nativeAccepted_.graph.roster.rememberLiveMuteSolo(id,mute,solo)) { + topologyFault_.store(true,std::memory_order_release); + return false; + } + nativeControlDirty_=true; + return true; + } + // CONTROL snapshot: genuine stable ChannelIds from the SAME publisher // as physical PCM. No guessed IDs, synthetic UI routes or JS DSP. juce::var nativeBusStatus() const { @@ -1837,6 +1859,7 @@ class LiveDryRoutingLab final { "NATIVE_APPLY_WIRE_TRANSACTION", "NATIVE_SET_CHANNEL_MIX", "NATIVE_SET_CHANNEL_MUTE_SOLO", + "NATIVE_SET_BUS_MUTE_SOLO", "NATIVE_LOAD_INSERT","NATIVE_SET_INSERT_BYPASS", "NATIVE_OPEN_INSERT_EDITOR"}) allowed.add(juce::var(juce::String(op))); diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index 67f7fc48b..a7b79bd19 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -33,6 +33,10 @@ struct NativeControlProbe { lastEpoch=e;lastRevision=r;lastId=id.value; lastMute=m;lastSolo=s;return true; } + bool setNativeBusMuteSolo(std::uint64_t e,std::uint64_t r, + armix::mixer::ChannelId id,bool m,bool s) { + return setNativeInputMuteSolo(e,r,id,m,s); + } }; static juce::var parse(const char* bytes) { auto json=juce::JSON::parse(juce::String::fromUTF8(bytes)); @@ -285,6 +289,63 @@ struct NativeWireProbe : NativeControlProbe { return {true,""}; } }; +static void approvedNativeGroupMuteSoloRegression() { + auto installed=realBusReadbackFixture(); + auto group=std::make_unique(); + group->setProperty("id","9007199254740994"); + group->setProperty("name","Bus A"); + group->setProperty("role","GROUP"); + group->setProperty("format","STEREO"); + group->setProperty("primaryOutput","0"); + group->setProperty("fader",1.0); + group->setProperty("pan",0.0); + group->setProperty("mute",false); + group->setProperty("solo",false); + group->setProperty("inserts",juce::var(juce::Array{})); + installed.getProperty("channels",{}).getArray()->add( + juce::var(group.release())); + juce::Array nativeOps;nativeOps.add("NATIVE_SET_BUS_MUTE_SOLO"); + installed.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + auto publicSnapshot=canonicalSnapshot(); + assert(projectApprovedNativeV8(publicSnapshot,installed,true)); + juce::Array publicOps; + publicOps.add("SET_MUTE");publicOps.add("SET_SOLO"); + publicSnapshot.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + auto makeRequest=[&](const char* op,bool newValue,const char* id){ + auto payload=std::make_unique(); + payload->setProperty("value",newValue); + auto request=std::make_unique(); + request->setProperty("requestId","group-control-1"); + request->setProperty("deviceEpoch","91"); + request->setProperty("baseGraphRevision","25"); + request->setProperty("baseRosterRevision","9"); + request->setProperty("targetChannelId",id); + request->setProperty("operation",op); + request->setProperty("payload",juce::var(payload.release())); + return juce::var(request.release()); + }; + NativeControlProbe probe; + const auto busId="9007199254740994"; + auto muted=translateApprovedNativeControl( + makeRequest("SET_MUTE",true,busId),publicSnapshot,installed); + assert(muted.ok()); + assert(muted.translated.getProperty("operation","").toString()== + "NATIVE_SET_BUS_MUTE_SOLO"); + assert(executeApprovedNativeControl(probe,muted.translated)); + assert(probe.lastId==9007199254740994ULL&&probe.lastMute&&!probe.lastSolo); + auto solo=translateApprovedNativeControl( + makeRequest("SET_SOLO",true,busId),publicSnapshot,installed); + assert(solo.ok()); + assert(executeApprovedNativeControl(probe,solo.translated)); + assert(probe.lastSolo&&!probe.lastMute); + // MAIN remains immutable through the BUS-specific control gate. + auto denied=translateApprovedNativeControl( + makeRequest("SET_MUTE",true,"18446744073709551615"), + publicSnapshot,installed); + assert(!denied.ok()); +} + static void approvedNativeVst3LoadContractRegression( const juce::var& canonical,const juce::var& producer) { // Native VST3 command admission is independent of a fabricated vendor @@ -852,6 +913,7 @@ int main() { controlIntentTranslationCases(snap,bus); nativeInsertCatalogInstanceProjectionRegression(); + approvedNativeGroupMuteSoloRegression(); approvedNativeVst3LoadContractRegression(snap,bus); approvedWireTranslationRegression(snap,bus); installedCallbackAdmissionRegression(bus); diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index 7333fadaf..5aab81422 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -723,7 +723,49 @@ static void verifySourceOnlyParallelMainVsExclusivePrimaryPcm() { assert(render()&&near(l[9],.25f*center)); } +// Actual GROUP post-insert PCM must be silenced by its own realtime MUTE, +// with no graph rebuild, physical source reset or lost monitor state. +static void verifyGroupMuteAffectsRealNativePcm() { + constexpr std::uint64_t ep=99222; + DynamicAcceptedSession pcm; + DynamicGraphRequest io;io.physicalInputs=1;io.maxFrames=64; + const std::array created{ + add(0,ChannelRole::input,"VOICE"), + add(1,ChannelRole::group,"BUS A",ProcessingFormat::stereo), + add(2,ChannelRole::main,"MAIN",ProcessingFormat::stereo) + }; + auto state=pcm.edit(0,0,created,io,ep,ep,true); + assert(state.ok()&&state.edit.createdIds.size()==3); + const auto voice=state.edit.createdIds[0]; + const auto bus=state.edit.createdIds[1]; + const auto main=state.edit.createdIds[2]; + io.sources={{voice,0,-1,false}}; + const std::array serial{output(voice,bus),output(bus,main)}; + state=pcm.edit(1,1,serial,io,ep,ep,true); + assert(state.ok()&&pcm.acceptedGraphRevision()==2); + std::array mono{},l{},r{}; + mono.fill(.25f); + const float* pins[]{mono.data()}; + const auto render=[&]{ + return pcm.render(ep,pins,1,l.data(),r.data(),64,false, + +[](ChannelId,float*,float*,int) noexcept {}); + }; + assert(render()); + const float audible=l[63]; + assert(audible>.05f&&near(r[63],audible)); + assert(pcm.setLiveMuteSolo(ep,2,bus,true,false)); + assert(render()&&near(l[63],0.f,1e-4f)&&near(r[63],0.f,1e-4f)); + assert(pcm.acceptedRoster().find(bus)->mute); + assert(pcm.setLiveMuteSolo(ep,2,bus,false,false)); + assert(render()&&near(l[63],audible,1e-4f)&&near(r[63],audible,1e-4f)); + assert(!pcm.setLiveMuteSolo(ep-1,2,bus,true,false)); + assert(!pcm.setLiveMuteSolo(ep,1,bus,true,false)); + assert(pcm.acceptedGraphRevision()==2); + assert(render()&&near(l[63],audible,1e-4f)); +} + int main() { + verifyGroupMuteAffectsRealNativePcm(); verifySourceOnlyParallelMainVsExclusivePrimaryPcm(); verifyHeldDragIntermediatePcmOnOriginalChannels(); verifyOriginalAndAddedInputsShareNativePcmControls(); From def768f3cb2cb82f4f422e760eb6bd8082f72aa6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 12:45:33 +0700 Subject: [PATCH 089/219] build(fat): attest Windows ZIP to exact PR #418 source HEAD Checkout the PR branch commit rather than synthetic merge when preparing native FAT binaries, fail early on source SHA mismatch, retain embedded binary/ZIP provenance checks. Remove now-unused implicit-MAIN identifier after CONNECT/ROUTE_ONLY separation. --- .github/workflows/p1-windows.yml | 16 ++++++++++++++++ engine/core/DynamicChannelRoster.h | 1 - 2 files changed, 16 insertions(+), 1 deletion(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 5a4ffb9a4..2eb9698c7 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -59,7 +59,23 @@ jobs: runs-on: windows-2022 timeout-minutes: 50 steps: + # PR builds must package the exact branch HEAD, not GitHub's synthetic + # pull/418/merge checkout. BUILD_PROVENANCE.json records this SHA and the + # artifact verifier compares the embedded EXE, files and source tree. - uses: actions/checkout@v4 + with: + ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} + - name: Verify FAT checkout matches exact PR source HEAD + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} + shell: pwsh + env: + EXPECTED_SOURCE_SHA: ${{ github.event.pull_request.head.sha }} + run: | + $actual = (& git rev-parse HEAD).Trim() + if ($LASTEXITCODE -ne 0 -or $actual -ne $env:EXPECTED_SOURCE_SHA) { + throw "FAT_SOURCE_HEAD_MISMATCH expected=$env:EXPECTED_SOURCE_SHA actual=$actual" + } + Write-Host "FAT_EXACT_PR_HEAD_CHECKOUT=$actual" - name: Cheap canonical Console v6 puzzle socket gate (no JUCE) run: node scripts/check_console_puzzle.mjs - name: Stop incomplete integrated product promotion before JUCE checkout diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index e6b8f118b..20868d49c 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -355,7 +355,6 @@ class DynamicChannelRoster final { const auto main=std::find_if(candidate.begin(),candidate.end(), [](const auto& ch){return ch.role==ChannelRole::main;}); if(main==candidate.end()){result.fault=ChannelEditFault::invalidAction;return result;} - const ChannelId mainId=main->id; std::uint64_t stagedNextEdge=nextEdgeId_; if(!assignMissingEdgeIds(candidate,stagedNextEdge)){ result.fault=ChannelEditFault::idExhausted;return result; From 53bdba61239aa6bb836f8c97aca6f596cf7a76a6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:01:14 +0700 Subject: [PATCH 090/219] fix(p0): project VST catalog and rack bypass in the actually compiled integration header Windows CTest #6 proved the runtime includes integration/ApprovedNativeV8Projection.h, not similarly named src/ file. Preserve independent instance/catalog identities in active graph, export authoritative rack bypass readback, validate both with real C++ projection assertions and source-of-truth test. Retain fail-closed malformed identity behavior. --- integration/ApprovedNativeV8Projection.h | 18 ++++++++++++++++-- tests/approved_native_m2_contract.test.cjs | 3 +++ tests/approved_native_v8_projection_test.cpp | 4 ++++ 3 files changed, 23 insertions(+), 2 deletions(-) diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index a2f6b3ee1..b43f0293a 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -81,15 +81,29 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, ch->setProperty("controls",juce::var(controls.release())); juce::Array fx; for(const auto& item:*inserts.getArray()){ + // This integration/ header is the one included by the live native + // runtime snapshot. The src/ counterpart is NOT its replacement. + // id is the installed processor token; catalogId is the vendor + // identity used for the command and subsequent ACK/readback. const auto token=item.getProperty("instanceId",{}),label=item.getProperty("name",{}); + const auto catalog=item.getProperty("id",{}); const auto bypass=item.getProperty("bypassed",{}); - if(!token.isString()||!label.isString()||!bypass.isBool())return false; + if(!token.isString()||token.toString().isEmpty()|| + !catalog.isString()||catalog.toString().isEmpty()|| + catalog.toString().getNumBytesAsUTF8()>256|| + !label.isString()||!bypass.isBool())return false; auto insert=std::make_unique(); - insert->setProperty("id",token);insert->setProperty("name",label); + insert->setProperty("id",token);insert->setProperty("catalogId",catalog); + insert->setProperty("name",label); insert->setProperty("bypassed",bypass); fx.add(juce::var(insert.release())); } ch->setProperty("inserts",juce::var(fx)); + const auto rackBypassed=row.getProperty("fxRackBypassed",{}); + if(!rackBypassed.isVoid()) { + if(!rackBypassed.isBool())return false; + ch->setProperty("fxRackBypassed",rackBypassed); + } ch->setProperty("sends",juce::var(juce::Array{})); if(role!="INPUT"){ auto dst=std::make_unique(); diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index b5563c8b1..658c6bad2 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -196,6 +196,9 @@ test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual const contract=read("web/approved-native-contract.js"); const translate=read("integration/ApprovedNativeControlIntent.h"); const snapshot=read("integration/ApprovedNativeRuntimeSnapshot.h"); + const activeProjection=read("integration/ApprovedNativeV8Projection.h"); + assert.match(activeProjection,/insert->setProperty\("catalogId",catalog\)/); + assert.match(activeProjection,/ch->setProperty\("fxRackBypassed",rackBypassed\)/); assert.match(bridge,/controller\.intent\("LOAD_INSERT",nativeId,/); assert.match(bridge,/legacy\(\)\?\.nativeBusStructural===true/); assert.match(lab,/nativeAccepted_\.fxOwners->externalChannel\(\)==target/); diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index a7b79bd19..dee37c83d 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -85,6 +85,8 @@ static void nativeInsertCatalogInstanceProjectionRegression() { inserts.add(juce::var(item.release())); source.getProperty("channels",{})[0].getDynamicObject() ->setProperty("inserts",juce::var(inserts)); + source.getProperty("channels",{})[0].getDynamicObject() + ->setProperty("fxRackBypassed",true); auto snapshot=canonicalSnapshot(); assert(projectApprovedNativeV8(snapshot,source,true)); const auto live=snapshot.getProperty("graph",{}) @@ -92,6 +94,8 @@ static void nativeInsertCatalogInstanceProjectionRegression() { assert(live.getProperty("id","").toString()=="vst3-instance-unique-7"); assert(live.getProperty("catalogId","").toString()=="vendor.eq.catalog"); assert(!static_cast(live.getProperty("bypassed",true))); + assert(static_cast(snapshot.getProperty("graph",{}) + .getProperty("channels",{})[0].getProperty("fxRackBypassed",false))); // A missing catalog token must not be projected as a verified processor. auto invalid=juce::JSON::parse(juce::JSON::toString(source,false)); invalid.getProperty("channels",{})[0].getProperty("inserts",{})[0] From a5da8dd69955102b0473537f27fd38c43b7d614a Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:26:17 +0700 Subject: [PATCH 091/219] fix(p0): validate ROUTE_ONLY PCM readback without rejecting preserved parallel MAIN sends --- web/approved-native-contract.js | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 0ef623c7f..1e57727ac 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -177,10 +177,17 @@ if (pending.originalPrimaryOutId && pending.originalPrimaryOutId!==edit.to && edges.some(e=>e.from===edit.from&& - e.to===pending.originalPrimaryOutId)) + e.to===pending.originalPrimaryOutId&& + // A remembered parallel send is NOT the former primary. + // Unknown/legacy edge identity stays fail-closed. + e.primaryOutput!==false)) return false; if (edit.to!==next.graph.mainChannelId && - edges.some(e=>e.from===edit.from&&e.to===next.graph.mainChannelId)) + edges.some(e=>e.from===edit.from&& + e.to===next.graph.mainChannelId&& + // ROUTE_ONLY replaces only the primary. A deliberate + // independent parallel MAIN send must remain audible. + e.primaryOutput!==false)) return false; } return true; From 2f499b1f78d33ee59ff9ac2ae8243a068e76aafb Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:27:10 +0700 Subject: [PATCH 092/219] test(p0): native ACK/readback for SOURCE ONLY and BUS route with retained parallel MAIN --- tests/approved_native_m2_contract.test.cjs | 79 ++++++++++++++++++++++ 1 file changed, 79 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 658c6bad2..b5e66ed75 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -254,6 +254,85 @@ test("Native VST3 insert ACK + readback distinguishes vendor catalog key from li assert.equal(accepted.at(-1).graph.channels[0].inserts[0].id,"vst3-instance-unique-7"); assert.ok(sent.some(evt=>evt.name==="arMixConsoleSubscribe")); }); +test("WIRE ROUTE ONLY to BUS preserves explicit MAIN parallel send after native ACK and readback",()=>{ + const before=acceptedFixture(); + const source=before.graph.channels[0], main=before.graph.mainChannelId; + const oldBus="9007199254740994",newBus="9007199254740995"; + const group=id=>({id,role:"GROUP",name:id===oldBus?"BUS A":"BUS B", + processingFormat:"STEREO",primaryOutId:main, + controls:{faderDb:0,pan:0,mute:false,solo:false},inserts:[],sends:[]}); + before.graph.channels.splice(1,0,group(oldBus),group(newBus)); + before.graph.destinations=[{id:oldBus},{id:newBus},{id:main}]; + source.primaryOutId=oldBus; + source.source={sourceFormat:"MONO",portId:"in:0"}; + const mkEdge=(id,from,to,primary)=>({edgeId:id,from,to, + tap:"POST_FADER",gainLinear:1,enabled:true,signalKind:"AUDIO", + primaryOutput:primary}); + before.graph.edges=[ + mkEdge("9223372036854775808",source.id,oldBus,true), + mkEdge("9223372036854775809",source.id,main,false), + mkEdge("9223372036854775810",oldBus,main,true), + mkEdge("9223372036854775811",newBus,main,true) + ]; + const events=[],controller=protocol.createController({ + emit:(name,payload)=>events.push({name,payload})}); + assert.equal(controller.onSnapshot(before),true); + assert.equal(controller.state().current.admitted,true); + const change={op:"ROUTE_ONLY",from:source.id,to:newBus, + tap:"POST_FADER",gainLinear:1}; + const submitted=controller.intent("APPLY_WIRE_TRANSACTION",source.id, + {changes:[change]}); + assert.equal(submitted.ok,true); + const after=clone(before); + after.graph.revision="6";after.graph.rosterRevision="8"; + after.graph.channels[0].primaryOutId=newBus; + after.graph.edges[0].to=newBus; // exact native EdgeId promoted/retargeted + assert.equal(controller.onAck({requestId:submitted.requestId,status:"ACCEPTED", + deviceEpoch:before.device.epoch,graphRevision:"6",rosterRevision:"8", + errorCode:"NONE"}),true); + assert.equal(controller.state().lastError,"PENDING_ACCEPTED_SNAPSHOT"); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK", + "verified ROUTE_ONLY must not reject intentionally preserved parallel MAIN"); + assert.equal(controller.state().current.graph.channels[0].primaryOutId,newBus); + assert.equal(controller.state().current.graph.edges.find(e=> + e.edgeId==="9223372036854775809").primaryOutput,false); + assert.ok(events.some(e=>e.name==="arMixConsoleSubscribe")); + const invalid=clone(after); + invalid.graph.edges[1].primaryOutput=true; + const pending={operation:"APPLY_WIRE_TRANSACTION",targetChannelId:source.id, + baseGraphRevision:"5",baseRosterRevision:"7", + originalPrimaryOutId:oldBus,payload:{changes:[change]}}; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(invalid),pending),false, + "a second MAIN primary must still fail closed"); + invalid.graph.edges[1].primaryOutput=false; + invalid.graph.edges[0].to=oldBus; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(invalid),pending),false, + "old primary may not survive as an independent cable"); +}); +test("WIRE SOURCE ONLY readback retains physical input but removes primary MAIN",()=>{ + const before=acceptedFixture(); + const source=before.graph.channels[0]; + before.graph.edges[0].primaryOutput=true; + source.source={sourceFormat:"MONO",portId:"in:0"}; + const after=clone(before); + after.graph.revision="6";after.graph.rosterRevision="8"; + delete after.graph.channels[0].primaryOutId; + after.graph.edges=[]; + const controller=protocol.createController({emit:()=>{}}); + assert.equal(controller.onSnapshot(before),true); + const cmd=controller.intent("APPLY_WIRE_TRANSACTION",source.id,{changes:[ + {op:"REMOVE",from:source.id,edgeId:before.graph.edges[0].edgeId} + ]}); + assert.equal(cmd.ok,true); + assert.equal(controller.onAck({requestId:cmd.requestId,status:"ACCEPTED", + deviceEpoch:before.device.epoch,graphRevision:"6",rosterRevision:"8", + errorCode:"NONE"}),true); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK"); + assert.equal(controller.state().current.graph.channels[0].source.portId,"in:0"); + assert.equal(controller.state().current.graph.channels[0].primaryOutId,undefined); +}); test("P0 first Add FX discovers real local VST3 lazily without an audio-thread scan",()=>{ const bridge=read("web/approved-native-bridge.js"); const native=read("src/Main.cpp"); From a7b9590ff9c08e5e30215117cfa89a6a256374f0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:29:26 +0700 Subject: [PATCH 093/219] test(p0): sample-backed BUS primary retarget preserves parallel MAIN and exact EdgeId detach --- tests/dynamic_accepted_session_test.cpp | 33 +++++++++++++++++++++++++ 1 file changed, 33 insertions(+) diff --git a/tests/dynamic_accepted_session_test.cpp b/tests/dynamic_accepted_session_test.cpp index 5aab81422..85c1d3eb7 100644 --- a/tests/dynamic_accepted_session_test.cpp +++ b/tests/dynamic_accepted_session_test.cpp @@ -409,6 +409,39 @@ static void verifyAtomicWireTransactionAndZeroSampleHops() { assert(findEdge(one,main,13)!=0); assert(session.acceptedRouting(epoch,13)->find(one)->primaryOutput==main); assert(render() && near(left[11],.3f*center,1e-4f)); + + // Installed PCM regression: a deliberate parallel MAIN send must survive + // a later exclusive BUS retarget. The GUI used to reject the successful + // readback merely because it saw any MAIN edge, even a NON-primary send. + a=session.wireTransaction(13,13,hop1,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==14); + assert(findEdge(one,two,14) && !findEdge(one,main,14)); + const std::array extraMain{connect(one,main,.25f)}; + a=session.wireTransaction(14,14,extraMain,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==15); + const auto preservedSend=findEdge(one,main,15); + assert(preservedSend && render() && + near(left[11],.3f*1.25f*center,1e-4f)); + const std::array switchBus{routeOnly(one,three)}; + a=session.wireTransaction(15,15,switchBus,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==16); + const auto* preserved=session.acceptedRouting(epoch,16); + assert(preserved && preserved->find(one)->primaryOutput==three); + assert(!findEdge(one,two,16) && findEdge(one,main,16)==preservedSend); + const auto parallelNative=std::find_if(preserved->edges.begin(), + preserved->edges.end(),[&](const auto& edge) { + return edge.edgeId==preservedSend; + }); + assert(parallelNative!=preserved->edges.end() && + !parallelNative->primaryOutput); + assert(render() && near(left[11],.3f*1.25f*center,1e-4f)); + // Detach the independent parallel MAIN send by the same stable EdgeId, + // keeping the BUS primary and returning to exactly one PCM path. + const std::array removeExtra{remove(one,preservedSend)}; + a=session.wireTransaction(16,16,removeExtra,physical,epoch,epoch,false); + assert(a.ok() && a.graphRevision==17); + assert(!findEdge(one,main,17) && findEdge(one,three,17)); + assert(render() && near(left[11],.3f*center,1e-4f)); session.unpublish(); session.pollRetirement(); } From b727887da87d3d9ea24d274bcabe3a6a376ac38b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:35:12 +0700 Subject: [PATCH 094/219] feat(p0): retain native FX leases with processing format across live PCM graph changes --- engine/core/DynamicChannelFxLeaseBank.h | 32 +++++++++++++++++++++++++ 1 file changed, 32 insertions(+) diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index 36499a531..42c7d272f 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -230,6 +230,38 @@ class DynamicChannelFxLeaseBank final { return prepare(epoch,revision,retained,destination,prior.external_); } + // Processing MONO/STEREO is a DSP lane property, not a device pin change. + // Rebind the vendor lease's matching format atomically with the PCM + // topology; otherwise a later insert would see stale format metadata. + // Never duplicate, reset or instantiate a live processor on this path. + static Fault reuseWithProcessingFormat( + std::uint64_t epoch,std::uint64_t revision, + const DynamicChannelFxLeaseBank& prior,ChannelId target, + ProcessingFormat format,DynamicChannelFxLeaseBank& destination) { + if(!epoch || epoch!=prior.epoch_ || revision<=prior.revision_) + return Fault::invalidEpoch; + if(!target.value || prior.external_.id==target) + return Fault::invalidExternalLease; + if(format!=ProcessingFormat::mono && format!=ProcessingFormat::stereo) + return Fault::invalidBusLayout; + std::vector retained; + retained.reserve(prior.rows_.size()); + bool found=false; + for(const auto& row:prior.rows_) { + Assignment item; + item.id=row.id; + item.format=row.id==target?format:row.format; + item.rackBypassed=row.rackBypassed; + item.inserts.reserve(row.count); + for(std::size_t slot=0;slot Date: Fri, 6 Nov 2026 13:35:39 +0700 Subject: [PATCH 095/219] feat(p0): publish native ChannelId MONO/STEREO processing changes without M4 fallback --- src/LiveDryRoutingLab.h | 82 +++++++++++++++++++++++++++++++++++++++++ 1 file changed, 82 insertions(+) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 53b87b699..323d90e4d 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1458,6 +1458,88 @@ class LiveDryRoutingLab final { } } + // User-facing M/ST toggle after ChannelId takes over. This changes + // processing width and pan semantics, NOT physical source pins, OUT + // routing or the operator's MONITOR state. Reuse vendor leases and + // publish the complete accepted PCM DAG atomically from CONTROL. + NativeBusResult editNativeProcessingFormat( + std::uint64_t expectedEpoch,std::uint64_t expectedPcmRevision, + std::uint64_t expectedRosterRevision,armix::mixer::ChannelId channel, + armix::mixer::ProcessingFormat format,bool outputsDisarmed=false, + const std::function& beforePublish={}) { + using namespace armix::mixer; + NativeBusResult reply{}; + reply.pcmRevision=nativeAccepted_.pcmRevision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + if(!outputsDisarmed){ + reply.error="PROCESSING_FORMAT_REQUIRES_PUBLICATION_GATE";return reply; + } + if(!channelIdPhysicalPcmActive()||!ready()|| + expectedEpoch!=epoch()||nativeAccepted_.deviceEpoch!=expectedEpoch|| + !nativeAccepted_.fxOwners|| + expectedPcmRevision!=nativeAccepted_.pcmRevision|| + expectedRosterRevision!=nativeAccepted_.graph.roster.revision()) { + reply.error="STALE_NATIVE_PROCESSING_GRAPH";return reply; + } + const auto* current=nativeAccepted_.graph.roster.find(channel); + if(!current || current->role!=ChannelRole::input || + (format!=ProcessingFormat::mono && format!=ProcessingFormat::stereo) || + current->format==format) { + reply.error="INVALID_NATIVE_PROCESSING_FORMAT";return reply; + } + // CH1 may have an externally leased vendor graph. Its width needs + // an explicit combined VST contract; do not reassign that owner here. + if(nativeAccepted_.fxOwners->externalChannel()==channel) { + reply.error="EXTERNAL_VST_LAYOUT_NOT_ADMITTED";return reply; + } + try { + auto roster=nativeAccepted_.graph.roster; + ChannelEdit edit; + edit.kind=ChannelEdit::Kind::setFormat; + edit.id=channel; + edit.format=format; + const std::array edits{edit}; + if(!roster.edit(expectedRosterRevision,edits).ok()) { + reply.error="NATIVE_PROCESSING_ROSTER_REJECTED";return reply; + } + DynamicChannelFxLeaseBank bank; + if(DynamicChannelFxLeaseBank::reuseWithProcessingFormat( + expectedEpoch,expectedPcmRevision+1, + *nativeAccepted_.fxOwners,channel,format,bank)!= + DynamicChannelFxLeaseBank::Fault::none) { + reply.error="NATIVE_PROCESSING_FX_REBIND_REJECTED";return reply; + } + auto owner=std::make_shared( + std::move(bank)); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(owner); + fx.context=owner.get(); + fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + fx.deviceEpoch=expectedEpoch; + fx.graphRevision=expectedPcmRevision+1; + if(beforePublish)beforePublish(); // no hardware mute during prepare + const auto published=nativePublisher_.commit( + roster,nativeAccepted_.graph.request,expectedPcmRevision, + expectedEpoch,epoch(),true,std::move(fx)); + if(!published.ok()) { + reply.error="NATIVE_PROCESSING_PCM_COMMIT_REJECTED";return reply; + } + nativeAccepted_.graph.roster=std::move(roster); + nativeAccepted_.fxOwners=std::move(owner); + nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; // never restore stale M4 width + nativeMeterEpoch_.store(0,std::memory_order_release); + reply.accepted=true;reply.error=""; + reply.pcmRevision=published.revision; + reply.rosterRevision=nativeAccepted_.graph.roster.revision(); + return reply; + } catch(...) { + reply.error="NATIVE_PROCESSING_PREPARE_FAILED";return reply; + } + } + // Product Console: a NEW stable ChannelId input, not a fixed M4 ordinal // or an unowned JS strip. Starts unpatched and silent. Structural graph, // old vendor FX leases and MAIN routing publish as ONE control transaction. From 160fa54233b7ad00e5b53cf1f046f49a79742d81 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:36:01 +0700 Subject: [PATCH 096/219] feat(p0): JUCE host gate for live ChannelId M/ST processing with MONITOR preservation --- src/LiveAudioEngine.h | 44 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 6b766fc88..79d4d18b0 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1432,6 +1432,50 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return rejected; } } + // Processing M/ST is an accepted ChannelId PCM topology transaction. + // The host gates physical output only at publication, then preserves + // the operator's original MONITOR decision on the same verified device. + LiveDryRoutingLab::NativeBusResult editNativeProcessingFormat( + std::uint64_t epoch,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,armix::mixer::ChannelId id, + armix::mixer::ProcessingFormat format) { + LiveDryRoutingLab::NativeBusResult rejected{}; + rejected.error="NATIVE_PROCESSING_DEVICE_UNAVAILABLE"; + if(independent_.active()||!attached_||secondaryOutput_.armed()|| + !directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0) + return rejected; + const bool wasMonitoring=isMonitorEnabled(); + bool publishing=false; + try { + const auto result=dryRoutingLab_.editNativeProcessingFormat( + epoch,pcmRevision,rosterRevision,id,format,true,[&] { + publishing=true; + if(wasMonitoring)topologyPublicationMute_.store( + true,std::memory_order_release); + }); + if(publishing) { + if(wasMonitoring && + !armix::mixer::NativeTopologyEditSafety::mayRestoreMonitor( + wasMonitoring,epoch==dryRoutingLab_.epoch(), + liveOutputArmFault(false).isEmpty(), + secondaryOutput_.armed())) + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + return result; + } catch(...) { + if(publishing) { + setOutputMuted(true); + topologyPublicationMute_.store(false,std::memory_order_release); + } + rejected.error="NATIVE_PROCESSING_PUBLICATION_EXCEPTION"; + return rejected; + } + } // User-owned VST3 on a true dynamic ChannelId. Instantiation/scan/layout // work is CONTROL only; the callback receives an immutable fx lease. LiveDryRoutingLab::NativeBusResult installNativeVst3( From 6f184111c3c6d959c375dd8495fadeb0d4155218 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:36:19 +0700 Subject: [PATCH 097/219] feat(p0): advertise processing-width edit only from installed native PCM publisher --- src/LiveDryRoutingLab.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 323d90e4d..2c5aeb9ed 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1939,6 +1939,7 @@ class LiveDryRoutingLab final { "NATIVE_CREATE_CHANNEL","NATIVE_PATCH_CHANNEL", "NATIVE_SET_PRIMARY_OUT", "NATIVE_APPLY_WIRE_TRANSACTION", + "NATIVE_SET_PROCESSING_FORMAT", "NATIVE_SET_CHANNEL_MIX", "NATIVE_SET_CHANNEL_MUTE_SOLO", "NATIVE_SET_BUS_MUTE_SOLO", From 86d387e08640f27065a6d13f9418d01429e7a33b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:36:23 +0700 Subject: [PATCH 098/219] feat(p0): project admitted ChannelId processing-format command to existing GUI --- integration/ApprovedNativeRuntimeSnapshot.h | 2 ++ 1 file changed, 2 insertions(+) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 69753dcd6..c76a57b73 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -282,6 +282,8 @@ inline bool projectInstalledNativeChannelIdGraph( // gesture as NOT_ADMITTED. Admit only the actual installed operation. if(has("NATIVE_APPLY_WIRE_TRANSACTION")) available.add(juce::String("APPLY_WIRE_TRANSACTION")); + if(has("NATIVE_SET_PROCESSING_FORMAT")) + available.add(juce::String("SET_PROCESSING_FORMAT")); if(has("NATIVE_LOAD_INSERT")) available.add(juce::String("LOAD_INSERT")); if(has("NATIVE_CREATE_GROUP_SELECTED")) From 249133b3b69129e99dfdcf2f87edc4c6360bfdfe Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:36:48 +0700 Subject: [PATCH 099/219] feat(p0): validate and execute approved native M/ST intent against single PCM graph --- integration/ApprovedNativeControlIntent.h | 55 +++++++++++++++++++++++ 1 file changed, 55 insertions(+) diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index 16f2f1799..f81a695dd 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -70,6 +70,44 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( return reject("STALE_NATIVE_CONTROL_REVISION"); if(!request.isString() || request.toString().isEmpty() || request.toString().length()>128)return reject("INVALID_REQUEST_ID"); + // A true ChannelId processing M/ST edit is structural PCM, never an + // M4 ordinal patch. Check both independent producer and public contracts + // before passing device/graph/roster-fenced native identities. + if(op=="SET_PROCESSING_FORMAT") { + if(!approvedHasOperation(caps.getProperty("supportedOps",{}), + "SET_PROCESSING_FORMAT") || + !approvedHasOperation(installedBus.getProperty("supportedOps",{}), + "NATIVE_SET_PROCESSING_FORMAT")) + return reject("NATIVE_PROCESSING_FORMAT_NOT_ADMITTED"); + juce::var owner,producer; + for(const auto& row:*rows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())owner=row; + for(const auto& row:*nativeRows.getArray()) + if(row.getProperty("id","").toString()==ids.toString())producer=row; + if(!owner.isObject()||!producer.isObject()|| + owner.getProperty("role","").toString()!="INPUT" || + producer.getProperty("role","").toString()!="INPUT" || + owner.getProperty("processingFormat","").toString()!= + producer.getProperty("format","").toString()) + return reject("PROCESSING_FORMAT_SOURCE_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto fmt=payload.getProperty("format",{}); + if(!payload.isObject()||!fmt.isString()|| + (fmt.toString()!="MONO"&&fmt.toString()!="STEREO")|| + fmt.toString()==producer.getProperty("format","").toString()) + return reject("INVALID_NATIVE_PROCESSING_FORMAT"); + auto checked=std::make_unique(); + checked->setProperty("format",fmt); + auto converted=std::make_unique(); + converted->setProperty("requestId",request); + converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster); + converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_SET_PROCESSING_FORMAT"); + converted->setProperty("payload",juce::var(checked.release())); + return {juce::var(converted.release()),{}}; + } // P1 WIRE: the previous GUI emitted APPLY_WIRE_TRANSACTION, but this // translator accepted only fader/pan/mute/solo and silently left native // BUS routing unavailable. Validate the exact accepted ChannelId/EdgeId @@ -351,6 +389,23 @@ inline bool executeApprovedNativeControl(Engine& engine, if(!payload.isObject())return false; const auto operation=translated.getProperty("operation","").toString(); const auto channel=armix::mixer::ChannelId{id}; + if(operation=="NATIVE_SET_PROCESSING_FORMAT") { + const auto format=payload.getProperty("format",{}); + if(!format.isString()|| + (format.toString()!="MONO"&&format.toString()!="STEREO")) + return false; + const auto mode=format.toString()=="MONO"? + armix::mixer::ProcessingFormat::mono: + armix::mixer::ProcessingFormat::stereo; + if constexpr(requires(Engine& e,armix::mixer::ProcessingFormat width) { + e.editNativeProcessingFormat(epoch,revision,roster,channel,width); + }) { + const auto changed=engine.editNativeProcessingFormat( + epoch,revision,roster,channel,mode); + return changed.accepted && changed.error!=nullptr && + changed.error[0]=='\\0'; + } else return false; + } if(operation=="NATIVE_APPLY_WIRE_TRANSACTION") { const auto raw=payload.getProperty("changes",{}); const auto* edits=raw.getArray(); From 6b81d2da7e166c5cec1a3d3c38ec379d3370b5f7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:37:12 +0700 Subject: [PATCH 100/219] fix(p0): use exact zero-byte status for native M/ST ACK ABI --- integration/ApprovedNativeControlIntent.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index f81a695dd..f5e8367b3 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -403,7 +403,7 @@ inline bool executeApprovedNativeControl(Engine& engine, const auto changed=engine.editNativeProcessingFormat( epoch,revision,roster,channel,mode); return changed.accepted && changed.error!=nullptr && - changed.error[0]=='\\0'; + changed.error[0]==0; } else return false; } if(operation=="NATIVE_APPLY_WIRE_TRANSACTION") { From 8850f72aabea204f5a8473305761116801a6e9ce Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:37:34 +0700 Subject: [PATCH 101/219] feat(p0): route GUI M/ST through native ChannelId PCM when BUS/WIRE owns graph --- web/approved-native-bridge.js | 23 +++++++++++++++++++++++ 1 file changed, 23 insertions(+) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index c7f6a9b36..b79aa97b1 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -278,6 +278,29 @@ let lastM4PortSignature="",pendingOutputPatch=null,m4RequestSerial=0,outputSerial=7000; const pendingSourceQueue=new Map(); function requestProcessingFormat(t){ + // Once the native ChannelId callback owns PCM, the old M4 routing + // revision is no longer authoritative. Send M/ST through the SAME + // admitted epoch/revision/roster transaction as WIRE and SOURCE. + if(mixerSession()?.authority==="CHANNEL_ID"){ + const current=controller?.state()?.current; + const channelId=nativeIdFor(t); + const source=current?.graph?.channels?.find(ch=>ch.id===channelId); + if(!current?.admitted || !channelId || source?.role!=="INPUT" || + !current.graph.capabilities.supportedOps.includes("SET_PROCESSING_FORMAT")){ + status("M/ST unavailable · native processing format not admitted"); + return false; + } + const target=source.processingFormat==="MONO"?"STEREO":"MONO"; + const request=controller.intent("SET_PROCESSING_FORMAT",channelId, + {format:target}); + if(!request.ok){ + status("M/ST rejected · "+request.error); + return false; + } + window.setTimeout(()=>controller?.expire(request.requestId),8000); + status(t.name+" M/ST → "+target+" · verifying native PCM readback"); + return true; + } const channel=m4Index(t); const ep=safeNativeCounter(hardware?.device?.epoch), rev=safeNativeCounter(legacy()?.routingRevision); From 5b3fa9dbcef6a79add0802c177737f0a530eff06 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:37:38 +0700 Subject: [PATCH 102/219] feat(p0): require independent accepted PCM roster and channel width readback after M/ST --- web/approved-native-contract.js | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 1e57727ac..de5d50a00 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -116,6 +116,11 @@ if (operation === "SET_MUTE" || operation === "SET_SOLO") return typeof payload.value==="boolean" && ch.controls[operation==="SET_MUTE"?"mute":"solo"]===payload.value; + if (operation === "SET_PROCESSING_FORMAT") + return ["MONO","STEREO"].includes(payload.format) && + cmp(next.graph.revision,pending.baseGraphRevision)>0 && + cmp(next.graph.rosterRevision,pending.baseRosterRevision)>0 && + ch.processingFormat===payload.format; if (operation === "LOAD_INSERT") return cmp(next.graph.revision,pending.baseGraphRevision)>0 && cmp(next.graph.rosterRevision,pending.baseRosterRevision)>0 && From ec2bf8b37bbc9446fe6efd476f9d6b926f1f3f23 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:38:00 +0700 Subject: [PATCH 103/219] test(p0): admitted M/ST native ACK, exact PCM width readback, stale roster and bridge authority --- tests/approved_native_m2_contract.test.cjs | 39 ++++++++++++++++++++++ 1 file changed, 39 insertions(+) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index b5e66ed75..24e69b530 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -333,6 +333,45 @@ test("WIRE SOURCE ONLY readback retains physical input but removes primary MAIN" assert.equal(controller.state().current.graph.channels[0].source.portId,"in:0"); assert.equal(controller.state().current.graph.channels[0].primaryOutId,undefined); }); +test("M/ST after BUS/WIRE uses native ChannelId intent and accepted PCM processing width",()=>{ + const before=acceptedFixture(); + before.graph.capabilities.supportedOps.push("SET_PROCESSING_FORMAT"); + before.graph.channels[0].source={sourceFormat:"MONO",portId:"in:0"}; + const source=before.graph.channels[0].id,events=[]; + const controller=protocol.createController({emit:(name,payload)=> + events.push({name,payload})}); + assert.equal(controller.onSnapshot(before),true); + const change=controller.intent("SET_PROCESSING_FORMAT",source,{format:"STEREO"}); + assert.equal(change.ok,true); + assert.equal(events.at(-1).payload.operation,"SET_PROCESSING_FORMAT"); + assert.equal(events.at(-1).payload.targetChannelId,source); + const after=clone(before); + after.graph.revision="6";after.graph.rosterRevision="8"; + after.graph.channels[0].processingFormat="STEREO"; + assert.equal(controller.onAck({requestId:change.requestId,status:"ACCEPTED", + deviceEpoch:before.device.epoch,graphRevision:"6",rosterRevision:"8", + errorCode:"NONE"}),true); + assert.equal(controller.state().lastError,"PENDING_ACCEPTED_SNAPSHOT"); + assert.equal(controller.onSnapshot(after),true); + assert.equal(controller.state().lastError,"ACCEPTED_READBACK"); + assert.equal(controller.state().current.graph.channels[0].source.portId,"in:0"); + const pending={operation:"SET_PROCESSING_FORMAT",targetChannelId:source, + baseGraphRevision:"5",baseRosterRevision:"7",payload:{format:"STEREO"}}; + const stale=clone(after); + stale.graph.channels[0].processingFormat="MONO"; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(stale),pending),false); + stale.graph.channels[0].processingFormat="STEREO"; + stale.graph.rosterRevision="7"; + assert.equal(protocol.readbackProvesIntent(protocol.normalizeSnapshot(stale),pending),false, + "no M/ST success from a stale native roster revision"); + const bridge=read("web/approved-native-bridge.js"); + const fn=bridge.slice(bridge.indexOf("function requestProcessingFormat(t)"), + bridge.indexOf("function previewNativePan(t,el,event)")); + assert.match(fn,/session\(\)\?\.authority|mixerSession\(\)\?\.authority/); + assert.match(fn,/controller.intent\("SET_PROCESSING_FORMAT",channelId,/); + assert.ok(fn.indexOf('authority==="CHANNEL_ID"')< + fn.indexOf('action:"routingChannelPatch"')); +}); test("P0 first Add FX discovers real local VST3 lazily without an audio-thread scan",()=>{ const bridge=read("web/approved-native-bridge.js"); const native=read("src/Main.cpp"); From 8f6b8c3a2cb295beb50376a8c358016ff7727517 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:38:47 +0700 Subject: [PATCH 104/219] test(p0): native M/ST translator exact identity, capability and stale revision regression --- tests/approved_native_v8_projection_test.cpp | 64 ++++++++++++++++++++ 1 file changed, 64 insertions(+) diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index dee37c83d..f6888cd8c 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -293,6 +293,69 @@ struct NativeWireProbe : NativeControlProbe { return {true,""}; } }; +// Processing-width intent is an admitted ChannelId operation, not the M4 +// channel ordinal. Probe tests exact 64-bit IDs without claiming hardware. +struct NativeFormatProbe : NativeControlProbe { + std::uint64_t epoch=0,revision=0,rosterRevision=0,id=0; + armix::mixer::ProcessingFormat width=armix::mixer::ProcessingFormat::mono; + struct Result {bool accepted=false;const char* error="REJECTED";}; + Result editNativeProcessingFormat(std::uint64_t ep,std::uint64_t rev, + std::uint64_t roster,armix::mixer::ChannelId target, + armix::mixer::ProcessingFormat next) { + epoch=ep;revision=rev;rosterRevision=roster; + id=target.value;width=next; + return {true,""}; + } +}; +static void approvedNativeMstTranslationRegression() { + auto installed=realBusReadbackFixture(); + juce::Array nativeOps; + nativeOps.add("NATIVE_SET_PROCESSING_FORMAT"); + installed.getDynamicObject()->setProperty("supportedOps",juce::var(nativeOps)); + auto accepted=canonicalSnapshot(); + assert(projectApprovedNativeV8(accepted,installed,true)); + juce::Array publicOps; + publicOps.add("SET_PROCESSING_FORMAT"); + accepted.getProperty("graph",{}).getProperty("capabilities",{}) + .getDynamicObject()->setProperty("supportedOps",juce::var(publicOps)); + auto payload=std::make_unique(); + payload->setProperty("format","STEREO"); + auto command=std::make_unique(); + command->setProperty("requestId","native-mst-test-1"); + command->setProperty("deviceEpoch","91"); + command->setProperty("baseGraphRevision","25"); + command->setProperty("baseRosterRevision","9"); + command->setProperty("targetChannelId","9007199254740993"); + command->setProperty("operation","SET_PROCESSING_FORMAT"); + command->setProperty("payload",juce::var(payload.release())); + auto intent=juce::var(command.release()); + const auto result=translateApprovedNativeControl(intent,accepted,installed); + assert(result.ok()); + assert(result.translated.getProperty("operation","").toString() + =="NATIVE_SET_PROCESSING_FORMAT"); + NativeFormatProbe probe; + assert(executeApprovedNativeControl(probe,result.translated)); + assert(probe.epoch==91 && probe.revision==25 && probe.rosterRevision==9); + assert(probe.id==9007199254740993ULL); + assert(probe.width==armix::mixer::ProcessingFormat::stereo); + + auto stale=juce::JSON::parse(juce::JSON::toString(intent,false)); + stale.getDynamicObject()->setProperty("baseRosterRevision","8"); + assert(!translateApprovedNativeControl(stale,accepted,installed).ok()); + auto wrong=juce::JSON::parse(juce::JSON::toString(intent,false)); + wrong.getProperty("payload",{}).getDynamicObject() + ->setProperty("format","MONO"); + assert(translateApprovedNativeControl(wrong,accepted,installed).error + =="INVALID_NATIVE_PROCESSING_FORMAT"); + auto main=juce::JSON::parse(juce::JSON::toString(intent,false)); + main.getDynamicObject()->setProperty("targetChannelId","18446744073709551615"); + assert(!translateApprovedNativeControl(main,accepted,installed).ok()); + auto noNative=juce::JSON::parse(juce::JSON::toString(installed,false)); + noNative.getDynamicObject()->setProperty( + "supportedOps",juce::var(juce::Array{})); + assert(!translateApprovedNativeControl(intent,accepted,noNative).ok()); +} + static void approvedNativeGroupMuteSoloRegression() { auto installed=realBusReadbackFixture(); auto group=std::make_unique(); @@ -917,6 +980,7 @@ int main() { controlIntentTranslationCases(snap,bus); nativeInsertCatalogInstanceProjectionRegression(); + approvedNativeMstTranslationRegression(); approvedNativeGroupMuteSoloRegression(); approvedNativeVst3LoadContractRegression(snap,bus); approvedWireTranslationRegression(snap,bus); From a3839c5349631ca8590b9783f280e3c83b513187 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:39:55 +0700 Subject: [PATCH 105/219] fix(p0): allow M/ST width changes on new FX-free ChannelIds with no legacy lease row --- engine/core/DynamicChannelFxLeaseBank.h | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index 42c7d272f..0489e508c 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -258,7 +258,14 @@ class DynamicChannelFxLeaseBank final { found|=row.id==target; retained.push_back(std::move(item)); } - if(!found)return Fault::emptyId; + // Newly created ChannelIds can be insert-free and absent from the + // original fixed M4 vendor lease inventory. Such a channel is still + // a valid PCM lane; create an EMPTY lease row for its new width. + if(!found) { + Assignment empty; + empty.id=target;empty.format=format; + retained.push_back(std::move(empty)); + } return prepare(epoch,revision,retained,destination,prior.external_); } From 7e7e0747205edbf816bedae088b2c1ca0b232419 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:46:04 +0700 Subject: [PATCH 106/219] fix(build): disambiguate native ChannelId edit from legacy M4 ChannelEdit in MSVC --- src/LiveDryRoutingLab.h | 8 +++++--- 1 file changed, 5 insertions(+), 3 deletions(-) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 2c5aeb9ed..c65db6fe8 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1494,11 +1494,13 @@ class LiveDryRoutingLab final { } try { auto roster=nativeAccepted_.graph.roster; - ChannelEdit edit; - edit.kind=ChannelEdit::Kind::setFormat; + // LiveDryRoutingLab has an unrelated legacy M4 ChannelEdit. + // Select the ChannelId roster's native edit ABI explicitly. + armix::mixer::ChannelEdit edit; + edit.kind=armix::mixer::ChannelEdit::Kind::setFormat; edit.id=channel; edit.format=format; - const std::array edits{edit}; + const std::array edits{edit}; if(!roster.edit(expectedRosterRevision,edits).ok()) { reply.error="NATIVE_PROCESSING_ROSTER_REJECTED";return reply; } From f904f2904cbdf43774b95a876b59371569bf167f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 13:50:59 +0700 Subject: [PATCH 107/219] ci(p0): replace multi-agent qualification gate with direct parallel Windows and Chromium Remove serial changed-files coordination and synthetic Product Qualification fan-in. Each workflow uses native GitHub changed-path PR triggers; retain MSVC/native PCM CTest, Chromium visual/interactions, exact-head FAT packaging, SHA verification, and independent failure status. Replace obsolete workflow-structure tests with direct-filter regressions. No audio DSP or GUI style changes. --- .github/workflows/p1-windows.yml | 43 ++++++++- .github/workflows/ui-smoke.yml | 91 ++++--------------- tests/ci_workflow_efficiency_test.mjs | 61 +++++-------- .../workstream_coordination_contract.test.mjs | 67 +++----------- 4 files changed, 97 insertions(+), 165 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 2eb9698c7..7a84b13df 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -40,10 +40,45 @@ on: - 'config/factoryfx-notices/**' - 'scripts/tests/test_factoryfx_release_bundle.py' - '.github/workflows/p1-windows.yml' - # PR native compile is called ONLY by UI smoke's Product Qualification fan-in. - # GUI/docs-only PRs skip Windows entirely; main and manual release stay here. - # Called by the all-PR quality workflow. No duplicate Windows PR run. - workflow_call: + # Direct native PR qualification; MSVC never waits on GUI or owner approval. + pull_request: + types: [opened, reopened, synchronize, ready_for_review] + paths: + - 'CMakeLists.txt' + - 'integration/console-v6/**' + - 'integration/*.h' + - 'integration/*.hpp' + - 'integration/*.cpp' + - 'integration/**/*.h' + - 'integration/**/*.hpp' + - 'integration/**/*.cpp' + - 'src/**' + - 'web/approved-native-bridge.js' + - 'web/approved-native-contract.js' + - 'tests/approved_native_m2_contract.test.cjs' + - 'scripts/build_approved_native_gui.py' + - 'tests/approved_native_gui_bundle_test.py' + - 'engine/**' + - 'web/bridge.js' + - 'web/monitor.js' + - 'tests/*.cpp' + - 'scripts/package_native_windows.ps1' + - 'scripts/verify_native_windows_artifact.ps1' + - 'scripts/collect_hardware_fat_windows.ps1' + - 'scripts/console_v6_fat_gate.mjs' + - 'scripts/verify_console_s0_native_fixture.mjs' + - 'scripts/run_console_native_s0.mjs' + - 'scripts/check_console_puzzle.mjs' + - 'scripts/check_approved_native_gui_release.mjs' + - 'scripts/check_pr278_console_authority.mjs' + - 'scripts/m3e_fat_evidence_gate.mjs' + - 'scripts/factoryfx_release_bundle.py' + - 'config/factoryfx-approved-releases.json' + - 'config/factoryfx-notices/**' + - 'scripts/tests/test_factoryfx_release_bundle.py' + - '.github/workflows/p1-windows.yml' + - 'tests/live_graph_contract_test.mjs' + - 'tests/*native*contract*.mjs' workflow_dispatch: concurrency: diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 115ef0e44..a3d0e8681 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -24,8 +24,26 @@ on: - '.github/workflows/ui-smoke.yml' - '.github/workflows/pages-publish.yml' # Every PR gets direct test selection; no ownership or PR collision audit. + # Direct changed-path admission; no serialized coordination/fan-in. pull_request: - types: [opened, reopened, synchronize, edited, ready_for_review] + types: [opened, reopened, synchronize, ready_for_review] + paths: + - 'web/**' + - 'integration/console-v6/**' + - 'site/**' + - 'AR-MIX-Live-FX-Host-Standalone-v0.3.html' + - 'scripts/build_pages.py' + - 'tests/*.py' + - 'tests/gui_workflow_contract_test.mjs' + - 'tests/*gui*contract*.mjs' + - 'tests/native_ui_contract_test.mjs' + - 'tests/wire_graph_canonical_model.test.cjs' + - 'tests/wire_main_native_handoff_contract.test.cjs' + - 'tests/ci_workflow_efficiency_test.mjs' + - 'tests/approved_native_m2_contract.test.cjs' + - 'scripts/build_ui_css.py' + - '.github/workflows/ui-smoke.yml' + - '.github/workflows/pages-publish.yml' # Manual full suite (including immutable CSS migration tests) or release-integration PR. workflow_dispatch: @@ -40,78 +58,7 @@ permissions: pull-requests: read jobs: - coordination: - name: Changed files only - runs-on: ubuntu-latest - timeout-minutes: 5 - outputs: - run_ui: ${{ steps.pr_scope.outputs.run_ui || steps.push_scope.outputs.run_ui }} - run_native: ${{ steps.pr_scope.outputs.run_native }} - steps: - - uses: actions/checkout@v4 - - name: Select UI and Windows tests from changed files, not owners - id: pr_scope - if: ${{ github.event_name == 'pull_request' }} - shell: bash - env: - BASE_SHA: ${{ github.event.pull_request.base.sha }} - run: | - set -euo pipefail - git fetch --no-tags --depth=1 origin "$BASE_SHA" - node scripts/ci_select_changed_paths.mjs "$BASE_SHA" - - name: Main push retains Chromium verification - id: push_scope - if: ${{ github.event_name != 'pull_request' }} - shell: bash - run: echo "run_ui=true" >> "$GITHUB_OUTPUT" - native: - needs: coordination - if: ${{ github.event_name == 'pull_request' && needs.coordination.outputs.run_native == 'true' }} - uses: ./.github/workflows/p1-windows.yml - permissions: - contents: read - pull-requests: read - - qualification: - name: Product Qualification - needs: [coordination, frontend, native] - if: ${{ always() && github.event_name == 'pull_request' }} - runs-on: ubuntu-latest - timeout-minutes: 3 - steps: - - name: Enforce actual outcomes for every selected test lane - shell: bash - env: - COORD_RESULT: ${{ needs.coordination.result }} - UI_RESULT: ${{ needs.frontend.result }} - NATIVE_RESULT: ${{ needs.native.result }} - RUN_UI: ${{ needs.coordination.outputs.run_ui }} - RUN_NATIVE: ${{ needs.coordination.outputs.run_native }} - run: | - set -euo pipefail - echo "Coordination: $COORD_RESULT, Chromium: $UI_RESULT ($RUN_UI), Windows: $NATIVE_RESULT ($RUN_NATIVE)" - if [[ "$COORD_RESULT" != "success" ]]; then - echo "::error::Coordination must PASS." - exit 1 - fi - if [[ "$RUN_UI" != "true" && "$RUN_UI" != "false" ]] || - [[ "$RUN_NATIVE" != "true" && "$RUN_NATIVE" != "false" ]]; then - echo "::error::Missing/malformed PR qualification scope." - exit 1 - fi - if [[ "$RUN_UI" == "true" && "$UI_RESULT" != "success" ]]; then - echo "::error::Required Chromium UI smoke did not PASS." - exit 1 - fi - if [[ "$RUN_NATIVE" == "true" && "$NATIVE_RESULT" != "success" ]]; then - echo "::error::Required Windows native CTest did not PASS." - exit 1 - fi - echo "Product Qualification PASS for selected lanes at this PR revision." - frontend: - needs: coordination - if: ${{ github.event_name != 'pull_request' || needs.coordination.outputs.run_ui == 'true' }} name: Standalone UI and geometry runs-on: ubuntu-latest timeout-minutes: 20 diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index 5d0b7d548..60a7532da 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -3,7 +3,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; -import {requiresUiSmoke, requiresNativeQualification} from '../scripts/check_workstream_coordination.mjs'; +// PR workflow paths, not deprecated multi-agent classifications, own CI routing. const read = path => readFileSync(path, 'utf8').replace(/\r\n/g, '\n'); const native = read('.github/workflows/p1-windows.yml'); @@ -36,13 +36,13 @@ function globMatches(pattern, filename) { return new RegExp(regex + '$').test(filename); } -const windowsPush = pathsFor(native, 'push', 'workflow_call'); -// Pull requests are always admitted; this exact classifier decides whether to call reusable MSVC. -const nativePrSelected = filename => requiresNativeQualification([filename]); +const windowsPush = pathsFor(native, 'push', 'pull_request'); +const windowsPR = pathsFor(native, 'pull_request', 'workflow_dispatch'); const uiPush = pathsFor(ui, 'push', 'pull_request'); -// Unfiltered PR entry runs cheap admission; only UI-relevant paths run browser. -const uiPRSelected = filename => requiresUiSmoke([filename]); +const uiPR = pathsFor(ui, 'pull_request', 'workflow_dispatch'); const selected = (paths, file) => paths.some(p => globMatches(p, file)); +const nativePrSelected = filename => selected(windowsPR,filename); +const uiPRSelected = filename => selected(uiPR,filename); test('visual GUI changes never consume Windows native runner on a PR or on main', () => { for (const filename of [ @@ -164,35 +164,22 @@ test('Pages is single guarded downstream publisher, never triggered by PR comple assert.doesNotMatch(factory, /^\s{2}push:/m); }); -test('M2.6 always-on coordination job has a stable name and skips unrelated Chromium', () => { - const prBlock=ui.split('\n pull_request:\n')[1]?.split('\n # Manual full suite')[0] || ''; - assert.match(prBlock,/types: \[opened, reopened, synchronize, edited, ready_for_review\]/); - assert.doesNotMatch(prBlock,/^\s+paths:/m); - assert.match(ui,/name: Changed files only/); - assert.match(ui,/needs: coordination/); - assert.match(ui,/needs\.coordination\.outputs\.run_ui == 'true'/); - assert.match(ui,/node scripts\/ci_select_changed_paths\.mjs/); - assert.doesNotMatch(ui,/scripts\/check_workstream_coordination\.mjs --pr/); - assert.doesNotMatch(native,/scripts\/check_workstream_coordination\.mjs --pr/); -}); - -test('P0 single product qualification fans in exact scoped native and UI jobs',()=>{ - assert.match(native,/^ workflow_call:/m); - assert.doesNotMatch(native,/^ pull_request:/m); - assert.match(ui,/uses: \.\/\.github\/workflows\/p1-windows\.yml/); - assert.match(ui,/name: Product Qualification/); - assert.match(ui,/needs: \[coordination, frontend, native\]/); - assert.match(ui,/NATIVE_RESULT.*needs\.native\.result/); - assert.match(ui,/UI_RESULT.*needs\.frontend\.result/); - assert.match(ui,/if: \$\{\{ always\(\) && github\.event_name == 'pull_request' \}\}/); - for(const path of [ - 'integration/ApprovedNativeRuntimeSnapshot.h', - 'integration/ApprovedNativeV8Projection.h', - 'integration/ApprovedNativeControlIntent.h', - 'scripts/check_console_puzzle.mjs', - 'scripts/check_approved_native_gui_release.mjs' - ]) assert.ok(nativePrSelected(path),path+' bypassed native build'); - for(const path of ['docs/workstreams/MULTI_AGENT_COORDINATION.md', - 'site/preview/assets/mixer-fader-assembly.css']) - assert.equal(nativePrSelected(path),false,path+' wrongly launches Windows'); +test('P0 standalone changed-path PR runners have no coordination or synthetic fan-in',()=>{ + assert.match(ui,/^ pull_request:$/m); + assert.match(native,/^ pull_request:$/m); + assert.doesNotMatch(ui,/^ coordination:$/m); + assert.doesNotMatch(ui,/^ qualification:$/m); + assert.doesNotMatch(ui,/needs: coordination|Product Qualification/); + assert.doesNotMatch(ui,/uses: \.\/\.github\/workflows\/p1-windows\.yml/); + assert.doesNotMatch(native,/^ workflow_call:$/m); + assert.ok(uiPRSelected('web/approved-native-bridge.js')); + assert.ok(nativePrSelected('web/approved-native-bridge.js')); + assert.ok(nativePrSelected('integration/ApprovedNativeV8Projection.h')); + assert.ok(nativePrSelected('tests/dynamic_accepted_session_test.cpp')); + assert.ok(uiPRSelected('site/preview-v2/assets/wire-graph-model.js')); + assert.equal(nativePrSelected('site/preview-v2/assets/mixer-fader-assembly.css'),false); + assert.equal(uiPRSelected('src/LiveDryRoutingLab.h'),false); + assert.equal(nativePrSelected('docs/workstreams/MULTI_AGENT_COORDINATION.md'),false); + assert.match(native,/FAT_EXACT_PR_HEAD_CHECKOUT/); + assert.match(native,/ctest --test-dir build -C Release --output-on-failure/); }); diff --git a/tests/workstream_coordination_contract.test.mjs b/tests/workstream_coordination_contract.test.mjs index 0801731d2..25480b35d 100644 --- a/tests/workstream_coordination_contract.test.mjs +++ b/tests/workstream_coordination_contract.test.mjs @@ -212,46 +212,17 @@ test('existing #396/#398 remain advisory, first strict PR is #400',()=>{ ['src/LiveAudioEngine.h']).ok,false); }); -test('coordinator uses existing native + Chromium CI, not a fifth workflow',()=>{ - const native=readFileSync('.github/workflows/p1-windows.yml','utf8').replace(/\r\n/g,'\n'); +test('P0 PR workflows run independently with direct path filters',()=>{ const ui=readFileSync('.github/workflows/ui-smoke.yml','utf8').replace(/\r\n/g,'\n'); - for(const workflow of [native,ui]) { - assert.match(workflow,/scripts\/check_workstream_coordination\.mjs --pr/); - assert.match(workflow,/pull-requests: read/); - assert.match(workflow,/GH_TOKEN: \$\{\{ github\.token \}\}/); - } - assert.match(native,/workflow_call:/); - assert.doesNotMatch(native,/^ pull_request:/m); - assert.match(ui,/ready_for_review/); - assert.match(ui,/uses: \.\/\.github\/workflows\/p1-windows\.yml/); - const guide=readFileSync('AGENTS.md','utf8'); - assert.match(guide,/One integration owner/); - assert.match(guide,/arsonmix-integration: single-owner/); - assert.match(guide,/Branch protection, review, exact-SHA tests/); - assert.match(readFileSync('docs/workstreams/MULTI_AGENT_COORDINATION.md','utf8'), - /SUPERSEDED — 2026-11-05/); -}); - -test('M2.6 always-on PR admission scopes Chromium to UI changes',()=>{ - for(const path of [ - 'docs/RELEASE_NOTES.md','README.md','src/LiveAudioEngine.h', - 'engine/core/PreparedMixerBlock.h', - 'scripts/check_workstream_coordination.mjs', - 'tests/workstream_coordination_contract.test.mjs' - ]) assert.equal(requiresUiSmoke([path]),false,path); - for(const path of [ - 'site/preview/index.html','web/approved-native-bridge.js', - 'integration/console-v6/contract.json','tests/pages_wire_first_canonical_main_smoke.py', - '.github/workflows/ui-smoke.yml' - ]) assert.equal(requiresUiSmoke([path]),true,path); - assert.equal(requiresUiSmoke(['README.md','src/Main.cpp','site/preview/index.html']),true); - const workflow=readFileSync('.github/workflows/ui-smoke.yml','utf8').replace(/\r\n/g,'\n'); - const prBlock=workflow.split('\n pull_request:\n')[1]?.split('\n # Manual full suite')[0] || ''; - assert.ok(prBlock,'missing PR event'); - assert.doesNotMatch(prBlock,/^\s+paths:/m,'PR entrypoint must not filter docs or PCM PRs'); - assert.match(workflow,/name: PR coordination admission/); - assert.match(workflow,/needs: coordination/); - assert.match(workflow,/needs\.coordination\.outputs\.run_ui/); + const native=readFileSync('.github/workflows/p1-windows.yml','utf8').replace(/\r\n/g,'\n'); + assert.match(ui,/^ pull_request:$/m); + assert.match(native,/^ pull_request:$/m); + assert.match(ui,/^ paths:$/m); + assert.match(native,/^ paths:$/m); + assert.doesNotMatch(ui,/^ coordination:$/m); + assert.doesNotMatch(ui,/needs: coordination|name: Product Qualification/); + assert.doesNotMatch(native,/^ workflow_call:$/m); + assert.match(readFileSync('AGENTS.md','utf8'),/One integration owner/); }); test('P0 native qualification is precise: native ABI/release scripts yes, docs/GUI no',()=>{ @@ -277,21 +248,13 @@ test('P0 native qualification is precise: native ABI/release scripts yes, docs/G assert.equal(requiresNativeQualification(['README.md','integration/ApprovedNativeV8Projection.h']),true); }); -test('P0 product verdict is a fail-closed fan-in with no duplicate PR Windows build',()=>{ - const ui=readFileSync('.github/workflows/ui-smoke.yml','utf8').replace(/\r\n/g,'\n'); +test('P0 exact-SHA Windows release still requires native CTest and ZIP verification',()=>{ const windows=readFileSync('.github/workflows/p1-windows.yml','utf8').replace(/\r\n/g,'\n'); - assert.match(ui,/name: Product Qualification/); - assert.match(ui,/needs: \[coordination, frontend, native\]/); - assert.match(ui,/always\(\) && github\.event_name == 'pull_request'/); - assert.match(ui,/uses: \.\/\.github\/workflows\/p1-windows\.yml/); - assert.match(ui,/needs\.coordination\.outputs\.run_native == 'true'/); - assert.match(ui,/NATIVE_RESULT.*needs\.native\.result/); - assert.match(ui,/UI_RESULT.*needs\.frontend\.result/); - assert.match(ui,/RUN_NATIVE.*needs\.coordination\.outputs\.run_native/); - assert.match(ui,/\$RUN_NATIVE.*true.*\$NATIVE_RESULT.*success/); - assert.match(windows,/^ workflow_call:/m); - assert.doesNotMatch(windows,/^ pull_request:/m); + const ui=readFileSync('.github/workflows/ui-smoke.yml','utf8').replace(/\r\n/g,'\n'); + assert.doesNotMatch(ui,/name: Product Qualification/); assert.match(windows,/ctest --test-dir build -C Release --output-on-failure/); + assert.match(windows,/verify_native_windows_artifact\.ps1/); + assert.match(windows,/EXPECTED_SOURCE_SHA/); }); test('P0 Windows checkout CRLF cannot suppress the PR event in coordination test',()=>{ From 3936baa3e60ad47190354de31cde6504e10a1675 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 14:16:09 +0700 Subject: [PATCH 108/219] feat(p0): keep ChannelId hardware IN available and FX power DOM-stable across native readback --- tests/approved_native_m2_contract.test.cjs | 164 +++++++++++++++++++++ web/approved-native-bridge.js | 86 ++++++++++- 2 files changed, 246 insertions(+), 4 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 24e69b530..0d67a8f6f 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -963,6 +963,170 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a assert.equal(scope.edges.length,0,"accepted snapshot replaces reference wire"); }); +test("P0 native FX rack and per-slot readback update mounted strip without replacing fader DOM",()=>{ + const vm=require("node:vm"),listeners=new Map(),sent=[]; + let paints=0,serial=100,wire=300,strip=null; + const scope={ + tracks:[],master:{id:1,name:"Master"},colors:["#456789"], + wireGraph:{validateCandidateGraph:()=>({ok:true})}, + make:(name,kind,color)=>({id:serial++,name,kind,color,selected:false}), + render(){paints++;}, + installGraph(tracks,master,edges){ + this.tracks=tracks;this.master=master;this.edges=edges;this.render(); + }, + allocateWireId:()=>wire++,displayMeterDbfs(){},stopDemo(){} + }; + const native={emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn)}; + const info={textContent:""},preview={disabled:false},toast={hidden:true}; + const doc={ + readyState:"complete",documentElement:{dataset:{}}, + getElementById:id=>id==="info"?info:id==="preview"?preview: + id==="armixNativeToast"?toast:null, + querySelector:selector=>selector.startsWith('.strip[data-id=')?strip:null, + addEventListener(){} + }; + const win={__JUCE__:{backend:native},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(){return 0},clearTimeout(){},queueMicrotask(fn){fn();}}; + vm.runInNewContext(read("web/approved-native-bridge.js"), + {window:win,document:doc,performance:{now:()=>0},console},{timeout:1500}); + const base=acceptedFixture(); + base.graph.channels[0].fxRackBypassed=false; + base.graph.channels[0].inserts=[ + {id:"vst-live-1",catalogId:"eq-a",name:"EQ",bypassed:false}, + {id:"vst-live-2",catalogId:"comp-b",name:"Compressor",bypassed:true} + ]; + base.mixerSession={authority:"CHANNEL_ID",deviceEpoch:base.device.epoch, + routeRevision:base.graph.revision,rosterRevision:base.graph.rosterRevision, + channels:base.graph.channels,main:{db:0,mute:false}}; + listeners.get("arMixConsoleSnapshot")(base); + assert.equal(win.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); + assert.equal(paints,1); + const track=scope.tracks[0]; + const button=()=>({ + attributes:new Map(), + setAttribute(key,val){this.attributes.set(key,String(val));}, + getAttribute(key){return this.attributes.get(key)||null;} + }); + const style=()=>({values:new Set(),toggle(name,enabled){ + if(enabled)this.values.add(name);else this.values.delete(name); + },contains(name){return this.values.has(name);}}); + const header=button(),rows=base.graph.channels[0].inserts.map((entry,i)=>{ + const power=button(); + return {dataset:{slot:String(i),insertId:entry.id},classList:style(), + querySelector:selector=>selector==='[data-action="slotPower"]'?power:null, + power}; + }); + const rack={dataset:{},classList:style(),querySelector(selector){ + return selector==='[data-action="fxOn"]'?header:null; + },querySelectorAll:selector=>selector==='.fxslot-row:not(.is-empty)'?rows:[]}; + const stableStrip={querySelector:selector=> + selector===".fx-section"?rack:null}; + strip=stableStrip; + const snapshot=clone(base); + snapshot.graph.channels[0].fxRackBypassed=true; + listeners.get("arMixConsoleSnapshot")(snapshot); + assert.equal(paints,1,"rack bypass must NOT replace the entire GUI channel DOM"); + assert.equal(strip,stableStrip); + assert.equal(track.fxOn,false); + assert.deepEqual(Array.from(track.slotBypass.slice(0,2)),[false,true], + "header bypass must never overwrite independent insert bypass preferences"); + assert.equal(rack.dataset.fxChainEnabled,"false"); + assert.equal(header.getAttribute("aria-pressed"),"false"); + assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["false","false"]); + assert.deepEqual(rows.map(r=>r.dataset.fxSlotEnabled),["true","false"]); + assert.deepEqual(rows.map(r=>r.dataset.fxEffective),["false","false"]); + assert.ok(rows.every(r=>r.classList.contains("is-bypassed"))); + const restored=clone(snapshot); + restored.graph.channels[0].fxRackBypassed=false; + listeners.get("arMixConsoleSnapshot")(restored); + assert.equal(paints,1,"re-enabling the FX rack preserves mounted controls"); + assert.equal(track.fxOn,true); + assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["true","false"]); + assert.deepEqual(rows.map(r=>r.dataset.fxEffective),["true","false"]); + const individual=clone(restored); + individual.graph.channels[0].inserts[0].bypassed=true; + listeners.get("arMixConsoleSnapshot")(individual); + assert.equal(paints,1,"slot power is a realtime scalar, not a topology edit"); + assert.deepEqual(Array.from(track.slotBypass.slice(0,2)),[true,true]); + assert.deepEqual(rows.map(r=>r.power.getAttribute("aria-pressed")),["false","false"]); + const replaced=clone(individual); + replaced.graph.channels[0].inserts[0].id="new-vst-instance"; + listeners.get("arMixConsoleSnapshot")(replaced); + assert.equal(paints,2,"an actual VST instance identity change MUST re-project"); +}); + +test("P0 native hardware IN remains selectable after ChannelId ownership, failed ACK drains the other channel",()=>{ + const vm=require("node:vm"),listeners=new Map(),sent=[],microtasks=[]; + let ordinal=100,wireId=400; + const scope={ + tracks:[],master:{id:1,name:"Master"},colors:["#456789"], + wireGraph:{validateCandidateGraph:()=>({ok:true})}, + make:(name,kind,color)=>({id:ordinal++,name,kind,color,selected:false}), + render(){}, + installGraph(tracks,main,edges){this.tracks=tracks;this.master=main;this.edges=edges;}, + allocateWireId:()=>wireId++,displayMeterDbfs(){},stopDemo(){}, + findTrack(el){return el.track;} + }; + const backend={emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn)}; + const toast={textContent:"",hidden:true},info={textContent:""}; + const doc={ + readyState:"complete",documentElement:{dataset:{}}, + getElementById:id=>id==="info"?info:id==="armixNativeToast"?toast: + id==="preview"?{disabled:true}:null, + querySelector:()=>null,addEventListener(){} + }; + const win={__JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(){return 0},clearTimeout(){}, + queueMicrotask(fn){microtasks.push(fn);}}; + vm.runInNewContext(read("web/approved-native-bridge.js"), + {window:win,document:doc,performance:{now:()=>0},console},{timeout:1500}); + const base=acceptedFixture(); + const first=base.graph.channels[0],main=base.graph.mainChannelId; + const second=clone(first);second.id="9007199254740994"; + second.name="Harmony";second.primaryOutId=main; + base.graph.channels.splice(1,0,second); + base.graph.edges.push({...base.graph.edges[0], + edgeId:"9223372036854775809",from:second.id}); + base.device.enabledInputs=[0,1]; + base.device.inputEndpoints=[ + {id:"in:0",port:0,callback:0,label:"Mic A",active:true}, + {id:"in:1",port:1,callback:1,label:"Mic B",active:true} + ]; + // Deliberately stale M4 renderer bit. The accepted ChannelId callback is + // the authority for new physical source changes after BUS/WIRE cutover. + base.legacyM4={active:false,routeAccepted:false,routingRevision:"9"}; + base.mixerSession={authority:"CHANNEL_ID",deviceEpoch:base.device.epoch, + routeRevision:base.graph.revision,rosterRevision:base.graph.rosterRevision, + channels:base.graph.channels,main:{db:0,mute:false}}; + listeners.get("arMixConsoleSnapshot")(base); + assert.equal(win.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,true); + assert.equal(scope.tracks.length,2); + const choose=(track,label)=>win.__ARMIX_NATIVE_M2__.consumeField({ + target:{track,dataset:{field:"input"},value:label},type:"change"}); + assert.equal(choose(scope.tracks[0],"Mono · Mic A [IN 1]"),true); + assert.equal(choose(scope.tracks[1],"Mono · Mic B [IN 2]"),true); + const sourceCommands=()=>sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingNativeSourcePatch"); + assert.equal(sourceCommands().length,1,"first source command sent to real JUCE gateway"); + assert.equal(sourceCommands()[0].payload.channelId,first.id); + assert.equal(sourceCommands()[0].payload.left,0); + const id=sourceCommands()[0].payload.requestId; + listeners.get("arMixNativeSourceAck")({requestId:id,ok:false,error:"STALE_NATIVE_SOURCE"}); + // Rejected source did not mutate graph; later authoritative readback is + // byte-identical. The queued SECOND channel must not be stranded. + listeners.get("arMixConsoleSnapshot")(base); + assert.ok(microtasks.length>0,"unchanged native graph must still drain queued source"); + while(microtasks.length)microtasks.shift()(); + assert.equal(sourceCommands().length,2); + assert.equal(sourceCommands()[1].payload.channelId,second.id); + assert.equal(sourceCommands()[1].payload.left,1); + assert.equal(sourceCommands()[1].payload.graphRevision,base.graph.revision); + assert.notEqual(sourceCommands()[1].payload.requestId,id); +}); test("M3 Windows bundle owns pointerup fader gesture and fences native FX keyboard reorder",()=>{ const builder=read("scripts/build_approved_native_gui.py"); const bridge=read("web/approved-native-bridge.js"); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index b79aa97b1..a083c40b8 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -145,10 +145,69 @@ scope.installGraph(nextTracks,nextMaster,edges); return true; } + // Rack and individual FX power are scalar native DSP controls, NOT a + // structural graph change. Updating them must not replace DOM strips, + // steal focus, interrupt a fader drag or reallocate WIRE render objects. + // The verified individual bypass flag stays distinct from rack bypass. + function paintNativeFxPowerReadback(ch,t){ + if(typeof ch.fxRackBypassed!=="boolean"||!Array.isArray(ch.inserts)) + return true; // never synthesize missing DSP readback + const enabled=!ch.fxRackBypassed; + const strip=document.querySelector('.strip[data-id="'+t.id+'"]'); + const rack=strip?.querySelector(".fx-section"); + // Virtualized mobile banks may have no mounted strip. The model still + // receives verified state; normal bank render creates the right buttons. + if(rack){ + const header=rack.querySelector('[data-action="fxOn"]'); + const rows=[...rack.querySelectorAll('.fxslot-row:not(.is-empty)')]; + if(!header||rows.length!==ch.inserts.length)return false; + for(let slot=0;slot + r.dataset.slot===String(slot)); + if(!insert||typeof insert.bypassed!=="boolean"|| + !row||row.dataset.insertId!==insert.id|| + !row.querySelector('[data-action="slotPower"]')) + return false; // structural re-render, never modify wrong FX owner + } + } + t.fxOn=enabled; + if(!Array.isArray(t.slotBypass))t.slotBypass=Array(8).fill(false); + for(let slot=0;slotr.dataset.slot===String(slot)); + const effective=enabled&&!insert.bypassed; + row.dataset.fxSlotEnabled=String(!insert.bypassed); + row.dataset.fxEffective=String(effective); + row.classList.toggle("is-active",effective); + row.classList.toggle("is-bypassed",!effective); + const button=row.querySelector('[data-action="slotPower"]'); + button.setAttribute("aria-pressed",String(effective)); + button.title=(insert.bypassed?"Enable":"Bypass")+ + " only insert "+(slot+1); + button.setAttribute("aria-label", + (insert.bypassed?"Enable":"Bypass")+" only FX insert "+ + (slot+1)+" in "+t.name); + } + return true; + } function projectNativeGraphWithoutFocusLoss(next) { + // Only identity, order, processing width, source and edges are structural. + // Rack/slot bypass is applied in-place from independent readback below. const structure=JSON.stringify([ next.graph.channels.map(ch=>[ch.id,ch.role,ch.name, - ch.processingFormat,ch.source,ch.primaryOutId,ch.inserts,ch.fxRackBypassed]), + ch.processingFormat,ch.source,ch.primaryOutId, + ch.inserts?.map(fx=>[fx.id,fx.catalogId,fx.name])]), next.graph.edges]); if(structure!==lastNativeTopologySignature){ if(!projection(next))return false; @@ -162,6 +221,13 @@ const t=id===scope?.master?.id?scope.master: scope?.tracks?.find(x=>x.id===id); if(!t||!ch.controls)continue; + if(!paintNativeFxPowerReadback(ch,t)){ + // A plugin owner or strip DOM changed under us: do not paint an + // unrelated instance. Rebuild from the accepted native graph. + if(!projection(next))return false; + lastNativeTopologySignature=structure; + return true; + } const c=ch.controls; const db=c.faderDb,pan=c.pan*100; const faderChanged=Number.isFinite(db)&&Math.abs(t.level-db)>.015; @@ -913,10 +979,18 @@ return (capture.includes("vb-audio")||playback.includes("vb-audio")) && capture.includes("cable output") && playback.includes("cable input"); }; + // A migrated ChannelId graph is the sole PCM authority. Its physical + // input chooser must NOT depend on the legacy M4.active bit after BUS/WIRE + // has made M4 structurally obsolete. First-sound M4 still requires its + // own verified active renderer; never manufacture hardware readiness. const deviceReady=()=>!!(hardware?.device?.backend && hardware.device.sampleRate>0 && hardware.device.enabledInputs.length>0 && - hardware.device.enabledOutputs.length>=2 && legacy()?.active===true); + hardware.device.enabledOutputs.length>=2 && + (mixerSession()?.authority==="CHANNEL_ID" + ? controller?.state()?.current?.admitted===true && + flags.acceptedGraphConnected + : mixerSession()?.authority==="M4" && legacy()?.active===true)); function updateHardwarePanel(next) { hardware=next || null; refreshRealM4Inputs(next); @@ -1430,6 +1504,12 @@ !caps?.supportedOps?.includes("CREATE_GROUP"); addBus.disabled=!!pendingBusCreate; } + if (nativeAdmitted && !activeNativeSource && pendingNativeSources.size) { + // A rejected/timeout source command may leave the graph revision + // unchanged. Drain the next distinct channel after this authoritative + // snapshot even if the GUI signature is otherwise identical. + window.queueMicrotask(dispatchNativeSource); + } if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; lastPaintedSignature="";lastNativeTopologySignature=""; @@ -1455,8 +1535,6 @@ } flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); - if(!activeNativeSource&&pendingNativeSources.size) - window.queueMicrotask(dispatchNativeSource); if(pendingFxInsert?.authority==="CHANNEL_ID"){ const p=pendingFxInsert; const inserted=next.graph.channels.find(ch=>ch.id===p.channelId) From 1d36427affc4ee97ce58557b167bdb815fc945e2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 14:21:24 +0700 Subject: [PATCH 109/219] fix(p0): prevent pending M4 fader ACK from freezing meters and FX rack Remove global snapshot gate while preserving accepted-only scalar readback and held-fader cap. Add VM regression for 20 live meter taps, independently verified CH1 rack, CH4 mute and subsequent CH5 ACK. No PCM/ASIO DSP modifications. --- tests/live_fader_held_drag.test.cjs | 83 ++++++++++++++++++++++++++--- web/approved-native-bridge.js | 7 ++- 2 files changed, 82 insertions(+), 8 deletions(-) diff --git a/tests/live_fader_held_drag.test.cjs b/tests/live_fader_held_drag.test.cjs index bb12707d0..d6edfd800 100644 --- a/tests/live_fader_held_drag.test.cjs +++ b/tests/live_fader_held_drag.test.cjs @@ -36,15 +36,27 @@ function nativeChannelIdFixture(){ }; return s; } -function harness(){ - const sent=[],listeners=new Map(),timers=[],visual=[]; +function harness({m4=false}={}){ + const sent=[],listeners=new Map(),timers=[],visual=[],meters=[]; + const m4Tracks=m4?Array.from({length:10},(_,i)=>({ + id:1000+i,name:"CH"+(i+1),kind:"audio",format:"mono",level:-6, + pan:0,mute:false,solo:false,input:"None",output:"Master",fxOn:true, + fx:Array(8).fill("None"),slotBypass:Array(8).fill(false) + })):[]; + const roots=new Map(m4Tracks.map(t=>[t.id,{ + isConnected:true, + querySelector:q=>q===".meter-fill.left"?{lane:t.id,side:"L"}: + q===".meter-fill.right"?{lane:t.id,side:"R"}:null + }])); let now=1000,nextId=100; const scope={ - tracks:[],master:{id:1,name:"MAIN"},colors:["#568ead"], + tracks:m4Tracks,master:{id:1,name:"MAIN",kind:"master",level:0, + pan:0,mute:false,output:"Realtek"},colors:["#568ead"], wireGraph:{validateCandidateGraph:()=>({ok:true})}, make:(name,kind,color)=>({id:nextId++,name,kind,color,selected:false}), render(){},findTrack(el){return this.tracks[el.lane||0];}, - displayMeterDbfs(){},allocateWireId(){return nextId++;}, + displayMeterDbfs(fill,db){meters.push({fill,db});}, + refreshStrip(){},allocateWireId(){return nextId++;}, installGraph(channels,master,edges){this.tracks=channels;this.master=master;this.edges=edges;}, syncFaderVisual(t){visual.push({id:t.id,db:t.level});}, stopDemo(){} @@ -57,7 +69,10 @@ function harness(){ readyState:"complete",documentElement:{dataset:{}}, getElementById:id=>id==="info"?{textContent:""}: id==="preview"?{disabled:false,setAttribute(){}}:null, - querySelector:()=>null,addEventListener(){} + querySelector:q=>{ + const match=/\.strip\[data-id="(\d+)"\]/.exec(q); + return match?roots.get(Number(match[1]))||null:null; + },addEventListener(){} }; const window={ __JUCE__:{backend},ArSonApprovedNativeContract:protocol, @@ -67,7 +82,7 @@ function harness(){ vm.runInNewContext(read("web/approved-native-bridge.js"),{ window,document,performance:{now:()=>now},console },{timeout:2500}); - return {scope,window,backend,sent,listeners,timers,visual, + return {scope,window,backend,sent,listeners,timers,visual,meters, tick(ms=40){ now+=ms; for(let i=0;i{ assert.match(bridge,/edit\.t\?\.kind==="master"\s*\|\|\s*m4ControlIsOwner\(\)/, "MAIN scalar uses guarded native host gain"); }); + +test("pending M4 fader ACK never stalls independently accepted meters, FX rack or mute",()=>{ + const h=harness({m4:true}),s=clone(fixture),rev="3"; + const controls=()=>({faderDb:-6,pan:0,mute:false,solo:false}); + const source=()=>({mode:"MONO",left:0,right:-1,main:true,channelFormat:"MONO"}); + s.legacyM4={ + active:true,routeAccepted:true,routingRevision:rev, + channelControls:Array.from({length:10},controls), + channels:Array.from({length:10},source), + fxInstances:Array.from({length:10},()=>Array(8).fill(null)) + }; + s.mixerSession={ + authority:"M4",deviceEpoch:s.device.epoch,routeRevision:rev, + channels:Array.from({length:10},()=>({ + source:source(),main:true,channelFormat:"MONO",controls:controls(), + fxRackBypassed:false,peakL:0.1,peakR:0.1 + })),main:{db:0,mute:false} + }; + const snapshot=h.listeners.get("arMixConsoleSnapshot"); + snapshot(s); + assert.equal(h.meters.length,20,"ten-channel hardware meters are live"); + const ch5={dataset:{field:"level"},lane:4,value:"-12",min:"-60",max:"10"}; + assert.equal(h.window.__ARMIX_NATIVE_M2__.consumeField({ + target:ch5,type:"input" + }),true); + const command=h.sent.findLast(e=> + e.name==="arMixAction"&&e.payload.action==="routingM4Control")?.payload; + assert.equal(command?.channel,4); + assert.equal(command.parameter,"faderDb"); + assert.equal(command.controlValue,-12); + const next=clone(s); + next.mixerSession.channels[0].fxRackBypassed=true; + next.mixerSession.channels[3].controls.mute=true; + next.mixerSession.channels[4].peakL=0.45; + snapshot(next); + assert.equal(h.meters.length,40, + "pending CH5 gain must not freeze all 20 physical meter taps"); + assert.equal(h.scope.tracks[0].fxOn,false, + "CH1 real rack state stays independent of CH5 pending gain"); + assert.equal(h.scope.tracks[3].mute,true, + "CH4 accepted mute stays independent of CH5 pending gain"); + assert.equal(h.scope.tracks[4].level,-6, + "unacknowledged CH5 gain must not appear as accepted PCM"); + assert.equal(h.visual.at(-1)?.db,-12, + "the CH5 held fader cap keeps the latest unacknowledged target"); + h.listeners.get("arMixM4ControlAck")({ + requestId:command.requestId,ok:true,deviceEpoch:s.device.epoch, + routingRevision:rev,channel:4,parameter:"faderDb" + }); + const accepted=clone(next); + accepted.mixerSession.channels[4].controls.faderDb=-12; + accepted.legacyM4.channelControls[4].faderDb=-12; + snapshot(accepted); + assert.equal(h.scope.tracks[4].level,-12); + assert.equal(h.meters.length,60); +}); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index a083c40b8..caafb8b77 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1483,8 +1483,11 @@ status("NATIVE SESSION UNAVAILABLE · controls unchanged"); return; } - // Never paint unacknowledged or still-unproven M4 scalar edits. - if(reconcileM4ControlReadback(next))return; + // Never paint unacknowledged controls; pending slider caps are kept + // separately by pendingFaderVisualDb while accepted telemetry continues. + // A pending scalar ACK is not a global snapshot gate. Only accepted producer + // data can update controls; independent meters and FX racks keep moving. + reconcileM4ControlReadback(next); reconcileM4RackReadback(next); if(session.authority==="M4" && m4Verified()) { paintM4Fallback(next); From cd4c20e20c7d178576af8c604e1644ebd46b92ba Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 14:45:39 +0700 Subject: [PATCH 110/219] fix(p0): break G0 first-sound bootstrap deadlock and expose verified IN pins before first PCM route --- tests/approved_native_m2_contract.test.cjs | 94 ++++++++++++++++++++++ web/approved-native-bridge.js | 49 ++++++++--- 2 files changed, 132 insertions(+), 11 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 0d67a8f6f..f54ef1793 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1057,6 +1057,100 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla assert.equal(paints,2,"an actual VST instance identity change MUST re-project"); }); +test("P0 FIRST SOUND G0 NONE authority exposes verified physical IN before any route and arms only after native ACK",()=>{ + const vm=require("node:vm"),sent=[],listeners=new Map(),renderedChoices=[]; + let win; + const tracks=Array.from({length:10},(_,i)=>({ + id:i+1,kind:"audio",name:"CH "+(i+1),input:"None", + output:"Master",format:"mono",fx:[],slotBypass:[],fxInsertIds:[] + })); + const scope={ + tracks,master:{id:50,kind:"master",output:"Master"}, + findTrack:el=>el?.track||null, + render(){renderedChoices.push([...win.__ARMIX_NATIVE_M2__.inputChoices(tracks[0])]);}, + stopDemo(){} + }; + const backend={ + emitEvent:(name,payload)=>sent.push({name,payload}), + addEventListener:(name,fn)=>listeners.set(name,fn) + }; + const info={textContent:""},preview={disabled:false}; + const document={ + readyState:"complete",documentElement:{dataset:{}},activeElement:null, + querySelector:()=>null, + getElementById:id=>id==="info"?info:id==="preview"?preview:null, + addEventListener(){} + }; + win={ + __JUCE__:{backend},ArSonApprovedNativeContract:protocol, + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){}, + setTimeout(){return 0},clearTimeout(){},queueMicrotask(fn){fn();} + }; + vm.runInNewContext(read("web/approved-native-bridge.js"),{ + window:win,document,performance:{now:()=>0},console + },{timeout:1500}); + const boot=clone(fixtures.g0); + boot.device.backend="Windows Audio"; + boot.device.captureDevice="Real hardware microphone"; + boot.device.playbackDevice="Speakers"; + boot.legacyM4={active:true,routeAccepted:false,routingRevision:"12"}; + boot.mixerSession={authority:"NONE",deviceEpoch:boot.device.epoch, + routeRevision:"0",rosterRevision:"0",channels:[],main:{outputArmed:false}}; + listeners.get("arMixConsoleSnapshot")(boot); + assert.equal(win.__ARMIX_APPROVED_NATIVE_GUI__.acceptedGraphConnected,false, + "unpatched G0 must not masquerade as ChannelId PCM"); + assert.ok(renderedChoices.length>0, + "first real JUCE pin readback must refresh the previously empty selector"); + assert.deepEqual(renderedChoices.at(-1),["None","Mono · IN 1 [IN 1]"], + "the only offered input is the native enabled physical pin"); + const choose=(label)=>win.__ARMIX_NATIVE_M2__.consumeField({ + type:"change",target:{dataset:{field:"input"},value:label,track:tracks[4]} + }); + assert.equal(choose("Mono · IN 1 [IN 1]"),true); + const source=sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingSourceSwitch"); + assert.equal(source.length,1, + "G0 needs exactly one direct JUCE source command, no Start/Patch/Arm wizard"); + assert.deepEqual([ + source[0].payload.channel,source[0].payload.mode, + source[0].payload.left,source[0].payload.right, + source[0].payload.deviceEpoch,source[0].payload.revision + ],[4,"MONO",0,-1,69,12]); + assert.equal(sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="monitor").length,0, + "MAIN cannot auto-arm before accepted native source topology"); + // Native control-thread producer ACK, not a fake browser state. + const acceptedRows=Array.from({length:10},(_,i)=>({ + mode:i===4?"MONO":"NONE",left:i===4?0:-1, + right:-1,main:true + })); + listeners.get("arMixSourceSwitchAck")({ + requestId:source[0].payload.requestId,ok:true, + state:{ready:true,epoch:69,revision:13,hasAcceptedRoute:true, + nativeChannelIdPcmActive:false, + channelControls:Array.from({length:10},()=>({db:0,pan:0,mute:false,solo:false})), + acceptedRoute:{channels:acceptedRows}} + }); + const monitors=sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="monitor"); + assert.equal(monitors.length,1, + "first accepted input routed to MAIN authorizes one automatic safe listen"); + assert.equal(monitors[0].payload.value,true); + assert.equal(monitors[0].payload.expectedEpoch,69); + assert.equal(monitors[0].payload.expectedRevision,13); + assert.equal(tracks[4].input,"None", + "GUI must wait for a subsequent independent native readback"); + const none=clone(boot); + none.device.enabledInputs=[];none.device.inputEndpoints=[]; + listeners.get("arMixConsoleSnapshot")(none); + assert.deepEqual([...win.__ARMIX_NATIVE_M2__.inputChoices(tracks[0])],["None"]); + const commandsBefore=sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingSourceSwitch").length; + assert.equal(choose("Mono · IN 1 [IN 1]"),true); + assert.equal(sent.filter(x=>x.name==="arMixAction"&& + x.payload.action==="routingSourceSwitch").length,commandsBefore, + "never invent physical capture when the driver has no enabled input pins"); +}); test("P0 native hardware IN remains selectable after ChannelId ownership, failed ACK drains the other channel",()=>{ const vm=require("node:vm"),listeners=new Map(),sent=[],microtasks=[]; let ordinal=100,wireId=400; diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index caafb8b77..d8cb5b63a 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -923,10 +923,20 @@ if(!scope?.tracks || next?.admitted || !Array.isArray(scope.tracks) || scope.tracks.length<10) return; const session=next?.raw?.mixerSession; - if(session?.authority!=="M4"||!Array.isArray(session.channels)||session.channels.length!==10)return; const m4=next?.raw?.legacyM4; - const rows=session.channels.map(ch=>ch.source); - const signature=JSON.stringify([next?.device?.epoch, + const acceptedM4=session?.authority==="M4" && + Array.isArray(session.channels)&&session.channels.length===10; + // An UNPATCHED prepared native M4 renderer has no accepted route yet, + // so the SessionSnapshot deliberately reports authority NONE. The + // operator must still SEE its verified physical IN choices to create + // the first route. Previously an early return left every dropdown at + // "None" forever; requiring a patched route to display the first pin + // created a circular bootstrap dependency. + const preparedFirstSound=session?.authority==="NONE" && + m4?.active===true && m4?.routeAccepted===false; + if(!acceptedM4&&!preparedFirstSound)return; + const rows=acceptedM4?session.channels.map(ch=>ch.source):null; + const signature=JSON.stringify([session.authority,next?.device?.epoch, next?.device?.enabledInputs,next?.device?.inputEndpoints, m4?.active,m4?.routingRevision,rows]); if(signature===lastM4UiSignature)return; @@ -934,7 +944,11 @@ for(let i=0;i<10;++i){ const t=scope.tracks.find(x=>x.id===m4TrackIds[i]); if(t?.kind!=="audio")continue; - const row=Array.isArray(rows)&&rows.length===10?rows[i]:null; + // An unpatched session has NO physical row. Keep the model at None, + // while rendering the native pin choices for the initial operator + // selection. Do not borrow source/OUT data from the demo or a prior + // device session. + const row=acceptedM4?rows[i]:null; t.input=inputLabelFor(row); if(row && typeof row.main==="boolean") t.output=row.main?"Master":"SOURCE ONLY (No Main)"; @@ -979,18 +993,27 @@ return (capture.includes("vb-audio")||playback.includes("vb-audio")) && capture.includes("cable output") && playback.includes("cable input"); }; - // A migrated ChannelId graph is the sole PCM authority. Its physical - // input chooser must NOT depend on the legacy M4.active bit after BUS/WIRE - // has made M4 structurally obsolete. First-sound M4 still requires its - // own verified active renderer; never manufacture hardware readiness. + // ChannelId requires its installed accepted callback. Before the FIRST + // source selection there is intentionally no ChannelId or M4 route yet: + // authoritative SessionSnapshot is NONE, but legacyM4.active means the + // JUCE callback has independently prepared a real SILENT M4 graph and + // verified sparse physical pins. Let THAT state accept the first IN patch. + // Never infer readiness from the Pages/demo tracks or the presence of a + // Windows playback device alone. const deviceReady=()=>!!(hardware?.device?.backend && - hardware.device.sampleRate>0 && + safeNativeCounter(hardware.device.epoch)!==null && + hardware.device.sampleRate>0 && hardware.device.bufferFrames>0 && + Array.isArray(hardware.device.enabledInputs) && hardware.device.enabledInputs.length>0 && + Array.isArray(hardware.device.enabledOutputs) && hardware.device.enabledOutputs.length>=2 && (mixerSession()?.authority==="CHANNEL_ID" ? controller?.state()?.current?.admitted===true && flags.acceptedGraphConnected - : mixerSession()?.authority==="M4" && legacy()?.active===true)); + : (mixerSession()?.authority==="M4" || + mixerSession()?.authority==="NONE") && + legacy()?.active===true && + safeNativeCounter(legacy()?.routingRevision)!==null)); function updateHardwarePanel(next) { hardware=next || null; refreshRealM4Inputs(next); @@ -1519,7 +1542,11 @@ stopDemo(); status(m4Verified()? "NATIVE M4 · real PCM faders and meters · ChannelId buses not yet admitted": - "NATIVE G0 · choose real hardware IN on any channel"); + deviceReady()? + "NATIVE G0 · verified physical IN ready · select a channel input": + hardware?.device?.enabledInputs?.length===0? + "NO CAPTURE PINS · Audio I/O: enable an actual hardware input": + "NATIVE G0 NOT READY · open Audio I/O and verify device / native route"); return; } // Control readback may change at the SAME structural graph revision. From 090cb5219141c1ac204659f9a54a4f026b60fe57 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 14:46:45 +0700 Subject: [PATCH 111/219] ci(p0): adopt repo-wide smart draft CI without losing P0 GUI/PCM tests Run cheap native and UI Linux checks on iterative draft PR #418 edits. Reserve Chromium/MSVC for reviewed milestone, main or manual Actions dispatch; upload hardware FAT ZIP only on explicit manual checkbox with exact source SHA. Remove automatic Windows build churn and protect manual runs from PR cancellation. Preserve the approved FX rack browser test, P0 engine and all CTest targets. --- .github/workflows/p1-windows.yml | 54 +++++++++++----- .github/workflows/ui-smoke.yml | 43 +++++++++++-- tests/ci_workflow_efficiency_test.mjs | 64 +++++++++++-------- .../workstream_coordination_contract.test.mjs | 47 ++++++++------ 4 files changed, 141 insertions(+), 67 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 7a84b13df..bbd2fc889 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -42,7 +42,7 @@ on: - '.github/workflows/p1-windows.yml' # Direct native PR qualification; MSVC never waits on GUI or owner approval. pull_request: - types: [opened, reopened, synchronize, ready_for_review] + types: [opened, reopened, synchronize, ready_for_review, converted_to_draft] paths: - 'CMakeLists.txt' - 'integration/console-v6/**' @@ -80,17 +80,43 @@ on: - 'tests/live_graph_contract_test.mjs' - 'tests/*native*contract*.mjs' workflow_dispatch: + inputs: + package_fat: + description: "Package, verify and upload experimental Windows FAT ZIP" + type: boolean + required: false + default: false concurrency: - group: windows-vst3-${{ github.head_ref || github.ref_name }} - cancel-in-progress: true + group: windows-vst3-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} permissions: contents: read pull-requests: read jobs: + quick: + name: Fast native contracts (no Windows / JUCE checkout) + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Catch broken native UI / CI contracts before a paid Windows runner + run: | + node scripts/check_console_puzzle.mjs + node --check web/approved-native-bridge.js + node --check web/approved-native-contract.js + node --test tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract_test.mjs tests/live_graph_contract_test.mjs + python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v + python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v windows-build: + name: Windows MSVC / realtime CTest + needs: quick + if: ${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }} runs-on: windows-2022 timeout-minutes: 50 steps: @@ -100,11 +126,10 @@ jobs: - uses: actions/checkout@v4 with: ref: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} - - name: Verify FAT checkout matches exact PR source HEAD - if: ${{ github.event_name == 'pull_request' && github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} + - name: Verify exact source SHA before native CTest / optional FAT ZIP shell: pwsh env: - EXPECTED_SOURCE_SHA: ${{ github.event.pull_request.head.sha }} + EXPECTED_SOURCE_SHA: ${{ github.event_name == 'pull_request' && github.event.pull_request.head.sha || github.sha }} run: | $actual = (& git rev-parse HEAD).Trim() if ($LASTEXITCODE -ne 0 -or $actual -ne $env:EXPECTED_SOURCE_SHA) { @@ -184,33 +209,28 @@ jobs: - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT - if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} shell: pwsh run: | & ./scripts/package_native_windows.ps1 -BuildDir build -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Stage ONLY legally approved and host-qualified Factory VST3 bundles - if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} shell: pwsh run: | python scripts/factoryfx_release_bundle.py stage --lock config/factoryfx-approved-releases.json --output dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Independently verify release ZIP and embedded GUI/engine before upload - if: ${{ github.event_name != 'pull_request' || startsWith(github.head_ref, 'integration/product-') || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} shell: pwsh run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - # P0 PR #414 is the ONLY additional FAT candidate: physical mouse/GPU - # proof requires its exact Windows EXE, never a stable release. - # Permit the one #418 First Sound candidate only for exact-SHA hardware FAT.\n # Ordinary engine PRs compile/CTest without wasting package/ZIP work. - # Release-integration PRs and main/manual runs package and verify, but never silently publish a stable release. - # This single M4 FAT branch is explicitly allowed to upload an - # UNQUALIFIED experimental ZIP for real physical hardware testing. + # Explicit FAT milestone only. Manual ZIP is not stable or field-qualified. - uses: actions/upload-artifact@v4 - if: ${{ github.event_name != 'pull_request' || github.head_ref == 'milestone/m4-unified-native-multichannel-fx-20261101' || github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' || github.head_ref == 'integration/daw-direct-hardware-input-20261105' }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} with: - name: ${{ github.event_name == 'pull_request' && github.head_ref == 'integration/daw-direct-hardware-input-20261105' && 'ArSonMix-P0-DAW-First-Sound-UNQUALIFIED-Windows-x64' || github.event_name == 'pull_request' && github.head_ref == 'perf/p0-stage-a-approved-gui-profiling-20261105' && 'ArSonMix-P0-EXPERIMENTAL-Pointer-Latency-FAT-Windows-x64' || github.event_name == 'pull_request' && 'ArSonMix-M4-EXPERIMENTAL-Hardware-FAT-Windows-x64' || 'ArSonMix-GUI10CH-P012-Verified-Hardware-FAT-Windows-x64' }} + name: ArSonMix-Windows-FAT-UNQUALIFIED-${{ github.run_id }} path: dist/ if-no-files-found: error retention-days: 14 diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index a3d0e8681..32009b49b 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -26,7 +26,7 @@ on: # Every PR gets direct test selection; no ownership or PR collision audit. # Direct changed-path admission; no serialized coordination/fan-in. pull_request: - types: [opened, reopened, synchronize, ready_for_review] + types: [opened, reopened, synchronize, ready_for_review, converted_to_draft] paths: - 'web/**' - 'integration/console-v6/**' @@ -50,16 +50,51 @@ on: # New PR commits supersede old UI checks. The production Pages dispatcher # only reacts to a completed successful main push, never cancelled checks. concurrency: - group: ui-smoke-${{ github.event.pull_request.number || github.ref }} - cancel-in-progress: true + # Manual full qualification runs do not share a cancellable PR group. + group: ui-smoke-${{ github.event_name == 'workflow_dispatch' && github.run_id || github.event.pull_request.number || github.ref }} + cancel-in-progress: ${{ github.event_name != 'workflow_dispatch' }} permissions: contents: read pull-requests: read jobs: + quick: + name: Fast UI contracts (every relevant PR commit) + runs-on: ubuntu-latest + timeout-minutes: 8 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Verify approved /preview/ and native bridge syntax without browser + run: | + node scripts/check_console_puzzle.mjs + node --check web/app.js + node --check web/approved-native-bridge.js + node --check web/approved-native-contract.js + node --check site/preview-v2/assets/gui-perf-probe.js + python scripts/build_ui_css.py --check + python tests/gui_baseline_lock_test.py + - name: Check native UI contracts, workflow policy, and WIRE without Chromium + run: | + node --test tests/workstream_coordination_contract.test.mjs tests/gui_workflow_contract_test.mjs tests/plugin_ui_contract_test.mjs tests/ci_workflow_efficiency_test.mjs tests/fx_drag_reorder_contract_test.mjs tests/mixer_io_operator_contract_test.mjs tests/mixer_shell_contract_test.mjs tests/approved_native_m2_contract.test.cjs + node tests/wire_graph_canonical_model.test.cjs + node tests/wire_main_native_handoff_contract.test.cjs + - name: Verify single published /preview/ source offline + run: | + python scripts/build_pages.py --out dist-pages --sha "${{ github.sha }}" --branch main + python tests/single_preview_publication_contract_test.py dist-pages + - name: Block incomplete product release only when preparing product review + if: ${{ github.event_name == 'pull_request' && !github.event.pull_request.draft && startsWith(github.head_ref, 'integration/product-') }} + run: node scripts/check_console_puzzle.mjs --release frontend: - name: Standalone UI and geometry + name: Full Chromium /preview/ visual and interaction qualification + needs: quick + # Keep draft iterative: full browser runs only at review milestone, + # on main or when explicitly dispatched for the selected branch. + if: ${{ github.event_name != 'pull_request' || github.event.pull_request.draft == false }} runs-on: ubuntu-latest timeout-minutes: 20 steps: diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index 60a7532da..4aa347fc8 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -3,7 +3,7 @@ import test from 'node:test'; import assert from 'node:assert/strict'; import {readFileSync} from 'node:fs'; -// PR workflow paths, not deprecated multi-agent classifications, own CI routing. +// Native Actions path filters (not a legacy PR owner classifier) select lanes. const read = path => readFileSync(path, 'utf8').replace(/\r\n/g, '\n'); const native = read('.github/workflows/p1-windows.yml'); @@ -41,8 +41,8 @@ const windowsPR = pathsFor(native, 'pull_request', 'workflow_dispatch'); const uiPush = pathsFor(ui, 'push', 'pull_request'); const uiPR = pathsFor(ui, 'pull_request', 'workflow_dispatch'); const selected = (paths, file) => paths.some(p => globMatches(p, file)); -const nativePrSelected = filename => selected(windowsPR,filename); -const uiPRSelected = filename => selected(uiPR,filename); +const nativePrSelected = filename => selected(windowsPR, filename); +const uiPRSelected = filename => selected(uiPR, filename); test('visual GUI changes never consume Windows native runner on a PR or on main', () => { for (const filename of [ @@ -123,8 +123,8 @@ test('docs and isolated CI tests do not fan out into unrelated builds', () => { }); test('ordinary GUI PR and main use current targeted checks; full history is explicit', () => { - assert.match(ui, /concurrency:\s+group: ui-smoke-/); - assert.match(ui, /cancel-in-progress: true/); + assert.match(ui, /group: ui-smoke-/); + assert.match(ui, /cancel-in-progress: \$\{\{ github\.event_name != 'workflow_dispatch' \}\}/); assert.match(ui, /python tests\/pages_wire_first_canonical_main_smoke.py/); assert.match(ui, /python tests\/pages_v55_context_wire_fader_smoke.py/); assert.match(ui, /node tests\/wire_main_native_handoff_contract.test.cjs/); @@ -135,13 +135,17 @@ test('ordinary GUI PR and main use current targeted checks; full history is expl assert.match(ui, /retention-days: 3/); }); -test('Windows runs native realtime CTest; packaging is for main, manual and release branches only', () => { - assert.match(native, /branches: \[main\]/); - assert.match(native, /workflow_dispatch:/); - assert.match(native, /cancel-in-progress: true/); - const packageGates = [...native.matchAll(/^\s{8}if: .*integration\/product-.*milestone\/m4-/gm)].length; - assert.equal(packageGates, 3, 'All 3 packaging/staging/ZIP steps must be gated'); - assert.match(native, /scripts\/verify_native_windows_artifact.ps1/); +test('Windows realtime CTest is automatic only for reviewed PRs; packaging requires explicit manual opt-in',()=>{ + assert.match(native,/branches: \[main\]/); + assert.match(native,/^ workflow_dispatch:\n inputs:\n package_fat:/m); + assert.match(native,/default: false/); + assert.match(native,/^ quick:\n name: Fast native contracts/m); + assert.match(native,/^ windows-build:[\s\S]*?needs: quick\n/m); + assert.match(native,/github\.event\.pull_request\.draft == false/); + const fatOnly = [...native.matchAll(/^ if: .*inputs\.package_fat == true.*$/gm)].length; + assert.equal(fatOnly,4,'Packaging, FactoryFX stage, ZIP verify and upload require manual FAT'); + assert.match(native,/FAT_EXACT_PR_HEAD_CHECKOUT/); + assert.match(native,/ctest --test-dir build -C Release --output-on-failure/); assert.ok(native.indexOf('scripts/verify_native_windows_artifact.ps1 -OutputDir dist') < native.indexOf('uses: actions/upload-artifact@v4')); }); @@ -164,22 +168,30 @@ test('Pages is single guarded downstream publisher, never triggered by PR comple assert.doesNotMatch(factory, /^\s{2}push:/m); }); -test('P0 standalone changed-path PR runners have no coordination or synthetic fan-in',()=>{ - assert.match(ui,/^ pull_request:$/m); - assert.match(native,/^ pull_request:$/m); - assert.doesNotMatch(ui,/^ coordination:$/m); - assert.doesNotMatch(ui,/^ qualification:$/m); - assert.doesNotMatch(ui,/needs: coordination|Product Qualification/); +test('Draft PR commits run inexpensive filtered contract checks without queued MSVC/Chromium',()=>{ + assert.match(ui,/^ pull_request:\n types: \[opened, reopened, synchronize, ready_for_review, converted_to_draft\]\n paths:/m); + assert.match(native,/^ pull_request:\n types: \[opened, reopened, synchronize, ready_for_review, converted_to_draft\]\n paths:/m); + assert.match(ui,/^ quick:\n name: Fast UI contracts/m); + assert.match(native,/^ quick:\n name: Fast native contracts/m); + assert.match(ui,/^ frontend:[\s\S]*?needs: quick[\s\S]*?github\.event\.pull_request\.draft == false/m); + assert.match(native,/^ windows-build:[\s\S]*?needs: quick[\s\S]*?github\.event\.pull_request\.draft == false/m); + assert.doesNotMatch(ui,/^ coordination:|^ qualification:|name: PR coordination admission|name: Product Qualification/m); + assert.doesNotMatch(native,/^ workflow_call:|check_workstream_coordination\.mjs --pr/m); assert.doesNotMatch(ui,/uses: \.\/\.github\/workflows\/p1-windows\.yml/); - assert.doesNotMatch(native,/^ workflow_call:$/m); + assert.equal(uiPRSelected('src/LiveAudioEngine.h'),false); + assert.equal(nativePrSelected('site/preview-v2/index.html'),false); assert.ok(uiPRSelected('web/approved-native-bridge.js')); assert.ok(nativePrSelected('web/approved-native-bridge.js')); assert.ok(nativePrSelected('integration/ApprovedNativeV8Projection.h')); - assert.ok(nativePrSelected('tests/dynamic_accepted_session_test.cpp')); - assert.ok(uiPRSelected('site/preview-v2/assets/wire-graph-model.js')); - assert.equal(nativePrSelected('site/preview-v2/assets/mixer-fader-assembly.css'),false); - assert.equal(uiPRSelected('src/LiveDryRoutingLab.h'),false); - assert.equal(nativePrSelected('docs/workstreams/MULTI_AGENT_COORDINATION.md'),false); - assert.match(native,/FAT_EXACT_PR_HEAD_CHECKOUT/); - assert.match(native,/ctest --test-dir build -C Release --output-on-failure/); + assert.ok(nativePrSelected('tests/channel_routing_contract_test.cpp')); + assert.equal(nativePrSelected('README.md'),false); + assert.equal(uiPRSelected('README.md'),false); +}); + +test('Manual FAT and visual qualification survive simultaneous commit pushes without cancellation',()=>{ + for(const workflow of [native,ui]) { + assert.match(workflow,/github\.event_name == 'workflow_dispatch' && github\.run_id/); + assert.match(workflow,/cancel-in-progress: \$\{\{ github\.event_name != 'workflow_dispatch' \}\}/); + } + assert.match(native,/github\.event_name == 'workflow_dispatch' && inputs\.package_fat == true/); }); diff --git a/tests/workstream_coordination_contract.test.mjs b/tests/workstream_coordination_contract.test.mjs index 25480b35d..4cda7cbbe 100644 --- a/tests/workstream_coordination_contract.test.mjs +++ b/tests/workstream_coordination_contract.test.mjs @@ -212,19 +212,26 @@ test('existing #396/#398 remain advisory, first strict PR is #400',()=>{ ['src/LiveAudioEngine.h']).ok,false); }); -test('P0 PR workflows run independently with direct path filters',()=>{ - const ui=readFileSync('.github/workflows/ui-smoke.yml','utf8').replace(/\r\n/g,'\n'); - const native=readFileSync('.github/workflows/p1-windows.yml','utf8').replace(/\r\n/g,'\n'); - assert.match(ui,/^ pull_request:$/m); - assert.match(native,/^ pull_request:$/m); - assert.match(ui,/^ paths:$/m); - assert.match(native,/^ paths:$/m); - assert.doesNotMatch(ui,/^ coordination:$/m); - assert.doesNotMatch(ui,/needs: coordination|name: Product Qualification/); - assert.doesNotMatch(native,/^ workflow_call:$/m); - assert.match(readFileSync('AGENTS.md','utf8'),/One integration owner/); +test('Coordination admission is historical only; native and UI runners have independent path scopes',()=>{ + const native=readFileSync('.github/workflows/p1-windows.yml','utf8'); + const ui=readFileSync('.github/workflows/ui-smoke.yml','utf8'); + for(const workflow of [native,ui]) { + assert.match(workflow,/^ pull_request:/m); + assert.match(workflow,/^ paths:/m); + assert.doesNotMatch(workflow,/check_workstream_coordination\.mjs --pr/); + } + assert.doesNotMatch(native,/workflow_call:/); + assert.doesNotMatch(ui,/name: PR coordination admission|name: Product Qualification/); +}); +test('Draft commits cannot start full Chromium, but matching changes still run quick checks',()=>{ + const workflow=readFileSync('.github/workflows/ui-smoke.yml','utf8'); + assert.match(workflow,/^ quick:/m); + assert.match(workflow,/^ frontend:/m); + assert.match(workflow,/github\.event\.pull_request\.draft == false/); + assert.match(workflow,/ready_for_review, converted_to_draft/); + assert.match(workflow,/^ paths:/m); + assert.doesNotMatch(workflow,/needs: coordination/); }); - test('P0 native qualification is precise: native ABI/release scripts yes, docs/GUI no',()=>{ for(const path of [ 'src/LiveAudioEngine.h','engine/core/PreparedMixerBlock.h', @@ -248,15 +255,15 @@ test('P0 native qualification is precise: native ABI/release scripts yes, docs/G assert.equal(requiresNativeQualification(['README.md','integration/ApprovedNativeV8Projection.h']),true); }); -test('P0 exact-SHA Windows release still requires native CTest and ZIP verification',()=>{ - const windows=readFileSync('.github/workflows/p1-windows.yml','utf8').replace(/\r\n/g,'\n'); - const ui=readFileSync('.github/workflows/ui-smoke.yml','utf8').replace(/\r\n/g,'\n'); - assert.doesNotMatch(ui,/name: Product Qualification/); - assert.match(windows,/ctest --test-dir build -C Release --output-on-failure/); - assert.match(windows,/verify_native_windows_artifact\.ps1/); - assert.match(windows,/EXPECTED_SOURCE_SHA/); +test('Production native CTest remains independent and after lightweight acceptance',()=>{ + const ui=readFileSync('.github/workflows/ui-smoke.yml','utf8'); + const windows=readFileSync('.github/workflows/p1-windows.yml','utf8'); + assert.doesNotMatch(ui,/Product Qualification|uses: \.\/\.github\/workflows\/p1-windows\.yml/); + assert.match(windows,/needs: quick/); + assert.match(windows,/^ pull_request:/m); + assert.match(windows,/ctest --test-dir build -C Release --output-on-failure/); + assert.match(windows,/package_fat/); }); - test('P0 Windows checkout CRLF cannot suppress the PR event in coordination test',()=>{ const workflow=readFileSync('.github/workflows/ui-smoke.yml','utf8').replace(/\r\n/g,'\n'); const windowsCheckout=workflow.replace(/\n/g,'\r\n'); From 45f2d2d195914e73c59abe059093818fdd0e94bf Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 14:47:14 +0700 Subject: [PATCH 112/219] fix(p0): preserve exact uint64 ChannelId epoch for physical input readiness --- web/approved-native-bridge.js | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index d8cb5b63a..b449c289b 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1001,7 +1001,11 @@ // Never infer readiness from the Pages/demo tracks or the presence of a // Windows playback device alone. const deviceReady=()=>!!(hardware?.device?.backend && - safeNativeCounter(hardware.device.epoch)!==null && + // ChannelId generation is a full uint64 decimal string and MUST NOT + // round through JS Number.MAX_SAFE_INTEGER. M4 numeric event tokens + // remain separately range-checked before their actual dispatch. + protocol.decimal(hardware.device.epoch)!==null && + hardware.device.epoch!=="0" && hardware.device.sampleRate>0 && hardware.device.bufferFrames>0 && Array.isArray(hardware.device.enabledInputs) && hardware.device.enabledInputs.length>0 && From d917110775ba025b4db2ad8845e6387d9e45f062 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 14:52:36 +0700 Subject: [PATCH 113/219] fix(p0): replace misleading silent boot Patch/Arm prompt with real IN readiness and device diagnosis --- tests/approved_native_m2_contract.test.cjs | 9 +++++++++ web/approved-native-bridge.js | 13 ++++++++++--- 2 files changed, 19 insertions(+), 3 deletions(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index f54ef1793..0bec0efe9 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1057,6 +1057,15 @@ test("P0 native FX rack and per-slot readback update mounted strip without repla assert.equal(paints,2,"an actual VST instance identity change MUST re-project"); }); +test("P0 startup banner never demands legacy Patch CH1 / Arm wizard",()=>{ + const bridge=read("web/approved-native-bridge.js"); + assert.match(bridge,/SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK/); + assert.match(bridge,/NO CAPTURE INPUT · OPEN AUDIO I\/O/); + assert.match(bridge,/NO VERIFIED INPUT ROUTE · OPEN AUDIO I\/O/); + assert.doesNotMatch(bridge,/NO AUDIBLE OUTPUT · PATCH INPUT \+ ARM/); + assert.match(bridge,/const preparedFirstSound=session\?\.authority==="NONE"/); + assert.match(bridge,/const deviceReady=\(\)=>/); +}); test("P0 FIRST SOUND G0 NONE authority exposes verified physical IN before any route and arms only after native ACK",()=>{ const vm=require("node:vm"),sent=[],listeners=new Map(),renderedChoices=[]; let win; diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index b449c289b..6bf820088 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1045,11 +1045,18 @@ (virtualOut?" · VIRTUAL / NO SPEAKERS":""); if(label && label.textContent!==transport)label.textContent=transport; const warning=document.querySelector?.(".status-bar .warning"); + // A silent first-sound session is not an operator failure and does + // not require Patch CH1 / Arm / Start controls. The real IN dropdown + // initiates native source publication; only its correlated ACK may + // request a safe first MONITOR. If the driver exposes no physical IN, + // guide the operator to the existing Audio I/O panel instead. const warningText=!deviceOpen?"NO VERIFIED AUDIO DEVICE": d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING": - "MAIN ARMED · PCM NOT YET ADMITTED"): - legacy()?.routeAccepted?"INPUT PATCHED · OUTPUT MUTED": - "NO AUDIBLE OUTPUT · PATCH INPUT + ARM"; + "MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED"): + !d.enabledInputs?.length?"NO CAPTURE INPUT · OPEN AUDIO I/O": + legacy()?.routeAccepted?"NATIVE INPUT ROUTED · MONITOR OFF": + deviceReady()?"SELECT CHANNEL IN · NATIVE MONITOR AFTER ACK": + "NO VERIFIED INPUT ROUTE · OPEN AUDIO I/O"; if(warning && warning.textContent!==warningText)warning.textContent=warningText; if(!inputSelect)return; const pins=deviceOpen?d.inputEndpoints.filter(p=> From 26dca0459f97e922a47c6e3a56d5fcc5dd0389e9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 14:53:39 +0700 Subject: [PATCH 114/219] test(p0): align first-sound monitor diagnostic with accurate native readiness label --- tests/approved_native_m2_contract.test.cjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 0bec0efe9..0d75b22fa 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -1263,7 +1263,7 @@ test("native Windows operator can explicitly patch first physical input, arm and assert.match(js,/NATIVE PATCH REJECTED:/); assert.match(js,/NO VERIFIED AUDIO DEVICE/); assert.match(js,/NATIVE PCM · HARDWARE FAT PENDING/); - assert.match(js,/MAIN ARMED · PCM NOT YET ADMITTED/); + assert.match(js,/MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED/); assert.match(main,/action=="routingSourceSwitch"/); assert.match(main,/engine_\.liveOutputArmFault\(\)/); assert.match(main,/safe->emitApprovedNativeSnapshot\(\)/); From a4618c026d90a99c7ab8243ebae127a52ba38353 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 15:33:32 +0700 Subject: [PATCH 115/219] ci(fat): issue exact-head unqualified Windows ZIP on explicit PR418 review promotion --- .github/workflows/p1-windows.yml | 11 ++++++----- tests/ci_workflow_efficiency_test.mjs | 10 ++++++++++ 2 files changed, 16 insertions(+), 5 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index bbd2fc889..a7adee7ad 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -209,26 +209,27 @@ jobs: - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.event.action == 'ready_for_review' && github.event.pull_request.number == 418 && github.head_ref == 'integration/daw-direct-hardware-input-20261105' && github.event.pull_request.draft == false) }} shell: pwsh run: | & ./scripts/package_native_windows.ps1 -BuildDir build -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Stage ONLY legally approved and host-qualified Factory VST3 bundles - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.event.action == 'ready_for_review' && github.event.pull_request.number == 418 && github.head_ref == 'integration/daw-direct-hardware-input-20261105' && github.event.pull_request.draft == false) }} shell: pwsh run: | python scripts/factoryfx_release_bundle.py stage --lock config/factoryfx-approved-releases.json --output dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Independently verify release ZIP and embedded GUI/engine before upload - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.event.action == 'ready_for_review' && github.event.pull_request.number == 418 && github.head_ref == 'integration/daw-direct-hardware-input-20261105' && github.event.pull_request.draft == false) }} shell: pwsh run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - # Explicit FAT milestone only. Manual ZIP is not stable or field-qualified. + # Explicit one-time PR #418 review promotion is a user-authorized FAT ZIP opt-in. + # No release publication; no package on ordinary PR synchronize or main push. - uses: actions/upload-artifact@v4 - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.event.action == 'ready_for_review' && github.event.pull_request.number == 418 && github.head_ref == 'integration/daw-direct-hardware-input-20261105' && github.event.pull_request.draft == false) }} with: name: ArSonMix-Windows-FAT-UNQUALIFIED-${{ github.run_id }} path: dist/ diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index 4aa347fc8..890266c01 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -150,6 +150,16 @@ test('Windows realtime CTest is automatic only for reviewed PRs; packaging requi native.indexOf('uses: actions/upload-artifact@v4')); }); +test('One-shot experimental FAT package on PR #418 review promotion remains SHA-pinned and non-release',()=>{ + const gate=/github\.event\.action == 'ready_for_review' && github\.event\.pull_request\.number == 418 && github\.head_ref == 'integration\/daw-direct-hardware-input-20261105'/g; + assert.equal([...native.matchAll(gate)].length,4); + assert.match(native,/github\.event\.pull_request\.draft == false/); + assert.match(native,/github\.event_name == 'workflow_dispatch' && inputs\.package_fat == true/); + assert.match(native,/FAT_EXACT_PR_HEAD_CHECKOUT/); + assert.match(native,/ArSonMix-Windows-FAT-UNQUALIFIED-/); + assert.match(native,/retention-days: 14/); +}); + test('Pages is single guarded downstream publisher, never triggered by PR completion', () => { assert.match(pages, /workflows: \["UI smoke \(Chromium\)"\]/); assert.match(pages, /github\.event\.workflow_run\.event == 'push'/); From 5ed7fe95f55027be5c1ac4ad5d66dfd21da242f9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 16:18:03 +0700 Subject: [PATCH 116/219] fix(audio): admit real channel WIRE PCM and keep source-only DSP/meters alive Repair the Windows approved decoder's INPUT destination rejection and decouple native render scheduling from output reachability. Preserve matching native roles, source/device/revision fences, exact edge identity and feedback rejection. Propagate native WIRE diagnostics through ACK. Add decoder-to-publisher deterministic sample, meter, FX-seam, routing lifecycle and zero-render-allocation regression; retain approved GUI and sole realtime callback. Physical hardware FAT remains pending. --- CMakeLists.txt | 6 + docs/P0_LIVE_ROUTING_RECOVERY_20261106.md | 76 ++++++ engine/core/DynamicAcceptedSession.h | 7 +- engine/core/DynamicNativeSessionPublisher.h | 2 +- engine/core/DynamicPreparedMixerBlock.h | 25 +- integration/ApprovedNativeControlIntent.h | 17 +- integration/ApprovedNativeV8Projection.h | 2 +- src/ApprovedNativeV8Projection.h | 2 +- src/LiveDryRoutingLab.h | 10 +- src/Main.cpp | 2 +- tests/approved_native_m2_contract.test.cjs | 30 +++ tests/approved_native_routing_pcm_test.cpp | 275 ++++++++++++++++++++ 12 files changed, 423 insertions(+), 31 deletions(-) create mode 100644 docs/P0_LIVE_ROUTING_RECOVERY_20261106.md create mode 100644 tests/approved_native_routing_pcm_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index e9ce7939d..27deec283 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -112,6 +112,12 @@ if(BUILD_TESTING) target_compile_features(ARMixNativeV8ProjectionTests PRIVATE cxx_std_20) add_test(NAME M3BNativeV8StableIdReadbackAndFailClosedProjection COMMAND ARMixNativeV8ProjectionTests) add_dependencies(ARMixMixerRoutingTests ARMixNativeV8ProjectionTests) + juce_add_console_app(ARMixApprovedRoutingPcmTests PRODUCT_NAME "ArSonMix Approved WIRE PCM Tests") + target_sources(ARMixApprovedRoutingPcmTests PRIVATE tests/approved_native_routing_pcm_test.cpp) + target_link_libraries(ARMixApprovedRoutingPcmTests PRIVATE juce::juce_core juce::juce_recommended_config_flags) + target_compile_features(ARMixApprovedRoutingPcmTests PRIVATE cxx_std_20) + add_test(NAME P0ApprovedDecoderChannelToChannelAndSourceOnlyPCM COMMAND ARMixApprovedRoutingPcmTests) + add_dependencies(ARMixMixerRoutingTests ARMixApprovedRoutingPcmTests) add_executable(ARMixChannelRoutingContractTests tests/channel_routing_contract_test.cpp) target_compile_features(ARMixChannelRoutingContractTests PRIVATE cxx_std_20) add_test(NAME MonoStereoSparsePhysicalPortRouting COMMAND ARMixChannelRoutingContractTests) diff --git a/docs/P0_LIVE_ROUTING_RECOVERY_20261106.md b/docs/P0_LIVE_ROUTING_RECOVERY_20261106.md new file mode 100644 index 000000000..02bb48043 --- /dev/null +++ b/docs/P0_LIVE_ROUTING_RECOVERY_20261106.md @@ -0,0 +1,76 @@ +# P0 live routing recovery — CH03 → CH04 and SOURCE ONLY + +Continue PR #418 on `integration/daw-direct-hardware-input-20261105`. +The approved assembled `/preview/` appearance and sole JUCE callback remain. + +## Root causes and changes + +1. `integration/ApprovedNativeControlIntent.h`, the decoder actually included + by `Main.cpp`, rejected INPUT destinations. The PCM compiler already + supports channel-to-channel routing. Admit an INPUT only when both the + accepted public and native inventories identify that exact ChannelId with + the same role. Retain epoch, graph, roster, edge, feedback and source guards. +2. `DynamicPreparedMixerBlock` culled every lane with no path to MAIN or + MONITOR. SOURCE ONLY therefore lost its DSP and local meter. Schedule + physical/insert signal roots and their descendants independently of output + reachability. Empty, unpatched descriptors still use no audio scratch. +3. Publish INPUT channels in the accepted destination inventory. Preserve + detailed native WIRE rejection reasons through the existing IPC executor + and ACK, including feedback cycle, duplicate route and stale edge. + +## Defined audio behavior + +- Physical capture and incoming WIRE PCM **sum before** the receiver's mono + fold, inserts, fader, PAN, MUTE/SOLO and post-fader meter. A hardware selector + set to None leaves incoming WIRE audio intact. +- CONNECT adds a deliberate parallel post-fader send; it can produce a second + audible path when the source still has a primary MAIN route. ROUTE ONLY + replaces the primary destination and preserves deliberate parallel sends. + Promotion of an existing send retains its EdgeId and does not double dry PCM. +- SOURCE ONLY removes the primary edge; source capture, inserts, meter and + deliberate parallel sends remain active. Removing an EdgeId affects only + that edge. Feedback cycles reject the complete candidate atomically. + +## Regression evidence + +`P0ApprovedDecoderChannelToChannelAndSourceOnlyPCM` is pulled into the existing +Windows build through `ARMixMixerRoutingTests`, then executed by CTest. +It crosses the approved production decoder/executor, accepted session, +publisher, compiler and renderer, asserting actual sample values and meters: + +- CH03 stereo hardware → MAIN; CH07 mono remains independently audible. +- CH03 → CH04 with no hardware on CH04; receiver FX gain and fader affect PCM. +- Parallel send, promotion to exclusive primary with stable EdgeId, unplug, + reconnect, retarget and CH03 → CH04 → BUS → MAIN. +- SOURCE ONLY at source or receiver retains local DSP and meters. +- Live receiver fader/PAN, FX seam bypass, MUTE/SOLO; hardware plus WIRE summing. +- Cycle rollback, stale graph/epoch and forged native destination role reject. +- Zero C++ heap allocations during every tested render block. + +The new regression fails with the old decoder and, separately, with the old +render scheduling. Existing routing/dynamic PCM tests, approved native v8 +tests, 127 fast native contracts, and deterministic approved GUI provenance +checks also pass locally. The Chromium/Windows result and exact checkpoint +SHA are recorded in PR #418; do not infer those results from this document. +The test FX seam is deterministic DSP, not a third-party VST3 hardware test. + +## Short physical FAT + +1. Use the checkpoint's **UNQUALIFIED** Windows ZIP. Choose a real ASIO/WASAPI + capture/playback pair. Set CH03 IN to stereo 1+2, CH04 IN to None, both + faders to 0 dB; no MUTE/SOLO. Verify CH03 and MAIN activity first. +2. Connect CH03 OUT → CH04 IN in normal post-fader send mode. CH04 meter must + move. Remove CH03's direct MAIN edge for a serial listening test; otherwise + the retained parallel MAIN route deliberately adds another dry contribution. +3. With CH04 → MAIN, move CH04's fader and bypass/enable a real VST3 insert. + Its output must affect MAIN. Test MONO/STEREO and MUTE/SOLO. +4. Remove CH04 → MAIN: CH03 and CH04 meters must keep moving; their contribution + to MAIN stops. Reconnect without changing hardware IN or restarting audio. +5. Set CH03 to SOURCE ONLY with no other sends: CH03's meter remains active, + CH04 no longer receives it. Reconnect and test BUS/MAIN plus device reopen. + +On failure, immediately choose **More → Copy Audio Report** and paste the +report with the exact ZIP/source SHA and routing steps. Physical listening, +vendor VST3 behavior, ASIO timing, hotplug and crackle soak remain **PENDING** +until observed on the user's hardware. This checkpoint does not authorize +merging main or promoting a stable release. diff --git a/engine/core/DynamicAcceptedSession.h b/engine/core/DynamicAcceptedSession.h index ec901f2d3..d3f3c6312 100644 --- a/engine/core/DynamicAcceptedSession.h +++ b/engine/core/DynamicAcceptedSession.h @@ -252,9 +252,12 @@ class DynamicAcceptedSession final { template bool render(std::uint64_t epoch,const float* const* inputs,int inputCount, float* mainL,float* mainR,int frames,bool muted,Fx&& fx, - float* monitorL=nullptr,float* monitorR=nullptr) noexcept { + float* monitorL=nullptr,float* monitorR=nullptr, + std::span channelPeaksL={}, + std::span channelPeaksR={}) noexcept { return publisher_.render(epoch,inputs,inputCount,mainL,mainR,frames, - muted,std::forward(fx),monitorL,monitorR); + muted,std::forward(fx),monitorL,monitorR, + channelPeaksL,channelPeaksR); } void unpublish() noexcept {publisher_.unpublish();hasHostedFx_=false;} void pollRetirement() noexcept {publisher_.pollRetirement();} diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index b9e4f66cf..066340210 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -68,7 +68,7 @@ class DynamicNativeSessionPublisher final { std::uint64_t proposedDeviceEpoch, std::uint64_t activeDeviceEpoch, bool allOutputsDisarmed, - FxPlan fx={},bool verifiedInternalWireOnly=false, + FxPlan fx={nullptr,nullptr,nullptr,0,0},bool verifiedInternalWireOnly=false, bool verifiedInternalFxOnly=false) { CommitResult report;report.revision=publisher_.lastRevision(); if(!fx.valid() || diff --git a/engine/core/DynamicPreparedMixerBlock.h b/engine/core/DynamicPreparedMixerBlock.h index e9365f83a..842592147 100644 --- a/engine/core/DynamicPreparedMixerBlock.h +++ b/engine/core/DynamicPreparedMixerBlock.h @@ -368,22 +368,11 @@ class DynamicPreparedMixerBlock final { !rows[i].mute && (!anySolo||solos[i]!=0)); next.topologicalOrder_=order; // control-prepared, never RT sorted - // One immutable render schedule serves BOTH logical output sinks. - // Active monitor-only channels must not vanish merely because they - // do not route to MAIN. Disconnected descriptors remain scratch-free. - std::vector reachesOutput(rows.size(),0); - if(next.lanes_[main].enabled)reachesOutput[main]=1; - if(monitor!=notScheduled && next.lanes_[monitor].enabled) - reachesOutput[monitor]=1; - for(auto k=order.rbegin();k!=order.rend();++k) - if(next.lanes_[*k].enabled) - for(const auto& edge:outgoing[*k]) - if(next.lanes_[edge.destination].enabled && - reachesOutput[edge.destination]) - reachesOutput[*k]=1; - // Reverse reachability alone would schedule 128 silent lanes with - // sends to MAIN. Include only actual capture sources, explicit FX - // generator lanes, and descendants; preserve empty MAIN for mute. + // Capture/FX lifetime is independent of output routing. SOURCE ONLY + // must still run inserts and publish its local post-fader meters. + // Schedule signal roots and descendants even with NO path to a sink; + // unpatched empty descriptors remain scratch-free. Keep empty sinks + // so MAIN/MONITOR silence is always rendered deterministically. std::vector hasSignal(rows.size(),0); for(std::size_t i=0;i( @@ -395,7 +384,7 @@ class DynamicPreparedMixerBlock final { hasSignal[edge.destination]=1; } for(const auto i:order) - if(reachesOutput[i] && (hasSignal[i] || i==main || i==monitor)) + if(hasSignal[i] || i==main || i==monitor) next.renderOrder_.push_back(i); // Edges must only target retained scratch lanes. This is distinct // from "reachable from MAIN": a silent incoming lane has no slot. @@ -407,7 +396,7 @@ class DynamicPreparedMixerBlock final { if(frame>0 && active>req.maxScratchBytes/(2*sizeof(float)*frame)) { error.fault=DynamicGraphFault::scratchBudget;return false; } - // One immutable CSR adjacency; only main-reachable edges retained. + // One immutable CSR adjacency over the retained processing lanes. for(std::size_t i=0;i inline bool executeApprovedNativeControl(Engine& engine, - const juce::var& translated) { + const juce::var& translated, + juce::String* nativeError=nullptr) { if(!translated.isObject())return false; std::uint64_t epoch=0,revision=0,roster=0,id=0; if(!approvedNativeId(translated.getProperty("deviceEpoch",{}),epoch) || @@ -453,6 +458,8 @@ inline bool executeApprovedNativeControl(Engine& engine, const auto applied=engine.applyNativeWireTransaction( epoch,revision,roster, std::span(changes)); + if(!applied.accepted && nativeError && applied.error) + *nativeError=applied.error; // NativeBusResult.error is const char*, not juce::String. // The compiler and regression probe must share the exact native // error ABI. Never claim ACK for a contradictory accepted/error pair. diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index b43f0293a..dcb691568 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -105,7 +105,7 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, ch->setProperty("fxRackBypassed",rackBypassed); } ch->setProperty("sends",juce::var(juce::Array{})); - if(role!="INPUT"){ + { // INPUT channels can receive WIRE PCM as well as physical capture. auto dst=std::make_unique(); dst->setProperty("id",id);dst->setProperty("name",name); dst->setProperty("role",role); diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index c09a81f97..18c8b7a76 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -96,7 +96,7 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { ch->setProperty("fxRackBypassed",rackBypassed); } ch->setProperty("sends",juce::var(juce::Array{})); - if(role!="INPUT"){ + { // INPUT channels can receive WIRE PCM as well as physical capture. auto dst=std::make_unique(); dst->setProperty("id",id);dst->setProperty("name",name); dst->setProperty("role",role); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index c65db6fe8..235a933ba 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1800,7 +1800,11 @@ class LiveDryRoutingLab final { auto roster=nativeAccepted_.graph.roster; const auto changed=roster.wireTransaction(expectedRosterRev,changes); if(!changed.ok()){ - r.error="NATIVE_WIRE_TRANSACTION_REJECTED";return r; + r.error=changed.fault==ChannelEditFault::missingEdge + ?"NATIVE_WIRE_STALE_EDGE": + changed.fault==ChannelEditFault::duplicateSend + ?"NATIVE_WIRE_DUPLICATE_ROUTE":"NATIVE_WIRE_TRANSACTION_REJECTED"; + return r; } DynamicChannelFxLeaseBank bank; if(DynamicChannelFxLeaseBank::reuseRevision( @@ -1821,7 +1825,9 @@ class LiveDryRoutingLab final { roster,nativeAccepted_.graph.request,expectedPcmRev, ep,epoch(),false,std::move(fx),true); if(!published.ok()){ - r.error="NATIVE_WIRE_PCM_GRAPH_REJECTED";return r; + r.error=published.graphError.fault==DynamicGraphFault::cycle + ?"NATIVE_WIRE_FEEDBACK_CYCLE":"NATIVE_WIRE_PCM_GRAPH_REJECTED"; + return r; } nativeAccepted_.graph.roster=std::move(roster); nativeAccepted_.fxOwners=std::move(owner); diff --git a/src/Main.cpp b/src/Main.cpp index 1b36d023d..4111ac8cd 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -923,7 +923,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr if(!applied)nativeError=result.error; } } else { - applied=armix::console::executeApprovedNativeControl(engine_,command); + applied=armix::console::executeApprovedNativeControl(engine_,command,&nativeError); } } // An engine setter ACK is not independent PCM evidence. Re-read the diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 0d75b22fa..c4ad0cec7 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -961,6 +961,36 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a const unwired=clone(updated);unwired.graph.revision="6";unwired.graph.edges=[]; listeners.get("arMixConsoleSnapshot")(unwired); assert.equal(scope.edges.length,0,"accepted snapshot replaces reference wire"); + // A receiver is an ordinary INPUT channel with no physical source. Its + // native ChannelId, never its visual ordinal, must receive the WIRE intent. + const receiver=clone(unwired.graph.channels[0]); + receiver.id="9007199254740995";receiver.name="CH04"; + delete receiver.primaryOutId; + const ready=clone(unwired);ready.graph.revision="7"; + delete ready.graph.channels[0].primaryOutId; + ready.graph.channels.splice(1,0,receiver); + ready.graph.destinations.push({id:receiver.id,role:"INPUT"}); + listeners.get("arMixConsoleSnapshot")(ready); + const receiverUi=scope.tracks.find(t=>t.name==="CH04").id; + assert.equal(window.__ARMIX_NATIVE_M2__.consumeWire([ + {type:"CONNECT",sourceId:sourceUi,destId:receiverUi,mode:"send"} + ]),true); + const send=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(send.payload.changes[0].to,receiver.id); + assert.equal(scope.edges.length,0,"INPUT WIRE stays pending until native readback"); + listeners.get("arMixConsoleAck")({ + requestId:send.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:ready.device.epoch,graphRevision:"8",rosterRevision:"8" + }); + assert.equal(scope.edges.length,0,"INPUT WIRE ACK alone never paints a cable"); + const routed=clone(ready);routed.graph.revision="8";routed.graph.rosterRevision="8"; + routed.graph.edges=[{edgeId:"9223372036854775810",from:send.targetChannelId, + to:receiver.id,tap:"POST_FADER",gainLinear:1,enabled:true, + primaryOutput:false,signalKind:"AUDIO"}]; + listeners.get("arMixConsoleSnapshot")(routed); + assert.equal(scope.edges.length,1); + assert.equal(scope.edges[0].destId,receiverUi); + assert.equal(window.__ARMIX_NATIVE_M2__.state().pending,null); }); test("P0 native FX rack and per-slot readback update mounted strip without replacing fader DOM",()=>{ diff --git a/tests/approved_native_routing_pcm_test.cpp b/tests/approved_native_routing_pcm_test.cpp new file mode 100644 index 000000000..518e25c12 --- /dev/null +++ b/tests/approved_native_routing_pcm_test.cpp @@ -0,0 +1,275 @@ +// SPDX-License-Identifier: AGPL-3.0-only +// Windows' actual approved decoder -> accepted publisher -> sample renderer. +// Offline PCM evidence, never an assertion of physical ASIO/VST vendor FAT. +#include "../integration/ApprovedNativeControlIntent.h" +#include "../engine/core/DynamicAcceptedSession.h" +#if defined(NDEBUG) +#undef NDEBUG +#endif +#include +#include +#include +#include +#include +#include + +static std::atomic allocations{0}; +void* operator new(std::size_t n) { + allocations.fetch_add(1,std::memory_order_relaxed); + if(auto* p=std::malloc(n?n:1))return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n){return ::operator new(n);} +void operator delete(void* p) noexcept {std::free(p);} +void operator delete[](void* p) noexcept {std::free(p);} +void operator delete(void* p,std::size_t) noexcept {std::free(p);} +void operator delete[](void* p,std::size_t) noexcept {std::free(p);} + +using namespace armix::mixer; +using namespace armix::console; +static bool near(float a,float b){return std::abs(a-b)<3.e-5f;} +static juce::String textId(std::uint64_t n){return juce::String(std::to_string(n));} +static juce::var object(){return juce::var(new juce::DynamicObject());} +static void put(const juce::var& v,const char* k,const juce::var& value) { + v.getDynamicObject()->setProperty(k,value); +} +static const char* roleName(ChannelRole role) { + switch(role) { + case ChannelRole::input:return "INPUT"; + case ChannelRole::group:return "GROUP"; + case ChannelRole::fxReturn:return "FX_RETURN"; + case ChannelRole::main:return "MAIN"; + case ChannelRole::monitor:return "MONITOR"; + } + return "INVALID"; +} + +struct PcmHost { + DynamicAcceptedSession pcm; + DynamicGraphRequest io; + std::uint64_t epoch=91,serial=0; + std::array channels{}; + ChannelId bus{},main{}; + std::array a{},b{},mic{},left{},right{}; + std::array peaksL{},peaksR{}; + bool fxBypass=false; + std::array calls{}; + DynamicAcceptedSession::Result last; + juce::String lastError; + struct Result {bool accepted=false;const char* error="PCM_REJECTED";}; + + PcmHost() { + io.physicalInputs=3;io.maxFrames=64; + std::vector create; + for(int i=0;i<12;++i) { + ChannelEdit e;e.kind=ChannelEdit::Kind::add;e.position=i; + e.role=i<10?ChannelRole::input:i==10?ChannelRole::group:ChannelRole::main; + e.format=ProcessingFormat::stereo;e.text="CH "+std::to_string(i+1); + create.push_back(e); + } + auto added=pcm.edit(0,0,create,io,epoch,epoch,true); + assert(added.ok()); + for(int i=0;i<10;++i)channels[i]=added.edit.createdIds[i]; + bus=added.edit.createdIds[10];main=added.edit.createdIds[11]; + io.sources={{channels[2],0,1,true},{channels[6],2,-1,false}}; + std::vector links; + for(auto from:{channels[2],channels[3],channels[6],bus}) { + WireChange w;w.kind=WireChange::Kind::routeOnly; + w.from=from;w.to=main;links.push_back(w); + } + assert(pcm.wireTransaction(1,1,links,io,epoch,epoch,true).ok()); + a.fill(.25f);b.fill(.125f);mic.fill(.1f); + assert(pcm.setLiveMix(epoch,2,channels[3],.5f,0.f)); + } + Result applyNativeWireTransaction(std::uint64_t ep,std::uint64_t rev, + std::uint64_t roster,std::span edits) { + last=pcm.wireTransaction(roster,rev,edits,io,ep,epoch,false); + return {last.ok(),last.ok()?"":"PCM_REJECTED"}; + } + bool setNativeInputMix(std::uint64_t ep,std::uint64_t rev, + ChannelId id,float gain,float pan) { + return pcm.setLiveMix(ep,rev,id,gain,pan); + } + bool setNativeBusMix(std::uint64_t ep,std::uint64_t rev, + ChannelId id,float gain,float pan) { + return pcm.setLiveMix(ep,rev,id,gain,pan); + } + bool setNativeInputMuteSolo(std::uint64_t ep,std::uint64_t rev, + ChannelId id,bool mute,bool solo) { + return pcm.setLiveMuteSolo(ep,rev,id,mute,solo); + } + // Serialize ONLY the accepted native roster/edge inventory. No guessed + // channel labels or browser graph can authorize a destination here. + juce::var readback() const { + const auto rev=pcm.acceptedGraphRevision(); + const auto* view=pcm.acceptedRouting(epoch,rev); + assert(view); + auto result=object();put(result,"graphRevision",textId(rev)); + put(result,"rosterRevision",textId(pcm.acceptedRosterRevision())); + juce::Array rows,edges,ops; + ops.add("NATIVE_APPLY_WIRE_TRANSACTION"); + for(std::size_t i=0;ichannels.size();++i) { + const auto& ch=view->channels[i]; + const auto* def=pcm.acceptedRoster().find(ch.id);assert(def); + auto row=object();put(row,"id",textId(ch.id.value)); + put(row,"name",juce::String(ch.name));put(row,"role",roleName(ch.role)); + put(row,"format",ch.format==ProcessingFormat::stereo?"STEREO":"MONO"); + put(row,"primaryOutput",textId(ch.primaryOutput.value)); + put(row,"fader",def->faderLinear);put(row,"pan",def->pan); + put(row,"mute",def->mute);put(row,"solo",def->solo); + put(row,"inserts",juce::var(juce::Array{})); + put(row,"peakL",peaksL[i]);put(row,"peakR",peaksR[i]);rows.add(row); + } + for(const auto& e:view->edges) { + auto edge=object();put(edge,"edgeId",textId(e.edgeId)); + put(edge,"from",textId(e.from.value));put(edge,"to",textId(e.to.value)); + put(edge,"gainLinear",e.gainLinear);put(edge,"primaryOutput",e.primaryOutput); + put(edge,"tap",e.preFader?"PRE_FADER":"POST_FADER");edges.add(edge); + } + put(result,"channels",juce::var(rows));put(result,"edges",juce::var(edges)); + put(result,"supportedOps",juce::var(ops));return result; + } + juce::var snapshot(const juce::var& native) const { + auto s=juce::JSON::parse(R"({"device":{"epoch":"91"},"graph":{ + "capabilities":{}},"telemetry":{}})"); + put(s.getProperty("device",{}),"epoch",textId(epoch)); + assert(projectApprovedNativeV8(s,native,true));return s; + } + juce::var request(const juce::var& edit) { + auto r=object();put(r,"requestId","pcm-wire-"+textId(++serial)); + put(r,"operation","APPLY_WIRE_TRANSACTION"); + put(r,"targetChannelId",edit.getProperty("from",{})); + put(r,"deviceEpoch",textId(epoch)); + put(r,"baseGraphRevision",textId(pcm.acceptedGraphRevision())); + put(r,"baseRosterRevision",textId(pcm.acceptedRosterRevision())); + auto payload=object();juce::Array edits;edits.add(edit); + put(payload,"changes",juce::var(edits));put(r,"payload",payload);return r; + } + bool apply(const juce::var& edit) { + const auto native=readback();const auto r=request(edit); + const auto decoded=translateApprovedNativeControl(r,snapshot(native),native); + assert(decoded.ok()); + lastError.clear(); + const bool result=executeApprovedNativeControl(*this,decoded.translated,&lastError); + pcm.pollRetirement();return result; + } + void render() { + const float* pins[]{a.data(),b.data(),mic.data()};calls.fill(0); + const auto fx=[&](ChannelId id,float* l,float* r,int n) noexcept { + const auto slot=static_cast(id.value-1);++calls[slot]; + if(id==channels[3]&&!fxBypass) + for(int f=0;f(edge.getProperty("primaryOutput",false))) { + put(e,"edgeId",edge.getProperty("edgeId",{}));return e; + } + assert(false);return {}; +} +int main() { + PcmHost h;const auto ch3=h.channels[2],ch4=h.channels[3]; + constexpr float mono=.1f*.7071067811865475f; + h.render();assert(near(h.left[63],.25f+mono));assert(h.peaksL[3]==0.f); + // Ordinary WIRE CH03 -> CH04: same decoder used by Windows Main.cpp. + assert(h.apply(link("CONNECT",ch3,ch4))); + h.render();assert(near(h.peaksL[3],.0625f)); + assert(near(h.left[63],.3125f+mono)); // deliberate parallel path + auto rb=h.readback();auto s=h.snapshot(rb); + assert(s.getProperty("graph",{}).getProperty("destinations",{}).size()==12); + assert(near(static_cast(s.getProperty("telemetry",{}) + .getProperty("channelMeterRmsPeak",{}).getProperty(textId(ch4.value),{}) + .getProperty("peakL",0.)),.0625f)); + // ROUTE ONLY promotes the existing send EdgeId without double-dry. + juce::String wireId; + for(const auto& edge:*rb.getProperty("edges",{}).getArray()) + if(edge.getProperty("from","").toString()==textId(ch3.value)&& + edge.getProperty("to","").toString()==textId(ch4.value)) + wireId=edge.getProperty("edgeId",{}).toString(); + assert(wireId.isNotEmpty()); + assert(h.apply(link("ROUTE_ONLY",ch3,ch4))); + h.render();assert(near(h.left[63],.0625f+mono)); + const auto* view=h.pcm.acceptedRouting(h.epoch,h.pcm.acceptedGraphRevision()); + assert(view->find(ch3)->primaryOutput==ch4); + bool retained=false; + for(const auto& e:view->edges)if(e.from==ch3&&e.to==ch4) + retained=textId(e.edgeId)==wireId; + assert(retained); + // Disconnect MAIN from receiver: both source and receiver DSP/meters + // remain alive. Only the unrelated CH07 still reaches MAIN. + const auto staleRemove=removePrimary(h,ch4); + const auto staleRequest=h.request(staleRemove); + assert(h.apply(staleRemove));h.render(); + assert(near(h.left[63],mono)&&near(h.peaksL[2],.25f)); + assert(near(h.peaksL[3],.0625f)&&h.calls[3]==1); + // Live fader, stereo PAN, FX bypass, MUTE/SOLO while source-only. + auto rev=h.pcm.acceptedGraphRevision(); + assert(h.pcm.setLiveMix(h.epoch,rev,ch4,.25f,1.f)); + h.render();h.render();assert(h.peaksL[3]==0.f&&near(h.peaksR[3],.015625f)); + h.fxBypass=true;h.render();assert(near(h.peaksR[3],.03125f)); + assert(h.pcm.setLiveMuteSolo(h.epoch,rev,ch4,true,false)); + h.render();h.render();assert(h.peaksR[3]==0.f); + assert(h.pcm.setLiveMuteSolo(h.epoch,rev,ch4,false,true)); + h.render();h.render();assert(near(h.peaksR[3],.03125f)); + assert(h.left[63]==0.f&&h.right[63]==0.f); // unrelated CH07 solo-suppressed + assert(h.pcm.setLiveMuteSolo(h.epoch,rev,ch4,false,false)); + assert(h.pcm.setLiveMix(h.epoch,rev,ch4,.5f,0.f));h.fxBypass=false; + h.render();h.render(); + // Serial CH03 -> CH04 -> BUS -> MAIN, then source-only at CH03. + assert(h.apply(link("ROUTE_ONLY",ch4,h.bus)));h.render(); + assert(near(h.left[63],.0625f+mono)&&near(h.peaksL[10],.0625f)); + assert(h.apply(removePrimary(h,ch3)));h.render(); + assert(near(h.peaksL[2],.25f)&&h.peaksL[3]==0.f); + assert(near(h.left[63],mono)); + // Reconnect without touching physical IN; retarget the SAME EdgeId. + assert(h.apply(link("ROUTE_ONLY",ch3,ch4)));h.render(); + auto retarget=removePrimary(h,ch3);put(retarget,"op","RETARGET"); + put(retarget,"to",textId(h.bus.value)); + assert(h.apply(retarget));h.render();assert(near(h.left[63],.25f+mono)); + // Hardware + WIRE are summed BEFORE receiver FX/fader, exactly once. + auto io=h.io;io.sources.push_back({ch4,0,1,true}); + ChannelEdit width;width.kind=ChannelEdit::Kind::setFormat; + width.id=ch4;width.format=ProcessingFormat::stereo; + assert(h.pcm.edit(h.pcm.acceptedRosterRevision(),h.pcm.acceptedGraphRevision(), + std::span(&width,1),io,h.epoch,h.epoch,true).ok()); + h.io=io;h.pcm.pollRetirement(); + assert(h.apply(link("ROUTE_ONLY",ch3,ch4)));h.render(); + assert(near(h.peaksL[3],.125f)&&near(h.left[63],.125f+mono)); + // Feedback cycle is rejected atomically by the actual graph compiler. + const auto beforeRev=h.pcm.acceptedGraphRevision(); + assert(!h.apply(link("CONNECT",ch4,ch3))); + assert(h.lastError=="PCM_REJECTED"); // preserve native reason through IPC executor + assert(h.last.native.graphError.fault==DynamicGraphFault::cycle); + assert(h.pcm.acceptedGraphRevision()==beforeRev);h.render(); + assert(near(h.left[63],.125f+mono)); + const auto current=h.readback();const auto accepted=h.snapshot(current); + assert(translateApprovedNativeControl(staleRequest,accepted,current).error== + "STALE_NATIVE_CONTROL_REVISION"); + auto wrongRole=juce::JSON::parse(juce::JSON::toString(current)); + put(wrongRole.getProperty("channels",{})[3],"role","MONITOR"); + auto fresh=h.request(link("CONNECT",ch3,ch4)); + assert(translateApprovedNativeControl(fresh,accepted,wrongRole).error== + "WIRE_UNSUPPORTED_DESTINATION"); + h.epoch=92; // stale generation must not receive cached source PCM + const float* pins[]{h.a.data(),h.b.data(),h.mic.data()}; + assert(!h.pcm.render(h.epoch,pins,3,h.left.data(),h.right.data(),64,false, + +[](ChannelId,float*,float*,int) noexcept {})); + assert(h.left[63]==0.f&&h.right[63]==0.f); + PcmHost reconnected;reconnected.render(); + assert(near(reconnected.left[63],.25f+mono)); +} From 2ce79c4185d9f0b98faee5e48dc5046dab561912 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 16:26:13 +0700 Subject: [PATCH 117/219] test(gui): validate compiled approved preview instead of retired publication variants Repair the full Chromium failure: seven historical regressions still demanded assets/HTML in redirect-only preview-v2 or preview-buttons routes. Run their unchanged visual/gesture assertions on the sole compiled /preview/index.html and reuse the independent exact-HTML/CSS/PNG provenance gate. No runtime, DSP, native binary input, GUI source or workflow changes. --- tests/approved_publication_fixture.py | 21 +++++++++++++++++++ tests/pages_contextual_buttons_smoke.py | 16 +++++++------- tests/pages_contextual_contrast_smoke.py | 6 +++--- .../pages_m1_meter_gain_calibration_smoke.py | 19 ++++++----------- tests/pages_micro_fader_visual_v18_smoke.py | 6 +++--- tests/pages_wire_v44_finish_smoke.py | 5 ++--- tests/pages_wire_v45_socket_layout_smoke.py | 5 ++--- tests/pages_wire_v46_precision_smoke.py | 6 ++---- 8 files changed, 47 insertions(+), 37 deletions(-) create mode 100644 tests/approved_publication_fixture.py diff --git a/tests/approved_publication_fixture.py b/tests/approved_publication_fixture.py new file mode 100644 index 000000000..b8c42f6b3 --- /dev/null +++ b/tests/approved_publication_fixture.py @@ -0,0 +1,21 @@ +"""Resolve the sole shipped console after checking its exact build provenance. + +Authoring HTML is a compiler input, and legacy URLs are redirect shells. +Browser regressions must exercise /preview/index.html, not demand a second +published skin or compare generated HTML with an unassembled input file. +""" +from pathlib import Path +import subprocess +import sys + +ROOT = Path(__file__).resolve().parents[1] + + +def published_console(dist): + dist = Path(dist) + # This existing independent contract checks the complete assembled HTML, + # compiled CSS bytes/hashes, approved PNG assets and legacy-only redirects. + subprocess.run( + [sys.executable, str(ROOT / "tests/single_preview_publication_contract_test.py"), + str(dist)], cwd=ROOT, check=True, capture_output=True, text=True) + return dist / "preview/index.html" diff --git a/tests/pages_contextual_buttons_smoke.py b/tests/pages_contextual_buttons_smoke.py index 6f93f27c8..0f25a9e7d 100644 --- a/tests/pages_contextual_buttons_smoke.py +++ b/tests/pages_contextual_buttons_smoke.py @@ -6,6 +6,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] OWNER='mixer-contextual-buttons.css' @@ -113,24 +114,23 @@ def main(): subprocess.run([sys.executable,str(ROOT/'scripts/build_pages.py'), '--out',str(dist),'--sha','v6-ci','--branch','main'], cwd=ROOT,check=True,capture_output=True,text=True) - for target in ('preview','preview-v2','preview-buttons'): - assets=dist/target/'assets' - assert (assets/OWNER).read_bytes()==(ROOT/'site/preview-v2/assets'/OWNER).read_bytes(),target - assert (assets/SCRIPT).read_bytes()==(ROOT/'site/preview-v2/assets'/SCRIPT).read_bytes(),target + published=published_console(dist) + assets=published.parent/'assets' + assert (assets/OWNER).read_bytes()==(ROOT/'site/preview-v2/assets'/OWNER).read_bytes() + assert (assets/SCRIPT).read_bytes()==(ROOT/'site/preview-v2/assets'/SCRIPT).read_bytes() png_src=ROOT/'site/preview-buttons/assets' - png_pub=dist/'preview-buttons/assets' + png_pub=assets for file in ('mixer-control-keys.css','mixer-control-keys.js','mute-solo-pfl-56x37.png'): assert (png_pub/file).read_bytes()==(png_src/file).read_bytes(),file with sync_playwright() as p: browser=p.chromium.launch(headless=True) for file,label in ( (CANON,'canonical'), - (dist/'preview/mixer.html','public'), - (dist/'preview-buttons/index.html','png') + (published,'png') ): check_page(browser,file,label) browser.close() - print('PASS V6 OTHER buttons: 3 routes, PNG protected, action release, native latches,') + print('PASS V6 OTHER buttons: authoring source + sole approved /preview/, PNG protected, action release, native latches,') print('micro geometry, fixed MAIN size, no pointer-focus or layout scroll') diff --git a/tests/pages_contextual_contrast_smoke.py b/tests/pages_contextual_contrast_smoke.py index d1bc627a1..1faabf800 100644 --- a/tests/pages_contextual_contrast_smoke.py +++ b/tests/pages_contextual_contrast_smoke.py @@ -10,6 +10,7 @@ from pathlib import Path import subprocess, sys, tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] PAGE=ROOT/"site/preview-v2/index.html" @@ -116,14 +117,13 @@ def main(): with sync_playwright() as p: browser=p.chromium.launch(headless=True) for path,label in ((PAGE,"canonical"), - (dst/"preview/mixer.html","published-mixer"), - (dst/"preview-buttons/index.html","approved-png")): + (published_console(dst),"approved-png")): page=browser.new_page(viewport={"width":1680,"height":900}) verify(page,label,path) page.close() browser.close() print("PASS arrow OFF/ON icon contrast, unchanged geometry, Route to Bus dark microcopy,") - print("WIRE linked/legacy semantic contrast, and PNG reference route 3/3") + print("WIRE linked/legacy semantic contrast, authoring source + approved PNG /preview/") if __name__=="__main__": diff --git a/tests/pages_m1_meter_gain_calibration_smoke.py b/tests/pages_m1_meter_gain_calibration_smoke.py index a34c63b23..f3904a624 100644 --- a/tests/pages_m1_meter_gain_calibration_smoke.py +++ b/tests/pages_m1_meter_gain_calibration_smoke.py @@ -11,6 +11,7 @@ from pathlib import Path from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT = Path(__file__).resolve().parents[1] CANON = ROOT / "site/preview-v2/index.html" @@ -199,17 +200,9 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","m1-calibrated","--branch","m1"], cwd=ROOT,check=True,capture_output=True,text=True) - published=dist/"preview/mixer.html" - assert published.read_bytes()==CANON.read_bytes(),"Published mixer source drift" - expected_ruler_keys={ - "mixer-fader-assembly.css":"css-owner-v27-fader-rollback-pre-v52-tail", - "mixer-meter-display.css":"css-owner-v27-meter-pruned", - } - for name,key in expected_ruler_keys.items(): - assert f"assets/{name}?v={key}" in published.read_text("utf-8"),( - "stale ruler cache URL",name,key) - for name in ("mixer-fader-assembly.css","mixer-meter-display.css"): - assert (dist/"preview/assets"/name).read_bytes()==(ASSETS/name).read_bytes(),name + # The shared provenance gate verifies every compiled ruler owner and + # its content-addressed runtime bundle against the exact source. + published=published_console(dist) with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for html,label,width,height in ( @@ -217,7 +210,7 @@ def main(): (CANON,"canonical",1680,900), (CANON,"canonical",1920,1080), (published,"pages",1680,900), - (dist/"preview-buttons/index.html","png",1366,768)): + (published,"png",1366,768)): page=browser.new_page(viewport={"width":width,"height":height}) errors=[] page.on("pageerror",lambda exc:errors.append(str(exc))) @@ -233,7 +226,7 @@ def main(): page.close() browser.close() print("PASS M1: dBFS meter and gain rulers calibrated to physical travel; " - "preview demo displays real dBFS percentages, 3 densities × 3 sizes × 3 Pages routes") + "preview demo displays real dBFS percentages, 3 densities × 3 sizes, source + sole approved /preview/") if __name__=="__main__": main() diff --git a/tests/pages_micro_fader_visual_v18_smoke.py b/tests/pages_micro_fader_visual_v18_smoke.py index cb7446100..1d71127d0 100644 --- a/tests/pages_micro_fader_visual_v18_smoke.py +++ b/tests/pages_micro_fader_visual_v18_smoke.py @@ -7,6 +7,7 @@ import sys import tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] SOURCE=ROOT/"site/preview-v2/index.html" @@ -111,13 +112,12 @@ def main(): with sync_playwright() as playwright: browser=playwright.chromium.launch(headless=True) for path,label in ((SOURCE,"canonical"), - (dist/"preview/mixer.html","public"), - (dist/"preview-buttons/index.html","png")): + (published_console(dist),"png")): page=browser.new_page(viewport={"width":1680,"height":900},device_scale_factor=1) check(page,path,label) browser.close() print("PASS V18: Material delete+phase, 17px square buttons, calibrated rulers,") - print("no label overlaps across densities, PNG preserved, 3 real preview routes") + print("no label overlaps across densities, PNG preserved, source + sole approved /preview/") if __name__=="__main__": main() diff --git a/tests/pages_wire_v44_finish_smoke.py b/tests/pages_wire_v44_finish_smoke.py index b06887855..3838be598 100644 --- a/tests/pages_wire_v44_finish_smoke.py +++ b/tests/pages_wire_v44_finish_smoke.py @@ -3,6 +3,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console from pages_wire_incoming_v43_smoke import center, impact_peak ROOT=Path(__file__).resolve().parents[1] @@ -20,10 +21,8 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dst),"--sha","v44-ui-smoke","--branch","gui-v44"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dst/"preview/mixer.html" - assert public.read_bytes()==SRC.read_bytes(),"published /preview/ differs from canonical GUI" + public=published_console(dst) assert (dst/"preview/assets/mixer-wire-dots.css").read_bytes()==CSS.read_bytes(),"published WIRE style missing" - assert 'assets/mixer-wire-dots.css?v=v59-selected-wire-quiet' in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680): diff --git a/tests/pages_wire_v45_socket_layout_smoke.py b/tests/pages_wire_v45_socket_layout_smoke.py index 9c5f2773c..214545fad 100644 --- a/tests/pages_wire_v45_socket_layout_smoke.py +++ b/tests/pages_wire_v45_socket_layout_smoke.py @@ -6,6 +6,7 @@ from pathlib import Path import subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console from pages_wire_incoming_v43_smoke import center ROOT=Path(__file__).resolve().parents[1] @@ -61,10 +62,8 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","v45-browser","--branch","v45"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dist/"preview/mixer.html" - assert public.read_bytes()==HTML.read_bytes(),"Pages did not publish canonical V45 console" + public=published_console(dist) assert (dist/"preview/assets/mixer-wire-dots.css").read_bytes()==STYLE.read_bytes(),"Pages lost WIRE CSS" - assert "assets/mixer-wire-dots.css?v=v59-selected-wire-quiet" in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680,1920): diff --git a/tests/pages_wire_v46_precision_smoke.py b/tests/pages_wire_v46_precision_smoke.py index 95a8f1e0d..fef2b0cb7 100644 --- a/tests/pages_wire_v46_precision_smoke.py +++ b/tests/pages_wire_v46_precision_smoke.py @@ -10,6 +10,7 @@ from pathlib import Path from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] HTML=ROOT/"site/preview-v2/index.html" @@ -49,12 +50,9 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"), "--out",str(dist),"--sha","v46-dot-anchors","--branch","v46"], cwd=ROOT,capture_output=True,text=True,check=True) - public=dist/"preview/mixer.html" - assert public.read_bytes()==HTML.read_bytes(),"published /preview/ HTML is stale" + public=published_console(dist) assert (dist/"preview/assets/mixer-wire-dots.css").read_bytes()==CSS.read_bytes(),"public WIRE CSS differs" - assert "assets/mixer-wire-dots.css?v=v59-selected-wire-quiet" in public.read_text("utf-8") assert (dist/"preview/assets/mixer-wire-out-align-v48.css").read_bytes()==(ROOT/"site/preview-v2/assets/mixer-wire-out-align-v48.css").read_bytes(), "V48 alignment stylesheet missing from /preview/" - assert "assets/mixer-wire-out-align-v48.css?v=out-center-v48" in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) From 68ade132d14d75430df8c6dd66037160166c6be1 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 16:31:03 +0700 Subject: [PATCH 118/219] test(wire): verify PNG and WIRE provenance through the compiled runtime bundle V43's old direct stylesheet-link assertion predates the one-CSS runtime bundle. Reuse the same strict independent publication gate and retain all physical socket/cable/gesture assertions. All eight publication preflights are checked before requesting full Chromium again. Native/build/product sources are unchanged. --- tests/pages_wire_incoming_v43_smoke.py | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/tests/pages_wire_incoming_v43_smoke.py b/tests/pages_wire_incoming_v43_smoke.py index 8c6b3f33f..a914c947a 100644 --- a/tests/pages_wire_incoming_v43_smoke.py +++ b/tests/pages_wire_incoming_v43_smoke.py @@ -3,6 +3,7 @@ from pathlib import Path import math,re,subprocess,sys,tempfile from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] CANONICAL=ROOT/"site/preview-v2/index.html" @@ -53,11 +54,9 @@ def main(): subprocess.run([sys.executable,str(ROOT/"scripts/build_pages.py"),"--out",str(dst), "--sha","v43-ci-source","--branch","main"],check=True, cwd=ROOT,capture_output=True,text=True) - public=dst/"preview/index.html" + public=published_console(dst) shared=dst/"preview/assets/mixer-wire-dots.css" - assert "mixer-control-keys.css?rev=" in public.read_text("utf-8"),"Published /preview/ lost approved PNG hardware keys" assert shared.read_bytes()==WIRE_CSS.read_bytes(),"Approved /preview/ did not publish the effective WIRE CSS" - assert 'assets/mixer-wire-dots.css?v=v59-selected-wire-quiet' in public.read_text("utf-8") with sync_playwright() as pw: browser=pw.chromium.launch(headless=True) for width in (1366,1680): From 9733446112cc7beb1909465f7559208a484d0796 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 16:38:36 +0700 Subject: [PATCH 119/219] ci(ui): qualify the current live console without replaying archived CSS migrations Keep full current /preview/ provenance, computed/screenshot parity and WIRE/FX/fader/meter/viewport regressions mandatory. Make the 28 archived V8-V27 test/mount/restore steps explicit historical_css maintenance opt-in (default false); their historical byte gate cannot qualify current live routing. Retain all archived tests and add semantic guard coverage for required current checks. No DSP/native/product GUI changes. --- .github/workflows/ui-smoke.yml | 73 ++++++++++++++------------- docs/SMART_CI_RUNNER_WORKFLOW.md | 8 +++ tests/ci_workflow_efficiency_test.mjs | 20 +++++++- 3 files changed, 65 insertions(+), 36 deletions(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 5f6349694..940d5b748 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -49,10 +49,15 @@ on: - 'scripts/chat_ci_dispatch.mjs' - 'tests/chat_ci_dispatch_contract.test.mjs' - '.github/workflows/chat-ci-milestone.yml' - # Manually run full Chromium (including immutable historical tests) on a - # specific development branch whenever a milestone needs visual qualification. + # Exact-SHA product qualification covers the CURRENT shipped console. + # Immutable historical migrations are an independent maintenance opt-in. workflow_dispatch: inputs: + historical_css: + description: "Also run archived V8-V27 migration fixtures (CSS maintenance only)" + type: boolean + required: false + default: false expected_sha: description: "Immutable source SHA for ChatGPT milestone" type: string @@ -209,12 +214,12 @@ jobs: - name: Verify V15 real pointer OUT-to-IN wire and exclusive Bus routing if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} run: python tests/preview_v15_drag_wire_smoke.py - # V10–V24 are exact historical migration/restoration tests. They compare - # original versioned bytes, so run them on immutable V24 rather than - # pretending the intentional V50 layout/stylesheet changes are V22. - # Restore PR files before ALL current GUI/function/geometry smoke tests. + # Archived CSS migrations compare historical bytes, not the current + # shipped mixer. Keep them available for explicit CSS maintenance; do + # not mount old skins during an ordinary live-audio product milestone. + # If requested, restore sources before ALL current product regressions. - name: Mount pinned V24 historical CSS fixture (reversible, no CI rebaseline) - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -227,58 +232,58 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V8 FX rack and Plugin Manager CSS ownership - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_ownership_v8_smoke.py - name: Verify V9 PAN/fader/meter CSS ownership and geometry - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_ownership_v9_smoke.py - name: Verify V10 cascade ownership and rendered console geometry - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v10_smoke.py - name: Validate V11 section ownership, cascade and computed visual styles - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v11_smoke.py - name: Verify V12 removed shadow declarations and old/new visual + control parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v12_smoke.py - name: Verify V13 owned CSS conflicts and physical control visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v13_smoke.py - name: Verify V14 canonical 45 material tokens and V13 browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v14_smoke.py - name: Verify V15 clean cross-owner CSS and actual interactive visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v15_smoke.py - name: Verify V16 WIRE single CSS owner, 241-rule exact source and visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v16_smoke.py - name: Verify V17 Plugin Manager and Fast FX Picker single CSS owner - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v17_smoke.py - name: Verify V18 physical Chrome ownership and four cascade conflict removals - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v18_smoke.py - name: Verify V19 shared operator key ownership and six shadowed declarations - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v19_smoke.py - name: Verify V20 elimination of 53 shadowed declarations and Chromium state parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v20_smoke.py - name: Verify V21 physical console chassis geometry owner and visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v21_smoke.py - name: Verify V22 legacy key material migration and M3 visual parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v22_smoke.py - name: Verify V23 exact cascade deletions and browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v23_smoke.py - name: Verify V24 Fader/Meter/FX cascade pruning and browser parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v24_smoke.py - name: Restore and verify exact V50 PR assets before current UI smoke - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -291,7 +296,7 @@ jobs: # The V25 historical test is an immutable exact-byte migration gate. # Do not rebaseline it after deliberate V26 dead-rule removals. - name: Mount pinned V25 original CSS before historical V25 migration test - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -304,10 +309,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V25 exact V51 physical-key owner migration and zero visual regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v25_smoke.py - name: Restore and verify current V26 source before latest GUI tests - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -319,7 +324,7 @@ jobs: git diff --exit-code -- site/preview-v2/index.html site/preview-v2/assets/mixer-control-keys.css site/preview-v2/assets/mixer-chrome-material.css site/preview-v2/assets/mixer-plugin-browser.css site/preview-v2/assets/mixer-pan-controls.css site/preview-v2/assets/mixer-fader-assembly.css site/preview-v2/assets/mixer-meter-display.css site/preview-v2/assets/mixer-utility-controls.css # Byte-exact V26 historical CSS check is pinned, not rebaselined. - name: Mount V26 approved source before historical regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -332,10 +337,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V26 retired socket dead rules and exact V25 visual/control parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v26_smoke.py - name: Restore P0 current WIRE source after historical V26 regression - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -348,7 +353,7 @@ jobs: # V27 is a byte-exact historical CSS migration proof; it must run # against its original qualified GUI, never rebaseline a newer FX/rail. - name: Mount pinned V27 GUI and CSS owners for immutable parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail @@ -361,10 +366,10 @@ jobs: git show "$baseline:$path" > "$path" done - name: Verify V27 scoped material and 37 owned loser declarations with Chromium parity - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} run: python tests/pages_css_architecture_v27_smoke.py - name: Restore and verify exact V53 current sources after historical V27 - if: ${{ github.event_name == 'workflow_dispatch' || (github.event_name == 'pull_request' && startsWith(github.head_ref, 'integration/product-')) }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.historical_css == true }} shell: bash run: | set -euo pipefail diff --git a/docs/SMART_CI_RUNNER_WORKFLOW.md b/docs/SMART_CI_RUNNER_WORKFLOW.md index 7259bc4c5..6d4c09eaa 100644 --- a/docs/SMART_CI_RUNNER_WORKFLOW.md +++ b/docs/SMART_CI_RUNNER_WORKFLOW.md @@ -28,6 +28,14 @@ for physical audio-interface listening, ASIO timing or glitch measurements. Draft checks deliberately do not certify a release. A PR's latest commit must pass the applicable full checks before merge. +Current product Chromium qualification always retains approved GUI provenance, +CSS visual parity, live-control/WIRE/FX/meter/fader interaction and viewport +checks. Archived V8–V27 CSS migrations compare historical source bytes and +mount old fixtures; they run only with `historical_css: true` for explicit CSS +maintenance. The normal connector `ui` lane leaves this option false, so an +audio milestone never replaces the current console with an archival skin. +All 28 historical test/mount/restore steps remain available independently. + The runner economy comes from *not scheduling* paid Windows or Playwright during PR iteration, not from sleeps, fake success, silenced CTest, or removing critical audio safety tests. Path-only changes to docs do not diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index f3b9d2050..c81b72413 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -129,8 +129,24 @@ test('ordinary GUI PR and main use current targeted checks; full history is expl assert.match(ui, /python tests\/pages_v55_context_wire_fader_smoke.py/); assert.match(ui, /node tests\/wire_main_native_handoff_contract.test.cjs/); assert.match(ui, /python tests\/pages_v51_portrait_led_peak_hold_smoke.py/); - const fullOnly = [...ui.matchAll(/^\s{8}if: .*workflow_dispatch.*integration\/product-/gm)].length; - assert.ok(fullOnly >= 35, 'Historical/extended GUI steps must be opt-in, found ' + fullOnly); + assert.match(ui,/historical_css:\n\s+description:.*\n\s+type: boolean\n\s+required: false\n\s+default: false/); + const start=ui.indexOf(' - name: Mount pinned V24 historical CSS fixture'); + const end=ui.indexOf(' - name: Verify V28 exact approved /preview/ source'); + assert.ok(start>0&&end>start,'archived fixtures and current product checks must remain distinct'); + const archived=ui.slice(start,end).split(/(?= - name: )/).filter(s=>s.trim()); + assert.equal(archived.length,28,'all archived tests and mount/restore steps remain available'); + for(const step of archived) + assert.match(step,/if: \$\{\{ github\.event_name == 'workflow_dispatch' && inputs\.historical_css == true \}\}/); + // Real product functional/geometry/provenance checks must never inherit + // the historical opt-in or disappear with the old fixture mounts. + for(const file of ['pages_wire_incoming_v43_smoke.py','preview_v15_drag_wire_smoke.py', + 'pages_m1_meter_gain_calibration_smoke.py','pages_m3_operator_visual_interaction_smoke.py', + 'pages_wire_v44_finish_smoke.py','pages_wire_v45_socket_layout_smoke.py', + 'pages_wire_v46_precision_smoke.py']) { + const step=ui.split(/(?= - name: )/).find(s=>s.includes('python tests/'+file)); + assert.ok(step,file+' stays required in current UI qualification'); + assert.ok(!step.includes('inputs.historical_css'),file+' was incorrectly made historical'); + } assert.match(ui, /python tests\/pages_css_architecture_v27_smoke.py/); assert.match(ui, /retention-days: 3/); }); From cc373798c8dbf170d40806e8e85d068f5d238782 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 16:50:12 +0700 Subject: [PATCH 120/219] test(gui): reconcile remaining PNG and V7 publication gates with the exact approved assembler Use the independent full HTML/CSS/PNG provenance verifier instead of assuming the only build changes are two stylesheet URLs. Preserve exact PNG bytes, RGBA geometry, JS/artwork source identity, compiled CSS verification, asset inventory and all real browser gestures/geometry. All 47 current workflow publication preflights pass locally before Chromium dispatch. Product/build inputs remain byte-identical to the 97334461 Windows checkpoint. --- ...s_png_buttons_wire_reconciliation_smoke.py | 28 ++++++++----------- tests/preview_v2_v7_visual_smoke.py | 21 ++++++-------- 2 files changed, 20 insertions(+), 29 deletions(-) diff --git a/tests/pages_png_buttons_wire_reconciliation_smoke.py b/tests/pages_png_buttons_wire_reconciliation_smoke.py index 036003f62..76327b950 100644 --- a/tests/pages_png_buttons_wire_reconciliation_smoke.py +++ b/tests/pages_png_buttons_wire_reconciliation_smoke.py @@ -7,13 +7,13 @@ """ import hashlib import json -import re import struct import subprocess import sys import tempfile from pathlib import Path from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT=Path(__file__).resolve().parents[1] REFERENCE=ROOT/"site/preview-v2" @@ -37,27 +37,23 @@ def verify_bundle(dist): assert "url=../preview/" in (dist/"preview-buttons/index.html").read_text(encoding="utf-8") assert 'http-equiv="refresh"' in (dist/"preview/mixer.html").read_text(encoding="utf-8") - # Strip only the two deliberate fingerprinted CSS/JS URLs. Everything - # else, including the V46+ WIRE model and channel events, must be 1:1. - stripped=html + # The shipped page uses the current authoritative-FX transformation and + # one compiled CSS bundle. The independent gate reconstructs/compares ALL + # generated HTML and owner CSS bytes, including approved PNG revisions. + assert published_console(dist)==generated/"index.html" for name in SPECIAL: - path="assets/"+name - original_url=re.search(re.escape(path)+r'(?:\?[^"\s>]+)?',original) - current_url=re.search(re.escape(path)+r'\?rev=([0-9a-f]{16})',stripped) - assert original_url and current_url,(name,"missing cache-safe URL") expected=hashlib.sha256((OWNER/name).read_bytes()).hexdigest()[:16] - assert current_url.group(1)==expected,(name,"wrong asset revision") - stripped=stripped[:current_url.start()]+original_url.group(0)+stripped[current_url.end():] + assert meta["button_css_js_revisions"][name]==expected,name assert (generated/"assets"/name).read_bytes()==(OWNER/name).read_bytes(),name - assert stripped==original,"User-approved button variant modified the real WIRE mixer" - - # Removing old snapshots makes every extra asset a current-source - # dependency, never a cloned V45 file frozen across future WIRE updates. canonical={f.name for f in (REFERENCE/"assets").iterdir() if f.is_file()} published={f.name for f in (generated/"assets").iterdir() if f.is_file()} - assert published==canonical|{SPRITE},("asset set drift",published^canonical) + assert published==canonical|{SPRITE,"arsonmix-approved-runtime.css"},( + "asset set drift",published^canonical) for name in canonical-set(SPECIAL): - assert (generated/"assets"/name).read_bytes()==(REFERENCE/"assets"/name).read_bytes(),name + # Compiled CSS is checked byte-for-byte by published_console above. + # Uncompiled JS/SVG/font/artwork assets must remain exact source bytes. + if not name.endswith(".css"): + assert (generated/"assets"/name).read_bytes()==(REFERENCE/"assets"/name).read_bytes(),name png=(generated/"assets"/SPRITE).read_bytes() assert png==(ROOT/"site/preview-v34/assets"/SPRITE).read_bytes() diff --git a/tests/preview_v2_v7_visual_smoke.py b/tests/preview_v2_v7_visual_smoke.py index 09f095a73..cfa008edb 100644 --- a/tests/preview_v2_v7_visual_smoke.py +++ b/tests/preview_v2_v7_visual_smoke.py @@ -1,14 +1,15 @@ #!/usr/bin/env python3 """Run headless real-Chromium physical geometry and workflow audit for Pages V7. -This is an independent review of the published /preview-v2/ snapshot in main, -NOT a validation of native ASIO/VST3 audio. Screenshots are uploaded by UI smoke. -No external web request; local site/preview-v2/index.html only. +Review both the internal authoring source and the sole published /preview/. +This does not validate native ASIO/VST3 audio. Screenshots are uploaded by UI +smoke. All browser pages are local deterministic build outputs. """ from __future__ import annotations from pathlib import Path -import subprocess, sys, re +import subprocess, sys from playwright.sync_api import sync_playwright +from approved_publication_fixture import published_console ROOT = Path(__file__).resolve().parents[1] PAGE = (ROOT / "site/preview-v2/index.html").resolve() @@ -296,15 +297,9 @@ def main(): "--out", str(ROOT / "_preview-public-qa"), "--sha", "qa"], check=True) assert PAGE.exists() and PUBLIC.exists(), (PAGE, PUBLIC) - assembled=PUBLIC.read_text(encoding="utf-8") - raw=PAGE.read_text(encoding="utf-8") - for asset in ("mixer-control-keys.css","mixer-control-keys.js"): - token="assets/"+asset - source_link=re.search(re.escape(token)+r'(?:\?[^"\s>]+)?',raw) - assert source_link,(asset,"source link missing") - assembled=re.sub(re.escape(token)+r'\?rev=[0-9a-f]{16}', - lambda _: source_link.group(0),assembled) - assert assembled==raw, "Public /preview/ must preserve every GUI interaction and differ only in approved PNG key URLs" + # Verify the exact current assembler (approved PNG, FX semantics and + # compiled CSS), not a comparison against the unassembled authoring HTML. + assert published_console(PUBLIC.parent.parent)==PUBLIC assert 'http-equiv="refresh"' in (PUBLIC.parent/"mixer.html").read_text(encoding="utf-8") count = 0 with sync_playwright() as playwright: From 16fe8c42d365f76ef24d143a5040bc8aee812ef7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Fri, 6 Nov 2026 20:00:29 +0700 Subject: [PATCH 121/219] feat(audio): connect live WIRE gain and identity-safe OUT to native PCM --- .github/workflows/ui-smoke.yml | 3 + docs/P1_NATIVE_WIRE_GAIN_20261106.md | 37 ++++++ engine/core/DynamicAcceptedSession.h | 9 ++ engine/core/DynamicNativeSessionPublisher.h | 32 ++++- engine/core/DynamicPreparedMixerBlock.h | 6 + integration/ApprovedNativeControlIntent.h | 43 +++++++ integration/ApprovedNativeRuntimeSnapshot.h | 2 + integration/ApprovedNativeV8Projection.h | 3 + scripts/build_approved_native_gui.py | 14 ++- src/ApprovedNativeV8Projection.h | 3 + src/LiveAudioEngine.h | 9 ++ src/LiveDryRoutingLab.h | 22 ++++ tests/approved_native_m2_contract.test.cjs | 103 +++++++++++++++- tests/approved_native_routing_pcm_test.cpp | 54 ++++++++ tests/approved_native_wire_gain_smoke.py | 129 ++++++++++++++++++++ web/approved-native-bridge.js | 98 ++++++++++++--- web/approved-native-contract.js | 19 ++- 17 files changed, 564 insertions(+), 22 deletions(-) create mode 100644 docs/P1_NATIVE_WIRE_GAIN_20261106.md create mode 100644 tests/approved_native_wire_gain_smoke.py diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 940d5b748..2c455a7b4 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -175,6 +175,8 @@ jobs: run: python tests/approved_preview_mobile_navigation_smoke.py - name: FX rack master bypass preserves each insert state (real Chromium) run: python tests/approved_fx_rack_master_power_smoke.py + - name: Native WIRE gain and OUT share accepted PCM identity (real Chromium) + run: python tests/approved_native_wire_gain_smoke.py - name: Stage D one runtime CSSOM and actual stylesheet network count run: python tests/approved_css_stage_d_single_bundle_smoke.py - name: Stage C rendered CSS parity (original vs compiled, three viewports + hover) @@ -458,5 +460,6 @@ jobs: pages-v55-*.png pages-v28-physical-console-owner-v59-*.png pages-mobile-*.png + native-wire-gain-*.png if-no-files-found: ignore retention-days: 3 diff --git a/docs/P1_NATIVE_WIRE_GAIN_20261106.md b/docs/P1_NATIVE_WIRE_GAIN_20261106.md new file mode 100644 index 000000000..86e0a39e5 --- /dev/null +++ b/docs/P1_NATIVE_WIRE_GAIN_20261106.md @@ -0,0 +1,37 @@ +# Native WIRE gain and channel OUT + +Continues PR #418's real channel-to-channel PCM and source-only recovery. +The approved `/preview/` layout and single JUCE audio callback remain the +product owners. + +## Behavior + +- WIRE send gain and Sends on Faders target an accepted native EdgeId. + Drag updates coalesce while one intent waits for ACK and independent + accepted readback. No optimistic audio state is presented as accepted. +- Gain is a scalar update: graph/roster revisions and strip DOM stay stable. + The existing preallocated DSP gain slew spans 64 samples. No graph compile, + allocation or new callback is introduced by a gain edit. +- Primary OUT stays at unity; use channel/destination faders for its level. +- OUT choices include INPUT, GROUP and FX_RETURN, resolved by ChannelId. + Duplicate and reserved names get an identity suffix. OUT uses the same + exclusive ROUTE_ONLY transaction as WIRE, including cycle validation. +- Source-only/dormant sends remember accepted gain. A subsequent hardware + source preparation must restore that gain instead of reverting to unity. +- Device, graph or roster changes discard queued old-identity edits. + +## Verification + +`approved_native_routing_pcm_test.cpp` exercises public decoder/executor, +accepted session/publisher and actual rendered samples. It checks level, +64-sample smoothing, accepted readback, unchanged revisions, invalid/primary +edge rejection, dormant gain restoration and zero render allocations. + +`approved_native_m2_contract.test.cjs` covers latest-value coalescing, +ACK/readback proof, destination/tap identity and ambiguous OUT names. +`approved_native_wire_gain_smoke.py` uses real compiled native HTML and +Chromium keyboard input at 1366x768, 1680x900 and 1920x1080. Its backend is +emulated for UI isolation; it is not physical audio evidence. + +Physical ASIO/WASAPI, third-party VST3 listening and live stability remain +PENDING until measured on a real rig. No stable qualification is implied. diff --git a/engine/core/DynamicAcceptedSession.h b/engine/core/DynamicAcceptedSession.h index d3f3c6312..343852940 100644 --- a/engine/core/DynamicAcceptedSession.h +++ b/engine/core/DynamicAcceptedSession.h @@ -246,6 +246,15 @@ class DynamicAcceptedSession final { source,destination,preFader,linear); } + bool setLiveWireGain(std::uint64_t epoch,std::uint64_t revision, + ChannelId source,std::uint64_t edgeId,float gain) noexcept { + const auto* row=accepted_.find(source); + if(!row||!edgeId)return false; + for(const auto& edge:row->sends) + if(edge.edgeId==edgeId&&!edge.primaryOutput) + return setLiveParallelSend(epoch,revision,source,edge.destination,edge.preFader,gain); + return false; + } // This is a callback-ready DELEGATE, not an additional audio renderer. // M3D does not attach it to the production JUCE device until VST/Show // ownership and native output-port parity have been migrated. diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 066340210..72afa749c 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -235,10 +235,38 @@ class DynamicNativeSessionPublisher final { bool preFader,float gain) noexcept { return publisher_.updateActiveControl(epoch,revision, [&](Prepared& active) noexcept { - return active.graph.setParallelSendGain( - source,destination,preFader,gain); + if(!std::isfinite(gain)||gain<0.f||gain>4.f)return false; + const bool admitted=std::any_of(active.routing.edges.begin(),active.routing.edges.end(), + [&](const auto& edge){return edge.from==source&&edge.to==destination&& + edge.preFader==preFader&&!edge.primaryOutput;}); + if(!admitted)return false; + if(active.graph.channelScheduled(source)&&!active.graph.setParallelSendGain( + source,destination,preFader,gain))return false; + // A dormant send has no scratch/atomic DSP edge yet. Its + // accepted gain is still editable and seeds the next source + // preparation through the authoritative remembered roster. + // Routing readback is CONTROL-only; AUDIO reads only the + // graph's atomic gain target and preallocated 64-sample slew. + for(auto& edge:active.routing.edges) + if(edge.from==source&&edge.to==destination&& + edge.preFader==preFader&&!edge.primaryOutput) + edge.gainLinear=gain; + for(auto& row:active.routing.channels)if(row.id==source) + for(auto& edge:row.parallelSends) + if(edge.destination==destination&&edge.preFader==preFader) + edge.gain=gain; + return true; }); } + bool setWireGain(std::uint64_t epoch,std::uint64_t revision, + ChannelId source,std::uint64_t edgeId,float gain) noexcept { + const auto* routing=acceptedRouting(epoch,revision); + if(!routing||!edgeId)return false; + for(const auto& edge:routing->edges) + if(edge.edgeId==edgeId&&edge.from==source&&!edge.primaryOutput) + return setParallelSendGain(epoch,revision,source,edge.to,edge.preFader,gain); + return false; + } // CONTROL ONLY; never destroy the last live graph in a callback. void unpublish() noexcept {publisher_.unpublish();} diff --git a/engine/core/DynamicPreparedMixerBlock.h b/engine/core/DynamicPreparedMixerBlock.h index 842592147..8ff0fcf98 100644 --- a/engine/core/DynamicPreparedMixerBlock.h +++ b/engine/core/DynamicPreparedMixerBlock.h @@ -204,6 +204,12 @@ class DynamicPreparedMixerBlock final { bool contains(ChannelId id) const noexcept { return controlIndex_.find(id.value)!=controlIndex_.end(); } + // CONTROL only. Empty unpatched lanes deliberately have no PCM scratch. + bool channelScheduled(ChannelId id) const noexcept { + const auto found=controlIndex_.find(id.value); + return found!=controlIndex_.end()&& + std::find(renderOrder_.begin(),renderOrder_.end(),found->second)!=renderOrder_.end(); + } // Control thread only. Rejection leaves the previous prepared object // byte-for-byte usable; caller must publish with epoch/revision MUTE/ACK. diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index ee5e54ce4..88aacc2b2 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -108,6 +108,41 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( converted->setProperty("payload",juce::var(checked.release())); return {juce::var(converted.release()),{}}; } + if(op=="SET_WIRE_GAIN") { + if(!approvedHasOperation(caps.getProperty("supportedOps",{}),"SET_WIRE_GAIN")|| + !approvedHasOperation(installedBus.getProperty("supportedOps",{}),"NATIVE_SET_WIRE_GAIN")) + return reject("NATIVE_WIRE_GAIN_NOT_ADMITTED"); + const auto payload=publicIntent.getProperty("payload",{}); + const auto edgeId=payload.getProperty("edgeId",{}); + double gain=0.; + if(!nativeV8Decimal(edgeId)||!nativeV8Number(payload.getProperty("gainLinear",{}),gain)|| + gain<0.||gain>4.)return reject("INVALID_NATIVE_WIRE_GAIN"); + juce::var publicEdge,nativeEdge; + const auto pub=graph.getProperty("edges",{}),native=installedBus.getProperty("edges",{}); + if(!pub.isArray()||!native.isArray())return reject("WIRE_EDGE_INVENTORY_UNAVAILABLE"); + for(const auto& e:*pub.getArray()) + if(e.getProperty("edgeId",{})==edgeId&&e.getProperty("from",{})==ids)publicEdge=e; + for(const auto& e:*native.getArray()) + if(e.getProperty("edgeId",{})==edgeId&&e.getProperty("from",{})==ids)nativeEdge=e; + if(!publicEdge.isObject()||!nativeEdge.isObject())return reject("WIRE_STALE_EDGE"); + const auto primary=publicEdge.getProperty("primaryOutput",{}); + const auto nativePrimary=nativeEdge.getProperty("primaryOutput",{}); + if(!primary.isBool()||!nativePrimary.isBool()||static_cast(primary)|| + static_cast(nativePrimary))return reject("WIRE_PRIMARY_GAIN_FIXED"); + if(publicEdge.getProperty("enabled",{})!=juce::var(true)|| + publicEdge.getProperty("to",{})!=nativeEdge.getProperty("to",{})|| + publicEdge.getProperty("tap",{})!=nativeEdge.getProperty("tap",{})) + return reject("WIRE_EDGE_IDENTITY_MISMATCH"); + auto checked=std::make_unique(); + checked->setProperty("edgeId",edgeId);checked->setProperty("gainLinear",gain); + auto converted=std::make_unique(); + converted->setProperty("requestId",request);converted->setProperty("deviceEpoch",epoch); + converted->setProperty("baseGraphRevision",revision); + converted->setProperty("baseRosterRevision",roster);converted->setProperty("targetChannelId",ids); + converted->setProperty("operation","NATIVE_SET_WIRE_GAIN"); + converted->setProperty("payload",juce::var(checked.release())); + return {juce::var(converted.release()),{}}; + } // P1 WIRE: the previous GUI emitted APPLY_WIRE_TRANSACTION, but this // translator accepted only fader/pan/mute/solo and silently left native // BUS routing unavailable. Validate the exact accepted ChannelId/EdgeId @@ -411,6 +446,14 @@ inline bool executeApprovedNativeControl(Engine& engine, changed.error[0]==0; } else return false; } + if(operation=="NATIVE_SET_WIRE_GAIN") { + std::uint64_t edge=0;double gain=0.; + if(!approvedNativeId(payload.getProperty("edgeId",{}),edge)|| + !nativeV8Number(payload.getProperty("gainLinear",{}),gain)||gain<0.||gain>4.)return false; + if constexpr(requires(Engine& e){e.setNativeWireGain(epoch,revision,roster,channel,edge,0.f);}) + return engine.setNativeWireGain(epoch,revision,roster,channel,edge,static_cast(gain)); + return false; + } if(operation=="NATIVE_APPLY_WIRE_TRANSACTION") { const auto raw=payload.getProperty("changes",{}); const auto* edits=raw.getArray(); diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index c76a57b73..66700c618 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -282,6 +282,8 @@ inline bool projectInstalledNativeChannelIdGraph( // gesture as NOT_ADMITTED. Admit only the actual installed operation. if(has("NATIVE_APPLY_WIRE_TRANSACTION")) available.add(juce::String("APPLY_WIRE_TRANSACTION")); + if(has("NATIVE_SET_WIRE_GAIN")) + available.add(juce::String("SET_WIRE_GAIN")); if(has("NATIVE_SET_PROCESSING_FORMAT")) available.add(juce::String("SET_PROCESSING_FORMAT")); if(has("NATIVE_LOAD_INSERT")) diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index dcb691568..d4886e20d 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -169,6 +169,9 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, if(auto* caps=graph.getProperty("capabilities",{}).getDynamicObject()){ caps->setProperty("callbackOwnsChannelIds",true); juce::Array ops;ops.add("APPLY_WIRE_TRANSACTION"); + const auto actual=bus.getProperty("supportedOps",{}); + if(const auto* list=actual.getArray()) + if(list->contains(juce::var("NATIVE_SET_WIRE_GAIN")))ops.add("SET_WIRE_GAIN"); caps->setProperty("supportedOps",juce::var(ops)); } t->setProperty("channelMeterRmsPeak",juce::var(meters.release())); diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index c20c167bc..1a8d730f2 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -172,10 +172,22 @@ def accepted_pages_html() -> str: # Native WebView2 only: expose the original Pages IIFE model to the thin # bridge. No second renderer/state reducer, no change to public /preview/. ("restorePluginPreferences();init();\n})();", - "let verifiedM4WireSignature='',verifiedM4WireDirty=false;\n" + "let verifiedM4WireSignature='',verifiedM4WireDirty=false,nativeWireGainDirty=false;\n" "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" + " syncNativeWireGains(rows){\n" + " for(const row of rows){\n" + " const edge=wireEdges.find(e=>e.id===row.id&&e.kind!=='primary');\n" + " if(edge&&Number.isFinite(row.levelDb)&&edge.levelDb!==row.levelDb){\n" + " edge.levelDb=row.levelDb;nativeWireGainDirty=true;\n" + " }\n" + " }\n" + " if(nativeWireGainDirty&&!wireGesture&&!faderGesture&&\n" + " !document.activeElement?.matches?.('.wire-gain,#wireWsGain')){\n" + " nativeWireGainDirty=false;refreshWireRoutingNodes();\n" + " }\n" + " },\n" " syncVerifiedM4Wires(rows,ids){\n" " if(!Array.isArray(rows)||rows.length!==10||!Array.isArray(ids)||ids.length!==10)\n" " return false;\n" diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index 18c8b7a76..abe496c4b 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -160,6 +160,9 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { if(auto* caps=graph.getProperty("capabilities",{}).getDynamicObject()){ caps->setProperty("callbackOwnsChannelIds",true); juce::Array ops;ops.add("APPLY_WIRE_TRANSACTION"); + const auto actual=bus.getProperty("supportedOps",{}); + if(const auto* list=actual.getArray()) + if(list->contains(juce::var("NATIVE_SET_WIRE_GAIN")))ops.add("SET_WIRE_GAIN"); caps->setProperty("supportedOps",juce::var(ops)); } t->setProperty("channelMeterRmsPeak",juce::var(meters.release())); diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 79d4d18b0..b3f2c89e2 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1646,6 +1646,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.applyNativeWireTransaction( ep,pcmRev,rosterRev,changes); } + bool setNativeWireGain(std::uint64_t epoch,std::uint64_t rev, + std::uint64_t roster,armix::mixer::ChannelId source, + std::uint64_t edge,float gain) noexcept { + if(independent_.active()||!attached_||!directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return false; + return dryRoutingLab_.setNativeWireGain(epoch,rev,roster,source,edge,gain); + } bool setNativeInputMix(std::uint64_t epoch,std::uint64_t rev, armix::mixer::ChannelId id,float gain,float pan) noexcept { if(independent_.active()||!directFence_.permitted()|| diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 235a933ba..c27ba7b8e 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -1925,6 +1925,27 @@ class LiveDryRoutingLab final { return true; } + // EdgeId-keyed live SEND level: no graph compile, VST recreation or + // callback handoff. Primary outputs retain their unity-gain contract. + bool setNativeWireGain(std::uint64_t ep,std::uint64_t graphRev, + std::uint64_t rosterRev,armix::mixer::ChannelId source, + std::uint64_t edgeId,float gain) noexcept { + if(!channelIdPhysicalPcmActive()||!ready()||ep!=epoch()|| + graphRev!=nativeAccepted_.pcmRevision|| + rosterRev!=nativeAccepted_.graph.roster.revision()|| + !std::isfinite(gain)||gain<0.f||gain>4.f)return false; + const auto* row=nativeAccepted_.graph.roster.find(source); + if(!row||!edgeId)return false; + for(const auto& edge:row->sends) + if(edge.edgeId==edgeId&&!edge.primaryOutput) { + if(!nativePublisher_.setWireGain(ep,graphRev,source,edgeId,gain))return false; + if(!nativeAccepted_.graph.roster.rememberLiveParallelSend( + source,edge.destination,edge.preFader,gain))return false; + nativeControlDirty_=true; + return true; + } + return false; + } // CONTROL snapshot: genuine stable ChannelIds from the SAME publisher // as physical PCM. No guessed IDs, synthetic UI routes or JS DSP. juce::var nativeBusStatus() const { @@ -1947,6 +1968,7 @@ class LiveDryRoutingLab final { "NATIVE_CREATE_CHANNEL","NATIVE_PATCH_CHANNEL", "NATIVE_SET_PRIMARY_OUT", "NATIVE_APPLY_WIRE_TRANSACTION", + "NATIVE_SET_WIRE_GAIN", "NATIVE_SET_PROCESSING_FORMAT", "NATIVE_SET_CHANNEL_MIX", "NATIVE_SET_CHANNEL_MUTE_SOLO", diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index c4ad0cec7..ceca46185 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -465,13 +465,14 @@ test("P0 WIRE-to-MAIN and channel OUT use one acknowledged native transaction",( assert.match(bridge,/function requestPrimaryOut\(t,target\)/); assert.match(bridge,/session\?\.authority==="CHANNEL_ID"/); assert.match(bridge,/controller\.intent\("APPLY_WIRE_TRANSACTION",channelId,/); - assert.match(bridge,/const to=target==="MAIN"\?main:group\?\.id\|\|null/); + assert.match(bridge,/const to=target==="MAIN"\?main:destination\?\.id\|\|null/); assert.match(bridge,/change=\{op:"ROUTE_ONLY",from:channelId,to,/); assert.match(bridge,/change=\{op:"REMOVE",from:channelId,edgeId:edge\.edgeId\}/); // Only the accepted PRIMARY edge may be detached. A parallel SEND to // MAIN must not be misclassified as a physical OUT. assert.match(bridge,/e\.primaryOutput===true/); - assert.doesNotMatch(bridge,/e\.primaryOutput!==false/); + const primaryOutPath=bridge.slice(bridge.indexOf("function requestPrimaryOut"),bridge.indexOf("const pendingNativeSources")); + assert.doesNotMatch(primaryOutPath,/e\.primaryOutput!==false/); const roster=read("engine/core/DynamicChannelRoster.h"); const translator=read("integration/ApprovedNativeControlIntent.h"); assert.match(roster,/target->primaryOutput=true/); @@ -865,10 +866,12 @@ test("M2 code edits approved Pages *events* only, not a second native GUI/audio }); test("M3 native-only Pages scope performs real bridge projection, fader intent and ACK readback",()=>{ - const vm=require("node:vm"),sent=[],listeners=new Map(); + const vm=require("node:vm"),sent=[],listeners=new Map(),timers=[]; let nextId=100,nextEdgeId=200,paints=0,rollbacks=0; const scope={ tracks:[],master:{id:1,name:"Master"},colors:["#568ead"], + get wireEdges(){return this.edges||[];}, + syncNativeWireGains(rows){for(const r of rows){const e=this.edges?.find(e=>e.id===r.id);if(e)e.levelDb=r.levelDb;}}, wireGraph:{validateCandidateGraph:()=>({ok:true})}, make:(name,kind,color)=>({id:nextId++,name,kind,color,selected:false}), render(){paints++;}, @@ -892,7 +895,7 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a }; const window={ __JUCE__:{backend:native},ArSonApprovedNativeContract:protocol, - __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){},setTimeout(){return 0;} + __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){},setTimeout(fn,ms){timers.push({fn,ms});return timers.length;} }; vm.runInNewContext(read("web/approved-native-bridge.js"),{ window,document,performance:{now:()=>0},console @@ -991,6 +994,71 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a assert.equal(scope.edges.length,1); assert.equal(scope.edges[0].destId,receiverUi); assert.equal(window.__ARMIX_NATIVE_M2__.state().pending,null); + // Continuous send gain coalesces the latest gesture while the native ACK + // is outstanding. Gain-only accepted readback must preserve strip DOM. + routed.graph.capabilities.supportedOps.push("SET_WIRE_GAIN"); + listeners.get("arMixConsoleSnapshot")(routed); + const gainUi=scope.edges[0].id,paintBeforeGain=paints; + const pump=()=>{const ready=timers.splice(0);for(const t of ready)if(t.ms===32)t.fn();}; + window.__ARMIX_NATIVE_M2__.consumeWire([{type:"GAIN",sourceId:sourceUi,edgeId:gainUi,levelDb:-6}]); + pump(); + const firstGain=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(firstGain.operation,"SET_WIRE_GAIN"); + assert.equal(firstGain.payload.edgeId,"9223372036854775810"); + assert.equal(scope.edges[0].levelDb,0,"no optimistic send gain acceptance"); + window.__ARMIX_NATIVE_M2__.consumeWire([{type:"GAIN",sourceId:sourceUi,edgeId:gainUi,levelDb:-9}]); + window.__ARMIX_NATIVE_M2__.consumeWire([{type:"GAIN",sourceId:sourceUi,edgeId:gainUi,levelDb:-12}]); + pump(); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.requestId,firstGain.requestId); + const ackGain=request=>listeners.get("arMixConsoleAck")({requestId:request.requestId,status:"ACCEPTED", + errorCode:"NONE",deviceEpoch:routed.device.epoch,graphRevision:"8",rosterRevision:"8"}); + ackGain(firstGain); + assert.equal(scope.edges[0].levelDb,0,"ACK alone is not PCM gain readback"); + const gained=clone(routed);gained.graph.edges[0].gainLinear=firstGain.payload.gainLinear; + listeners.get("arMixConsoleSnapshot")(gained); + assert.equal(scope.edges[0].levelDb,-6); + assert.equal(paints,paintBeforeGain,"scalar WIRE gain cannot rebuild mounted strips"); + pump(); + const latestGain=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.notEqual(latestGain.requestId,firstGain.requestId); + assert.ok(Math.abs(latestGain.payload.gainLinear-Math.pow(10,-12/20))<1e-9); + ackGain(latestGain);gained.graph.edges[0].gainLinear=latestGain.payload.gainLinear; + listeners.get("arMixConsoleSnapshot")(gained); + assert.equal(scope.edges[0].levelDb,-12); + assert.equal(paints,paintBeforeGain); + // OUT uses the same actual INPUT destination as WIRE, not a name-only + // GROUP lookup. An exclusive route promotes the existing native edge. + const hooks=window.__ARMIX_NATIVE_M2__,sourceTrack=scope.tracks[0]; + assert.ok(hooks.outputChoices(sourceTrack).includes("CH04")); + const output={dataset:{field:"output"},value:"CH04",closest:()=>null}; + hooks.consumeField({target:output,type:"change"}); + const outRequest=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.equal(outRequest.operation,"APPLY_WIRE_TRANSACTION"); + assert.equal(outRequest.payload.changes[0].op,"ROUTE_ONLY"); + assert.equal(outRequest.payload.changes[0].to,receiver.id); + listeners.get("arMixConsoleAck")({requestId:outRequest.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:gained.device.epoch,graphRevision:"9",rosterRevision:"9"}); + const primary=clone(gained);primary.graph.revision="9";primary.graph.rosterRevision="9"; + primary.graph.channels[0].primaryOutId=receiver.id; + primary.graph.edges[0].primaryOutput=true;primary.graph.edges[0].gainLinear=1; + listeners.get("arMixConsoleSnapshot")(primary); + assert.equal(scope.tracks[0].output,"CH04"); + const duplicate=clone(primary),other=clone(receiver); + other.id="9007199254740997";duplicate.graph.channels.splice(2,0,other); + const reserved=clone(receiver);reserved.id="9007199254740999";reserved.name="NONE"; + duplicate.graph.channels.splice(3,0,reserved); + duplicate.graph.revision="10";duplicate.graph.rosterRevision="10"; + listeners.get("arMixConsoleSnapshot")(duplicate); + const choices=hooks.outputChoices(scope.tracks[0]); + assert.ok(choices.includes("CH04 ["+receiver.id+"]")); + assert.ok(choices.includes("CH04 ["+other.id+"]")); + assert.ok(!choices.includes("CH04"),"duplicate names cannot address the wrong native channel"); + assert.ok(!choices.includes("NONE"),"a channel name cannot alias SOURCE ONLY"); + assert.ok(choices.includes("NONE ["+reserved.id+"]")); + output.value="CH04";hooks.consumeField({target:output,type:"change"}); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.requestId,outRequest.requestId); + output.value="CH04 ["+other.id+"]";hooks.consumeField({target:output,type:"change"}); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.payload.changes[0].to,other.id); }); test("P0 native FX rack and per-slot readback update mounted strip without replacing fader DOM",()=>{ @@ -1303,3 +1371,30 @@ test("native Windows operator can explicitly patch first physical input, arm and // Held-pointer native fader regression runs within existing Windows / Chromium test gates. require("./live_fader_held_drag.test.cjs"); + +test("live WIRE gain requires exact same-revision sample-target readback and unchanged edge identity",()=>{ + const base=acceptedFixture();delete base.graph.channels[0].primaryOutId; + base.graph.edges[0].primaryOutput=false;base.graph.edges[0].tap="POST_FADER"; + base.graph.capabilities.supportedOps.push("SET_WIRE_GAIN"); + const source=base.graph.channels[0].id,edge=base.graph.edges[0].edgeId; + const create=()=>{const sent=[];const c=protocol.createController({emit:(name,payload)=>sent.push({name,payload})}); + c.onSnapshot(clone(base));return {c,sent};}; + const accept=(c,r)=>c.onAck({requestId:r.requestId,status:"ACCEPTED",errorCode:"NONE", + deviceEpoch:base.device.epoch,graphRevision:base.graph.revision,rosterRevision:base.graph.rosterRevision}); + for(const corrupt of [s=>{s.graph.edges[0].gainLinear=.5;},s=>{s.graph.edges[0].tap="PRE_FADER";}, + s=>{s.graph.edges[0].primaryOutput=true;}]){ + const {c}=create();const r=c.intent("SET_WIRE_GAIN",source,{edgeId:edge,gainLinear:.25}); + assert.ok(r.ok);accept(c,r); + const bad=clone(base);bad.graph.edges[0].gainLinear=.25;corrupt(bad); + assert.equal(c.onSnapshot(bad),false); + assert.equal(c.state().lastError,"ACK_READBACK_EFFECT_MISMATCH"); + assert.equal(c.state().current.graph.edges[0].gainLinear,1); + } + const {c}=create();const r=c.intent("SET_WIRE_GAIN",source,{edgeId:edge,gainLinear:.25}); + accept(c,r);assert.equal(c.state().current.graph.edges[0].gainLinear,1); + const good=clone(base);good.graph.edges[0].gainLinear=.25; + assert.ok(c.onSnapshot(good));assert.equal(c.state().pending,null); + assert.equal(c.state().current.graph.revision,base.graph.revision); + assert.equal(c.state().current.graph.edges[0].gainLinear,.25); + assert.equal(c.intent("SET_WIRE_GAIN",source,{edgeId:"99999",gainLinear:.5}).ok,false); +}); diff --git a/tests/approved_native_routing_pcm_test.cpp b/tests/approved_native_routing_pcm_test.cpp index 518e25c12..c68b5f2cf 100644 --- a/tests/approved_native_routing_pcm_test.cpp +++ b/tests/approved_native_routing_pcm_test.cpp @@ -86,6 +86,11 @@ struct PcmHost { last=pcm.wireTransaction(roster,rev,edits,io,ep,epoch,false); return {last.ok(),last.ok()?"":"PCM_REJECTED"}; } + bool setNativeWireGain(std::uint64_t ep,std::uint64_t rev,std::uint64_t roster, + ChannelId source,std::uint64_t edgeId,float gain) { + return roster==pcm.acceptedRosterRevision()&& + pcm.setLiveWireGain(ep,rev,source,edgeId,gain); + } bool setNativeInputMix(std::uint64_t ep,std::uint64_t rev, ChannelId id,float gain,float pan) { return pcm.setLiveMix(ep,rev,id,gain,pan); @@ -108,6 +113,7 @@ struct PcmHost { put(result,"rosterRevision",textId(pcm.acceptedRosterRevision())); juce::Array rows,edges,ops; ops.add("NATIVE_APPLY_WIRE_TRANSACTION"); + ops.add("NATIVE_SET_WIRE_GAIN"); for(std::size_t i=0;ichannels.size();++i) { const auto& ch=view->channels[i]; const auto* def=pcm.acceptedRoster().find(ch.id);assert(def); @@ -153,6 +159,22 @@ struct PcmHost { const bool result=executeApprovedNativeControl(*this,decoded.translated,&lastError); pcm.pollRetirement();return result; } + juce::var gainRequest(ChannelId source,std::uint64_t edge,float gain) { + auto edit=object();put(edit,"from",textId(source.value)); + auto r=request(edit);put(r,"operation","SET_WIRE_GAIN"); + auto payload=object();put(payload,"edgeId",textId(edge));put(payload,"gainLinear",gain); + put(r,"payload",payload);return r; + } + std::uint64_t sendEdge(ChannelId source,ChannelId destination) const { + for(const auto& edge:pcm.acceptedRoster().find(source)->sends) + if(edge.destination==destination)return edge.edgeId; + assert(false);return 0; + } + bool gain(ChannelId source,std::uint64_t edge,float value) { + const auto native=readback(); + const auto decoded=translateApprovedNativeControl(gainRequest(source,edge,value),snapshot(native),native); + assert(decoded.ok());return executeApprovedNativeControl(*this,decoded.translated); + } void render() { const float* pins[]{a.data(),b.data(),mic.data()};calls.fill(0); const auto fx=[&](ChannelId id,float* l,float* r,int n) noexcept { @@ -190,6 +212,25 @@ int main() { assert(h.apply(link("CONNECT",ch3,ch4))); h.render();assert(near(h.peaksL[3],.0625f)); assert(near(h.left[63],.3125f+mono)); // deliberate parallel path + const auto send=h.sendEdge(ch3,ch4),sameGraph=h.pcm.acceptedGraphRevision(), + sameRoster=h.pcm.acceptedRosterRevision(); + assert(h.gain(ch3,send,.5f)); + h.render();assert(h.left[0]>h.left[63]); // actual 64-sample gain slew + h.render();assert(near(h.peaksL[3],.03125f)&&near(h.left[63],.28125f+mono)); + assert(h.pcm.acceptedGraphRevision()==sameGraph&&h.pcm.acceptedRosterRevision()==sameRoster); + const auto* gainView=h.pcm.acceptedRouting(h.epoch,sameGraph); + assert(near(gainView->find(ch3)->parallelSends[0].gain,.5f)); + assert(near(h.pcm.acceptedRoster().find(ch3)->sends.back().gain,.5f)); + const auto gainNative=h.readback(),gainPublic=h.snapshot(gainNative); + assert(translateApprovedNativeControl(h.gainRequest(ch3,h.sendEdge(ch3,h.main),.5f), + gainPublic,gainNative).error=="WIRE_PRIMARY_GAIN_FIXED"); + assert(translateApprovedNativeControl(h.gainRequest(ch4,send,.5f), + gainPublic,gainNative).error=="WIRE_STALE_EDGE"); + assert(translateApprovedNativeControl(h.gainRequest(ch3,send,5.f), + gainPublic,gainNative).error=="INVALID_NATIVE_WIRE_GAIN"); + assert(!h.setNativeWireGain(h.epoch+1,sameGraph,sameRoster,ch3,send,.5f)); + assert(!h.setNativeWireGain(h.epoch,sameGraph,sameRoster-1,ch3,send,.5f)); + assert(h.gain(ch3,send,1.f));h.render();h.render(); auto rb=h.readback();auto s=h.snapshot(rb); assert(s.getProperty("graph",{}).getProperty("destinations",{}).size()==12); assert(near(static_cast(s.getProperty("telemetry",{}) @@ -272,4 +313,17 @@ int main() { assert(h.left[63]==0.f&&h.right[63]==0.f); PcmHost reconnected;reconnected.render(); assert(near(reconnected.left[63],.25f+mono)); + // Configure a dormant send BEFORE assigning its hardware IN. The + // remembered live level must seed its later real PCM preparation. + PcmHost dormant;const auto empty=dormant.channels[7],receiver=dormant.channels[3]; + assert(dormant.apply(link("CONNECT",empty,receiver))); + const auto dormantEdge=dormant.sendEdge(empty,receiver); + assert(dormant.gain(empty,dormantEdge,.25f));dormant.render(); + assert(dormant.peaksL[7]==0.f&&near(dormant.left[63],.25f+mono)); + dormant.io.sources.push_back({empty,0,1,true}); + width.id=empty; + assert(dormant.pcm.edit(dormant.pcm.acceptedRosterRevision(),dormant.pcm.acceptedGraphRevision(), + std::span(&width,1),dormant.io,dormant.epoch,dormant.epoch,true).ok()); + dormant.render();assert(near(dormant.peaksL[3],.015625f)); + assert(near(dormant.left[63],.265625f+mono)); } diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py new file mode 100644 index 000000000..221aa544f --- /dev/null +++ b/tests/approved_native_wire_gain_smoke.py @@ -0,0 +1,129 @@ +"""Actual compiled native DOM/keyboard -> intent -> ACK -> accepted readback. + +The WebView backend is emulated for UI isolation. Native PCM/sample/ramp +evidence comes from P0ApprovedDecoderChannelToChannelAndSourceOnlyPCM CTest. +""" +import copy +import importlib.util +import json +from pathlib import Path +import tempfile +from playwright.sync_api import sync_playwright + +ROOT = Path(__file__).resolve().parents[1] +SOURCE, RECEIVER, MAIN = "9007199254740993", "9007199254740995", "18446744073709551615" +SEND = "9223372036854775810" + + +def snapshot(): + s = json.loads((ROOT / "integration/console-v6/fixtures.json").read_text())["g0"] + g = s["graph"] + g.update(revision="2", rosterRevision="2", mainChannelId=MAIN) + g["capabilities"].update(callbackOwnsChannelIds=True, + supportedOps=["SET_WIRE_GAIN", "APPLY_WIRE_TRANSACTION"]) + g["channels"] = [ + {"id": ident, "name": name, "role": role, "processingFormat": "STEREO", + "controls": {"faderDb": 0, "pan": 0, "mute": False, "solo": False}, + "inserts": [], "sends": []} + for ident, name, role in [(SOURCE, "CH03", "INPUT"), + (RECEIVER, "CH04", "INPUT"), (MAIN, "MAIN", "MAIN")]] + for ch in g["channels"][:2]: + ch["primaryOutId"] = MAIN + g["edges"] = [ + {"edgeId": "9223372036854775808", "from": SOURCE, "to": MAIN, "primaryOutput": True, "gainLinear": 1}, + {"edgeId": SEND, "from": SOURCE, "to": RECEIVER, "primaryOutput": False, "gainLinear": .5}, + {"edgeId": "9223372036854775812", "from": RECEIVER, "to": MAIN, "primaryOutput": True, "gainLinear": 1}] + for edge in g["edges"]: + edge.update(tap="POST_FADER", enabled=True, signalKind="AUDIO") + g["destinations"] = [{k: ch[k] for k in ("id", "role", "name")} for ch in g["channels"]] + s["mixerSession"] = {"authority": "CHANNEL_ID", "deviceEpoch": s["device"]["epoch"], + "routeRevision": "2", "rosterRevision": "2", "channels": copy.deepcopy(g["channels"]), + "main": {"db": 0, "mute": False}} + return s + + +def emit(page, name, payload): + page.evaluate("([name,payload])=>window.__nativeListeners.get(name)?.(payload)", [name, payload]) + + +def ack(page, state, intent): + emit(page, "arMixConsoleAck", {"requestId": intent["requestId"], "status": "ACCEPTED", + "errorCode": "NONE", "deviceEpoch": state["device"]["epoch"], + "graphRevision": state["graph"]["revision"], "rosterRevision": state["graph"]["rosterRevision"]}) + + +def main(): + spec = importlib.util.spec_from_file_location("native_bundle", ROOT / "scripts/build_approved_native_gui.py") + bundle = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory(prefix="arsonmix-native-send-") as directory: + out = Path(directory) + bundle.stage(out) + with sync_playwright() as p: + browser = p.chromium.launch(headless=True) + for width, height in [(1366, 768), (1680, 900), (1920, 1080)]: + page = browser.new_page(viewport={"width": width, "height": height}) + errors = [] + page.on("pageerror", lambda error: errors.append(str(error))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out / "index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled") + state = snapshot() + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_selector('#tracks .strip[data-id="2"]') + if "collapsed-send" in (page.locator(".console-body").get_attribute("class") or ""): + page.locator('.section-rail [data-section="send"]').click() + page.locator('#tracks .strip[data-id="1"] .wire-node-out').click() + knob = page.locator('#tracks .strip[data-id="2"] .wire-gain') + knob.wait_for(state="visible") + page.evaluate("""()=>{window.__heldWireInput=document.querySelector('#tracks .strip[data-id="2"] .wire-gain'); + window.__heldStrip=document.querySelector('#tracks .strip[data-id="2"]');}""") + knob.focus() + knob.press("End") + page.wait_for_function("()=>window.__nativeIntents.filter(x=>x.operation==='SET_WIRE_GAIN').length===1") + first = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert first["payload"]["edgeId"] == SEND + knob.press("Home") + page.wait_for_timeout(70) + assert page.evaluate("()=>window.__nativeIntents.length") == 1, "must coalesce behind ACK" + state["graph"]["edges"][1]["gainLinear"] = first["payload"]["gainLinear"] + ack(page, state, first) + emit(page, "arMixConsoleSnapshot", state) + page.wait_for_function("()=>window.__nativeIntents.length===2") + assert page.evaluate("()=>window.__heldWireInput===document.querySelector('#tracks .strip[data-id=\"2\"] .wire-gain')"), "ACK detached held gain control" + latest = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert abs(latest["payload"]["gainLinear"] - .001) < 1e-8 + state["graph"]["edges"][1]["gainLinear"] = latest["payload"]["gainLinear"] + ack(page, state, latest) + emit(page, "arMixConsoleSnapshot", state) + knob.press("Tab") + emit(page, "arMixConsoleSnapshot", state) + assert page.evaluate("()=>window.__heldStrip===document.querySelector('#tracks .strip[data-id=\"2\"]')"), "scalar edit rebuilt strip" + assert float(page.locator('#tracks .strip[data-id="2"] .wire-gain').input_value()) == -60 + # OUT to the same INPUT is the existing exclusive native transaction. + page.locator('#tracks .strip[data-id="1"] select[data-field="output"]').select_option(label="CH04") + route = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert route["operation"] == "APPLY_WIRE_TRANSACTION" + assert route["payload"]["changes"][0]["to"] == RECEIVER + assert route["payload"]["changes"][0]["op"] == "ROUTE_ONLY" + state["graph"].update(revision="3", rosterRevision="3") + state["graph"]["channels"][0]["primaryOutId"] = RECEIVER + state["graph"]["edges"].pop(0) + state["graph"]["edges"][0].update(primaryOutput=True, gainLinear=1) + state["mixerSession"].update(routeRevision="3", rosterRevision="3", + channels=copy.deepcopy(state["graph"]["channels"])) + ack(page, state, route) + emit(page, "arMixConsoleSnapshot", state) + assert page.locator('#tracks .strip[data-id="2"] .wire-gain').is_disabled(), "primary OUT gain must stay unity" + assert not errors, errors + page.screenshot(path=f"native-wire-gain-{width}.png") + page.close() + browser.close() + print("PASS native WIRE gain: real keyboard, coalesced ACK/readback, stable DOM, INPUT OUT, 3 viewports (UI only)") + + +if __name__ == "__main__": + main() diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 6bf820088..15f04e4fb 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -16,6 +16,8 @@ const uiByNativeId = new Map(); // EXACT uint64 string -> local view-only ordinal const wireByUiId = new Map(); // view-only EdgeId -> EXACT decimal-string native EdgeId const uiByWireId = new Map(); + const pendingWireGains=new Map(); + let wireGainFlushQueued=false; let lastPaintedSignature = "",lastNativeTopologySignature = "", lastNativeError = "NATIVE_NOT_SUBSCRIBED"; // B-stage: attached-node-only meter caches; a structural render invalidates @@ -45,6 +47,43 @@ document.documentElement.dataset.armixNativeAuthority = authority; }; const nativeIdFor = t => nativeByUiId.get(t?.id) || null; + function queueWireGainFlush(){ + if(wireGainFlushQueued)return; + wireGainFlushQueued=true; + window.setTimeout(()=>{wireGainFlushQueued=false;flushWireGains();},32); + } + function flushWireGains(){ + const state=controller?.state(),current=state?.current; + if(state?.pending||!current?.admitted)return; + for(const [edgeId,edit] of pendingWireGains){ + pendingWireGains.delete(edgeId); + if(current.identity!==edit.identity)continue; // never replay into a new graph/device + const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===edgeId&&e.from===edit.source); + if(!edge||edge.primaryOutput!==false)continue; + if(Math.abs(edge.gainLinear-edit.gain)<.00001)continue; + const result=controller.intent("SET_WIRE_GAIN",edit.source,{edgeId,gainLinear:edit.gain}); + if(result.ok)window.setTimeout(()=>controller?.expire(result.requestId),8000); + else status("WIRE gain rejected · "+result.error); + return; // next coalesced target follows ACK + independent readback + } + } + function requestWireGain(op){ + const current=controller?.state()?.current; + const edgeId=wireByUiId.get(op.edgeId),source=nativeByUiId.get(op.sourceId); + const db=Number(op.levelDb); + if(!current?.admitted||!current.graph.capabilities.supportedOps.includes("SET_WIRE_GAIN")|| + !Number.isFinite(db)||db< -60||db>6)return false; + const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===edgeId&&e.from===source); + if(!edge||edge.primaryOutput!==false)return false; + pendingWireGains.set(edgeId,{source,gain:Math.pow(10,db/20),identity:current.identity}); + queueWireGainFlush();return true; + } + function nativeOutputTargets(t,channels=controller?.state()?.current?.graph?.channels||[]){ + const source=nativeIdFor(t),reserved=["Master","SOURCE ONLY (No Main)","MAIN","NONE"]; + return channels.filter(ch=>ch.id!==source&&["INPUT","GROUP","FX_RETURN"].includes(ch.role)) + .map(ch=>({id:ch.id,label:reserved.includes(ch.name)|| + channels.filter(other=>other.name===ch.name).length>1?ch.name+" ["+ch.id+"]":ch.name})); + } const intent = (operation,t,payload) => { if (!flags.acceptedGraphConnected) { status("NATIVE: accepted graph not projected; control unchanged"); @@ -95,10 +134,12 @@ r=/^in:(\d+)$/.exec(src.portIdRight||""); t.input=l?inputLabelFor({mode:src.sourceFormat==="STEREO"?"STEREO":"MONO", left:Number(l[1]),right:r?Number(r[1]):-1}):"None"; - const out=accepted.channels.find(dest=>dest.id===ch.primaryOutId); - t.output=out?.role==="MAIN"?"Master": - (out?.name||"SOURCE ONLY (No Main)"); } + const out=accepted.channels.find(dest=>dest.id===ch.primaryOutId); + // Identity-safe labels also handle duplicate names and reserved labels. + const target=out&&nativeOutputTargets(t,accepted.channels).find(x=>x.id===out.id); + if(ch.role!=="MAIN")t.output=out?.role==="MAIN"?"Master": + (target?.label||"SOURCE ONLY (No Main)"); t.selected=previous.get(t.id)?.selected || false; if(typeof ch.fxRackBypassed==="boolean")t.fxOn=!ch.fxRackBypassed; if (Array.isArray(ch.inserts)) { @@ -208,12 +249,15 @@ next.graph.channels.map(ch=>[ch.id,ch.role,ch.name, ch.processingFormat,ch.source,ch.primaryOutId, ch.inserts?.map(fx=>[fx.id,fx.catalogId,fx.name])]), - next.graph.edges]); + next.graph.edges.map(e=>[e.edgeId,e.from,e.to,e.tap,e.enabled,e.primaryOutput])]); if(structure!==lastNativeTopologySignature){ if(!projection(next))return false; lastNativeTopologySignature=structure; return true; } + scope?.syncNativeWireGains?.(next.graph.edges.filter(e=>e.enabled&&e.primaryOutput===false) + .map(e=>({id:uiByWireId.get(e.edgeId),levelDb:Math.round(Math.max(-60,Math.min(6, + e.gainLinear>0?20*Math.log10(e.gainLinear):-60))*10)/10}))); // Immutable graph topology is identical: update actual scalar controls // only. Never detach the active HTML select or the captured fader pointer. for(const ch of next.graph.channels){ @@ -253,6 +297,16 @@ // Native telemetry owns the physical meter. When no measured per-channel // samples are published, leave the meter dark; never use Pages sine demo. function paintNativeMeters(next) { + for(const edge of next.graph.edges||[]){ + const ui=uiByWireId.get(edge.edgeId); + if(ui===undefined)continue; + for(const input of document.querySelectorAll?.('.wire-gain[data-wire-id="'+ui+'"]')||[]){ + const fixed=edge.primaryOutput===true; + if(input.disabled!==fixed)input.disabled=fixed; + const title="Primary OUT is unity gain · use the destination fader"; + if(fixed&&input.title!==title)input.title=title; + } + } if (!scope?.displayMeterDbfs)return; const data=next.telemetry?.channelMeterRmsPeak; if (!data || typeof data!=="object")return; @@ -434,9 +488,8 @@ !current.graph.capabilities.supportedOps.includes("APPLY_WIRE_TRANSACTION") || !["INPUT","GROUP","FX_RETURN"].includes(ch.role) || !target)return false; - const group=current.graph.channels.find(row=> - row.role==="GROUP"&&row.name===target); - const to=target==="MAIN"?main:group?.id||null; + const destination=nativeOutputTargets(t).find(row=>row.label===target); + const to=target==="MAIN"?main:destination?.id||null; if(target!=="NONE"&&!to)return false; const dest=ch.primaryOutId||null; if((to&&dest===to)||(target==="NONE"&&!dest)){ @@ -1509,6 +1562,7 @@ },8000); } function onNativeReadback(next) { + scope?.syncNativeWireGains?.([]); // flush accepted paint after pointer release updateHardwarePanel(next); // The installed native SessionSnapshot selects exactly one UI authority. const session=next?.raw?.mixerSession; @@ -1609,6 +1663,8 @@ status("NATIVE "+state.lastError+" · awaiting authoritative readback"); if(!state.pending && state.lastError==="ACCEPTED_READBACK" && pendingNativeControl.size)queueLiveControlFlush(); + if(!state.pending&&state.lastError==="ACCEPTED_READBACK"&&pendingWireGains.size) + queueWireGainFlush(); // Rejection cleanup and native rollback must BOTH run. // Former else-if was unreachable after the cleanup branch matched. const failed=!state.pending && @@ -1616,6 +1672,7 @@ state.lastError!=="NONE" && state.lastError!=="NATIVE_NOT_SUBSCRIBED"; if(failed){ + pendingWireGains.clear(); if(pendingFxInsert?.authority==="CHANNEL_ID"){ pendingFxInsert=null; nativeToast("VST3 insert rejected · "+state.lastError); @@ -1874,15 +1931,13 @@ outputChoices(t) { if(t?.kind==="master") return [String(hardware?.device?.playbackDevice||t.output||"Choose audio output")]; - if(t?.kind==="audio"){ + if(t?.kind!=="master"){ // M4 accepts MAIN or source-only. Bus routing is via native WIRE, // never pretend the demo's other destinations have native PCM. const options=["Master","SOURCE ONLY (No Main)"]; const graph=controller?.state()?.current?.graph; if(mixerSession()?.authority==="CHANNEL_ID"&&graph?.channels) - for(const bus of graph.channels) - if(bus.role==="GROUP"&&bus.name && - !options.includes(bus.name))options.push(bus.name); + for(const target of nativeOutputTargets(t))options.push(target.label); if(t.output&&!options.includes(t.output))options.push(t.output); return options; } @@ -1894,6 +1949,12 @@ if (!field)return false; const t=scope?.findTrack?.(el) || null; if (!t)return true; + if(field==="wireGain"){ + const edge=scope?.wireEdges?.find(e=>e.id===Number(el.dataset.wireId)&&e.destId===t.id); + if(!edge||!requestWireGain({sourceId:edge.sourceId,edgeId:edge.id,levelDb:Number(el.value)})) + status("WIRE gain unavailable · accepted parallel send required"); + return true; + } if(field==="input"){ // Input selection is independent of Record Arm, transport START and // ChannelId admission. A physical mixer strip can receive ANY active @@ -1942,11 +2003,10 @@ el.value=t.output;openNativeAudioIO();return true; } const graph=controller?.state()?.current?.graph; - const bus=graph?.channels?.find(ch=> - ch.role==="GROUP"&&ch.name===el.value); + const destination=nativeOutputTargets(t).find(ch=>ch.label===el.value); const target=el.value==="Master"?"MAIN": el.value==="SOURCE ONLY (No Main)"?"NONE": - bus?bus.name:null; + destination?destination.label:null; // No optimistic GUI state. Both this menu and the WIRE jack use // the same ID/epoch-guarded, acknowledged native route transaction. if(el.value!==t.output && !requestPrimaryOut(t,target)){ @@ -2083,6 +2143,16 @@ }, consumeWire(ops) { if (!connected)return false; + if(Array.isArray(ops)&&ops.length===1&&ops[0].type==="GAIN"){ + if(!requestWireGain(ops[0]))status("WIRE gain unavailable · accepted parallel send required"); + return true; + } + // Sends-on-faders creates a new send plus its initial gain atomically; + // its draft UI EdgeId must never be sent as an accepted native EdgeId. + if(Array.isArray(ops)&&ops.length===2&&ops[0].type==="CONNECT"&& + ops[1].type==="GAIN"&&ops[0].sourceId===ops[1].sourceId&& + !wireByUiId.has(ops[1].edgeId)&&Number.isFinite(ops[1].levelDb)) + ops=[{...ops[0],mode:"send",levelDb:ops[1].levelDb}]; const current=controller?.state().current; // P0 first-sound WIRE to MAIN is the very same native M4 PRIMARY_OUT // transaction as the ordinary OUT drop-down. Do not reject a real diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index de5d50a00..f4159cf71 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -132,6 +132,14 @@ ch.inserts[payload.slot].id.length>0 && !ch.inserts.slice(0,payload.slot).some(insert=> insert.id===ch.inserts[payload.slot].id); + if (operation === "SET_WIRE_GAIN") { + const before=pending.wireIdentity; + const edge=next.graph.edges.find(e=>e.enabled&&e.edgeId===payload.edgeId&&e.from===targetChannelId); + return !!before && !!edge && edge.primaryOutput===false && + edge.to===before.to && edge.tap===before.tap && + Number.isFinite(payload.gainLinear)&&Number.isFinite(edge.gainLinear)&& + Math.abs(edge.gainLinear-payload.gainLinear)<=0.0001; + } if (operation !== "APPLY_WIRE_TRANSACTION" || !Array.isArray(payload.changes) || !payload.changes.length) return false; // A structural WIRE transaction must advance the actual PCM graph. @@ -313,12 +321,21 @@ lastError="UNKNOWN_CHANNEL_ID";notify();return {ok:false,error:lastError}; } if (!object(payload)) {lastError="INVALID_PAYLOAD";notify();return {ok:false,error:lastError};} + let wireIdentity=null; + if(operation==="SET_WIRE_GAIN") { + const edge=current.graph.edges.find(e=>e.enabled&&e.edgeId===payload.edgeId&&e.from===targetChannelId); + if(!edge||edge.primaryOutput!==false||!Number.isFinite(payload.gainLinear)|| + payload.gainLinear<0||payload.gainLinear>4) { + lastError="INVALID_WIRE_GAIN_TARGET";notify();return {ok:false,error:lastError}; + } + wireIdentity={to:edge.to,tap:edge.tap}; + } const requestId=session+"-"+(++lastRequest); const msg={requestId,deviceEpoch:current.device.epoch, baseGraphRevision:current.graph.revision, baseRosterRevision:current.graph.rosterRevision, operation,targetChannelId,payload}; - pending={requestId,operation,targetChannelId,payload, + pending={requestId,operation,targetChannelId,payload,wireIdentity, originalPrimaryOutId:current.graph.channels.find( ch=>ch.id===targetChannelId)?.primaryOutId||null, deviceEpoch:msg.deviceEpoch,baseGraphRevision:msg.baseGraphRevision, From 51e37cb914ec02e9a097d883aeab53cd23f569fd Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 04:33:15 +0700 Subject: [PATCH 122/219] fix(audio): recover cold WIRE and native VST3 insertion with prepared graph PDC --- .github/workflows/ui-smoke.yml | 3 + CMakeLists.txt | 4 + docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md | 68 ++++++++++++ engine/core/DynamicChannelFxLeaseBank.h | 21 ++-- engine/core/DynamicNativeSessionPublisher.h | 16 ++- engine/core/DynamicPreparedMixerBlock.h | 97 ++++++++++++----- engine/core/LiveChannelFxGraph.h | 37 +++++-- engine/core/StereoLatencyDelay.h | 28 +++++ .../core/UnifiedLegacyProductionAdmission.h | 3 + integration/ApprovedNativeControlIntent.h | 2 +- integration/ApprovedNativeV8Projection.h | 6 ++ src/ApprovedNativeV8Projection.h | 6 ++ src/LiveAudioEngine.h | 10 +- src/LiveDryRoutingLab.h | 52 ++++++--- src/Main.cpp | 13 ++- tests/approved_native_cold_start_smoke.py | 101 ++++++++++++++++++ tests/approved_native_m2_contract.test.cjs | 4 +- tests/dynamic_latency_compensation_test.cpp | 77 +++++++++++++ tests/live_channel_fx_graph_test.cpp | 44 ++++++-- web/approved-native-bridge.js | 64 ++++++++++- 20 files changed, 573 insertions(+), 83 deletions(-) create mode 100644 docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md create mode 100644 engine/core/StereoLatencyDelay.h create mode 100644 tests/approved_native_cold_start_smoke.py create mode 100644 tests/dynamic_latency_compensation_test.cpp diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 2c455a7b4..c3886c3a5 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -175,6 +175,8 @@ jobs: run: python tests/approved_preview_mobile_navigation_smoke.py - name: FX rack master bypass preserves each insert state (real Chromium) run: python tests/approved_fx_rack_master_power_smoke.py + - name: Cold start first WIRE and original-channel VST3 picker editor + run: python tests/approved_native_cold_start_smoke.py - name: Native WIRE gain and OUT share accepted PCM identity (real Chromium) run: python tests/approved_native_wire_gain_smoke.py - name: Stage D one runtime CSSOM and actual stylesheet network count @@ -461,5 +463,6 @@ jobs: pages-v28-physical-console-owner-v59-*.png pages-mobile-*.png native-wire-gain-*.png + native-cold-start-*.png if-no-files-found: ignore retention-days: 3 diff --git a/CMakeLists.txt b/CMakeLists.txt index 27deec283..9e6f1e467 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -118,6 +118,10 @@ if(BUILD_TESTING) target_compile_features(ARMixApprovedRoutingPcmTests PRIVATE cxx_std_20) add_test(NAME P0ApprovedDecoderChannelToChannelAndSourceOnlyPCM COMMAND ARMixApprovedRoutingPcmTests) add_dependencies(ARMixMixerRoutingTests ARMixApprovedRoutingPcmTests) + add_executable(ARMixLatencyCompensationTests tests/dynamic_latency_compensation_test.cpp) + target_compile_features(ARMixLatencyCompensationTests PRIVATE cxx_std_20) + add_test(NAME NativeGraphLatencyAlignedFanInAndHardwarePCM COMMAND ARMixLatencyCompensationTests) + add_dependencies(ARMixMixerRoutingTests ARMixLatencyCompensationTests) add_executable(ARMixChannelRoutingContractTests tests/channel_routing_contract_test.cpp) target_compile_features(ARMixChannelRoutingContractTests PRIVATE cxx_std_20) add_test(NAME MonoStereoSparsePhysicalPortRouting COMMAND ARMixChannelRoutingContractTests) diff --git a/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md new file mode 100644 index 000000000..fb4aed4f6 --- /dev/null +++ b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md @@ -0,0 +1,68 @@ +# Cold WIRE and native VST3 recovery + +Continues #418 at `16fe8c42`. The supplied Windows screenshots show two +different FX failures: stale routing publication and a blanket plugin-latency +rejection. The reported first-WIRE toast was not captured in those images; +cold admission is covered explicitly below rather than inferred from a +previously working OUT-dropdown transaction. + +## Audited faults + +1. The picker chose M4 for original CH1–10 while ChannelId already owned PCM, + unless an unrelated WIRE edit had set `nativeBusStructural`. PCM authority + now selects native insertion for all admitted INPUT/GROUP/FX_RETURN/MAIN + channels. An occupied external CH1 vendor chain keeps its ownership guard. +2. The legacy compatibility insertion cloned `sourceTemplate_` with its old + APPLY revision. It now stamps the validated current epoch/revision, and + APPLY rejects stale revisions before expensive vendor preparation. +3. Native plugin admission compared a routing epoch to a device-start count. + Reopening a device can make those counters differ. Admission now compares + the actual routing epoch, consistently with accepted native readback. +4. Clicking an admitted native insert still queried M4's FX array. Editor + acquisition now uses exact ChannelId, native PCM revision, slot and opaque + instance token. The existing JUCE editor window retains the real owner. +5. A first drag could reach the bridge while SOURCE admission or another + native intent was pending. One bounded latest CONNECT/ROUTE_ONLY gesture + is retained, requests independent readback and dispatches only after native + projection is ready. Epoch changes, changed mapped endpoint identities, + failure and timeout discard it. No automatic OUT rewrite, output arm or + optimistic wire is introduced. + +## Fixed-latency VST3 support + +The native graph now computes latency along the same prepared DAG. Each +fan-in aligns incoming edges and its own hardware source before processing. +PRE-fader edges in this kernel are post-insert, so they include that source's +FX latency. MAIN and MONITOR terminal timing is aligned as well. A bypassed +insert/rack retains its declared latency through an aligned dry delay, so +scalar bypass does not change compensation or rebuild the graph. + +All delay storage is prepared on CONTROL, bounded by the graph scratch +budget and 131072 samples per path. Callback processing uses preallocated +stereo rings, with no heap/lock/device operation. The host reports actual +native plugin delay in snapshots/audio status. Excessive latency rejects +the candidate and retains the old graph. + +A plugin changing its latency after preparation is conservatively rendered +as aligned dry with `latencyChanged` readback until reloaded. Automatic live +latency reconfiguration is not claimed. Legacy external CH1 paths retain +their existing restrictions; this is not a license to remove their guards. + +## Regression evidence + +- `approved_native_cold_start_smoke.py`: compiled native DOM, real mouse drag + from G0 before admission, no OUT priming, native picker insert on an original + channel with structural=false and unrelated M4 revision, then editor token. + Three desktop sizes. Its backend is emulated for UI isolation. +- `dynamic_latency_compensation_test.cpp`: actual sample impulses through + source latency, serial/parallel PRE/POST sends, receiver hardware fan-in, + MAIN/MONITOR, varying callback sizes, zero render allocations and rejection + rollback on budget overflow. +- `live_channel_fx_graph_test.cpp`: real JUCE AudioProcessor sample delay, + wet/individual/rack bypass timing, zero render allocations, latency-change + fallback and existing vendor-instance migration/ownership regressions. +- Existing decoder/channel-to-channel/source-only PCM and approved GUI bundle + provenance checks remain required. + +Physical user-rig ASIO/WASAPI/VST3 listening and soak remain PENDING. Software +tests do not prove that a third-party vendor plugin or a public rig is safe. diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index 0489e508c..58f0e3689 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -118,13 +118,11 @@ class DynamicChannelFxLeaseBank final { if(owner->processor->getTotalNumInputChannels()!=2 || owner->processor->getTotalNumOutputChannels()!=2) return Fault::invalidBusLayout; - // Global live-mixer architecture (Waves LV1/Ableton): - // parallel PRE/POST paths with unequal VST latency require - // true graph-aware PDC. Until that engine exists, never - // admit a plugin that would produce misaligned MAIN/MONITOR, - // AUX/Group or parallel FX Return PCM. This is a CONTROL-only - // processor inspection, NEVER called from realtime. - if(owner->processor->getLatencySamples()!=0) + // Latency is captured once at prepared instance creation. + // The publisher builds graph-aware fan-in delay from it. + if(owner->latencySamples<0 || + owner->latencySamples>armix::dsp::StereoLatencyDelay::maximumSamples || + owner->latencyChanged.load(std::memory_order_acquire)) return Fault::uncompensatedLatency; for(const auto& existing:candidate.rows_) for(std::size_t k=0;kcount;++i) { + const int n=row->raw[i]->latencySamples; + if(n>armix::dsp::StereoLatencyDelay::maximumSamples-total)return -1; + total+=n; + } + return total; + } std::uint64_t epoch() const noexcept{return epoch_;} std::uint64_t revision() const noexcept{return revision_;} std::size_t lanes() const noexcept{return rows_.size();} diff --git a/engine/core/DynamicNativeSessionPublisher.h b/engine/core/DynamicNativeSessionPublisher.h index 72afa749c..a4f3d6ac8 100644 --- a/engine/core/DynamicNativeSessionPublisher.h +++ b/engine/core/DynamicNativeSessionPublisher.h @@ -28,8 +28,9 @@ class DynamicNativeSessionPublisher final { void* context=nullptr; // unchanged owner.get(), RT raw pointer void (*render)(void*,ChannelId,float*,float*,int) noexcept=nullptr; std::uint64_t deviceEpoch=0,graphRevision=0; + int (*latency)(void*,ChannelId) noexcept=nullptr; bool valid() const noexcept { - return (!owner&&!context&&!render&&!deviceEpoch&&!graphRevision) || + return (!owner&&!context&&!render&&!deviceEpoch&&!graphRevision&&!latency) || (owner&&context==owner.get()&&render&& deviceEpoch>0&&graphRevision>0); } @@ -68,7 +69,7 @@ class DynamicNativeSessionPublisher final { std::uint64_t proposedDeviceEpoch, std::uint64_t activeDeviceEpoch, bool allOutputsDisarmed, - FxPlan fx={nullptr,nullptr,nullptr,0,0},bool verifiedInternalWireOnly=false, + FxPlan fx={nullptr,nullptr,nullptr,0,0,nullptr},bool verifiedInternalWireOnly=false, bool verifiedInternalFxOnly=false) { CommitResult report;report.revision=publisher_.lastRevision(); if(!fx.valid() || @@ -84,7 +85,7 @@ class DynamicNativeSessionPublisher final { expectedRevision==std::numeric_limits::max()) { report.fault=Fault::staleRevision;return report; } - // A zero-latency vendor FX lease can be prepared off-RT and + // A latency-budgeted vendor FX lease can be prepared off-RT and // published on the SAME physical device/patch as the existing // ChannelId graph. Neither WIRE nor this in-place FX edit can // change physical pins. Other structural edits still disarm. @@ -103,6 +104,11 @@ class DynamicNativeSessionPublisher final { roster,request,prepared->graph,report.graphError)) { report.fault=Fault::invalidGraph;return report; } + if(!prepared->graph.prepareLatency([&](ChannelId id) noexcept { + return fx.latency?fx.latency(fx.context,id):0; + },request.maxScratchBytes,report.graphError)) { + report.fault=Fault::invalidGraph;return report; + } // The Console data and PCM schedule must originate from one and the // same accepted roster. No browser-side inferred BUS assignments. if(!DynamicConsoleRoutingView::build(roster,prepared->routing)) { @@ -269,6 +275,10 @@ class DynamicNativeSessionPublisher final { } // CONTROL ONLY; never destroy the last live graph in a callback. + int latencySamples(std::uint64_t epoch,std::uint64_t revision) const noexcept { + const auto* p=publisher_.controlPrepared(epoch,revision); + return p?p->graph.latencySamples():0; + } void unpublish() noexcept {publisher_.unpublish();} void pollRetirement() noexcept {publisher_.pollRetirement();} std::uint64_t acceptedRevision() const noexcept { diff --git a/engine/core/DynamicPreparedMixerBlock.h b/engine/core/DynamicPreparedMixerBlock.h index 8ff0fcf98..196cb1788 100644 --- a/engine/core/DynamicPreparedMixerBlock.h +++ b/engine/core/DynamicPreparedMixerBlock.h @@ -2,6 +2,7 @@ #pragma once #include "DynamicChannelRoster.h" #include "RealtimeSlew64.h" +#include "StereoLatencyDelay.h" #include "RealtimeStereoControlWord.h" #include #include @@ -211,6 +212,55 @@ class DynamicPreparedMixerBlock final { std::find(renderOrder_.begin(),renderOrder_.end(),found->second)!=renderOrder_.end(); } + // CONTROL-only DAG PDC. Every fan-in receives sample-aligned PCM, + // including a destination's own hardware capture and PRE-fader sends. + // A failure discards the unpublished candidate; the old graph stays live. + template + bool prepareLatency(Latency&& latency,std::size_t budget,DynamicGraphError& error) { + std::vector arrival(lanes_.size(),0),output(lanes_.size(),0); + std::size_t bytes=scratch_.size()*sizeof(float); + edgeDelays_.resize(edges_.size());physicalDelays_.resize(lanes_.size()); + sinkDelays_.resize(lanes_.size()); + const auto allocate=[&](armix::dsp::StereoLatencyDelay& delay,int samples) { + if(samples<0||samples>armix::dsp::StereoLatencyDelay::maximumSamples)return false; + const auto need=static_cast(samples)*2*sizeof(float); + if(bytes>budget||need>budget-bytes)return false; + bytes+=need;return delay.prepare(samples); + }; + for(const auto i:renderOrder_) { + const int own=latency(lanes_[i].id); + if(own<0||own>armix::dsp::StereoLatencyDelay::maximumSamples|| + arrival[i]>armix::dsp::StereoLatencyDelay::maximumSamples-own) { + error={DynamicGraphFault::overflow,lanes_[i].id};return false; + } + const auto dryBytes=static_cast(own)*2*sizeof(float); + if(bytes>budget||dryBytes>budget-bytes) { + error={DynamicGraphFault::scratchBudget,lanes_[i].id};return false; + } + bytes+=dryBytes; // prepared VST bypass delay is part of PDC budget + output[i]=arrival[i]+own; + for(std::size_t e=lanes_[i].first;e=0&&!allocate(physicalDelays_[i],arrival[i])) { + error={DynamicGraphFault::scratchBudget,lane.id};return false; + } + for(std::size_t e=lane.first;e(fade.remaining-1)* - (1.f/static_cast(armix::dsp::RealtimeSlew64::samples)); - const float beforeL=oldL?oldL[f]:0.f; - const float beforeR=oldR?oldR[f]:0.f; - const float afterL=newL?newL[f]:0.f; - const float afterR=newR?newR[f]:0.f; - l[f]+=beforeL+(afterL-beforeL)*alpha; - r[f]+=beforeR+(afterR-beforeR)*alpha; - --fade.remaining; - if(fade.remaining==0){ - fade.current=fade.next; - // New CONTROL requests are consumed next block; - // never change the source mid-sample. - oldL=newL;oldR=newR; - for(int k=f+1;k0) { + const float alpha=1.f-static_cast(fade.remaining-1)/ + static_cast(armix::dsp::RealtimeSlew64::samples); + vl+=((newL?newL[f]:0.f)-vl)*alpha; + vr+=((newR?newR[f]:0.f)-vr)*alpha; + if(--fade.remaining==0){fade.current=fade.next;oldL=newL;oldR=newR;} } + if(!physicalDelays_.empty())physicalDelays_[i].process(vl,vr); + l[f]+=vl;r[f]+=vr; } } if(lane.format==ProcessingFormat::mono) @@ -605,8 +641,9 @@ class DynamicPreparedMixerBlock final { target.applied.retarget(goal); for(int f=0;f initialAudible_,soloAncestors_,soloDescendants_; std::vector blockTargets_; // all allocated before RT std::vector scratch_; + std::vector edgeDelays_,physicalDelays_,sinkDelays_; + int latencySamples_=0; std::unique_ptr channelTargets_; std::unique_ptr[]> sourceTargets_; std::unique_ptr sourceFades_; diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index 7bd2ba0e4..bf9bb31e3 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -2,6 +2,8 @@ #pragma once #include "PreparedMixerBlock.h" #include "FxBypassEnvelope.h" +#include "StereoLatencyDelay.h" +#include #include #include #include @@ -27,12 +29,15 @@ class LiveChannelFxGraph final { static constexpr int maxInsertsPerStrip=8; // fixed capacity, no RT allocation using Processor=juce::AudioProcessor; - struct FxInstance final { + struct FxInstance final : juce::AudioProcessorListener { std::unique_ptr processor; juce::MidiBuffer midi; const juce::String catalogId; const juce::String name; const juce::String instanceId; // stable through MOVE; never a slot index + const int latencySamples; + std::atomic latencyChanged{false}; + armix::dsp::StereoLatencyDelay dryDelay; std::atomic bypassRequested{false}; armix::dsp::FxBypassEnvelope bypassFade; // RT exclusive state std::vector dryLeft,dryRight; // CONTROL allocation @@ -46,10 +51,13 @@ class LiveChannelFxGraph final { : processor(std::move(p)),catalogId(std::move(id)),name(std::move(label)), instanceId("g5c-"+juce::String(static_cast( nextId.fetch_add(1,std::memory_order_relaxed)))), + latencySamples(processor?processor->getLatencySamples():0), dryLeft(static_cast(maxSamples)), dryRight(static_cast(maxSamples)) { + if(!dryDelay.prepare(latencySamples))throw std::invalid_argument("VST3 latency exceeds prepared delay budget"); midi.ensureSize(1024); bypassFade.prepare(false,processor?processor->getSampleRate():48000.0,0); + if(processor)processor->addListener(this); } FxInstance(const FxInstance&)=delete; FxInstance& operator=(const FxInstance&)=delete; @@ -57,10 +65,17 @@ class LiveChannelFxGraph final { // Shared by old/new immutable snapshots; last owner drops ONLY on // control-thread retirement after the final RT reader exits. if(processor) { + processor->removeListener(this); try { processor->releaseResources(); } catch(...) { /* vendor cleanup cannot unwind graph retirement */ } } } + void audioProcessorParameterChanged(juce::AudioProcessor*,int,float) override {} + void audioProcessorChanged(juce::AudioProcessor* p, + const juce::AudioProcessorListener::ChangeDetails& details) override { + if(details.latencyChanged && p && p->getLatencySamples()!=latencySamples) + latencyChanged.store(true,std::memory_order_release); + } // G5E: vendor binary state capture is CONTROL only. This is the same // fail-closed gate used by realtime processBlock. While control owns // the gate, a racing muted callback returns silence without waiting. @@ -89,21 +104,25 @@ class LiveChannelFxGraph final { // G5C: atomic request from control; fade and scratch RT-owned. // Master rack bypass affects the WET/DRY envelope, never the remembered insert preference. bypassFade.request(rackBypassed || bypassRequested.load(std::memory_order_relaxed)); - if(bypassFade.fullyBypassed()) { - processing.clear(std::memory_order_release); - return; - } if(samples<=0 || static_cast(samples)>dryLeft.size()) { juce::FloatVectorOperations::clear(left,std::max(0,samples)); juce::FloatVectorOperations::clear(right,std::max(0,samples)); processing.clear(std::memory_order_release); return; } - const bool fading=bypassFade.transitioning(); - if(fading) { - juce::FloatVectorOperations::copy(dryLeft.data(),left,samples); - juce::FloatVectorOperations::copy(dryRight.data(),right,samples); + // Keep bypass at the SAME declared latency as wet, including + // rack bypass and disabled slots. PDC never changes on a scalar. + for(int i=0;i(i)]=l; + dryRight[static_cast(i)]=r; + } + if(bypassFade.fullyBypassed()||latencyChanged.load(std::memory_order_acquire)) { + juce::FloatVectorOperations::copy(left,dryLeft.data(),samples); + juce::FloatVectorOperations::copy(right,dryRight.data(),samples); + processing.clear(std::memory_order_release);return; } + const bool fading=bypassFade.transitioning(); try { float* planar[]{left,right}; juce::AudioBuffer buffer(planar,2,samples); diff --git a/engine/core/StereoLatencyDelay.h b/engine/core/StereoLatencyDelay.h new file mode 100644 index 000000000..804530e16 --- /dev/null +++ b/engine/core/StereoLatencyDelay.h @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include + +namespace armix::dsp { +// CONTROL prepares storage; AUDIO owns the cursor. Zero delay is a true +// passthrough. No allocation, interpolation, lock or modulo in the sample path. +class StereoLatencyDelay final { +public: + static constexpr int maximumSamples=131072; + bool prepare(int samples) { + if(samples<0 || samples>maximumSamples)return false; + data_.assign(static_cast(samples)*2,0.f);cursor_=0; + return true; + } + void process(float& left,float& right) noexcept { + if(data_.empty())return; + const float l=data_[cursor_],r=data_[cursor_+1]; + data_[cursor_]=left;data_[cursor_+1]=right; + left=l;right=r;cursor_+=2; + if(cursor_==data_.size())cursor_=0; + } +private: + std::vector data_; + std::size_t cursor_=0; +}; +} diff --git a/engine/core/UnifiedLegacyProductionAdmission.h b/engine/core/UnifiedLegacyProductionAdmission.h index e82a86b55..ba55ee45a 100644 --- a/engine/core/UnifiedLegacyProductionAdmission.h +++ b/engine/core/UnifiedLegacyProductionAdmission.h @@ -186,6 +186,9 @@ class UnifiedLegacyProductionAdmission final { plan.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { (*static_cast(ctx))(id,l,r,n); }; + plan.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; plan.deviceEpoch=deviceEpoch;plan.graphRevision=expectedPcmRevision+1; result.native=publisher.commit(candidate.roster,candidate.request, expectedPcmRevision,deviceEpoch,currentHardwareEpoch, diff --git a/integration/ApprovedNativeControlIntent.h b/integration/ApprovedNativeControlIntent.h index 88aacc2b2..ee4c6c38d 100644 --- a/integration/ApprovedNativeControlIntent.h +++ b/integration/ApprovedNativeControlIntent.h @@ -263,7 +263,7 @@ inline ApprovedNativeControlIntent translateApprovedNativeControl( const auto role=ch.getProperty("role","").toString(); if(!ch.isObject()||!nativeCh.isObject()|| role!=nativeCh.getProperty("role","").toString()|| - (role!="INPUT"&&role!="GROUP")) + (role!="INPUT"&&role!="GROUP"&&role!="FX_RETURN"&&role!="MAIN")) return reject("NATIVE_VST3_TARGET_NOT_ADMITTED"); const auto payload=publicIntent.getProperty("payload",{}); const auto catalog=payload.getProperty("catalogId",{}); diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index d4886e20d..ac7b0b98a 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -96,6 +96,10 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, insert->setProperty("id",token);insert->setProperty("catalogId",catalog); insert->setProperty("name",label); insert->setProperty("bypassed",bypass); + const auto latency=item.getProperty("latencySamples",{}); + if(latency.isInt())insert->setProperty("latencySamples",latency); + const auto changed=item.getProperty("latencyChanged",{}); + if(changed.isBool())insert->setProperty("latencyChanged",changed); fx.add(juce::var(insert.release())); } ch->setProperty("inserts",juce::var(fx)); @@ -162,6 +166,8 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, if(!g||!t||!graph.getProperty("capabilities",{}).isObject())return false; // All validation completed before anything becomes authoritative. g->setProperty("revision",rev);g->setProperty("rosterRevision",roster); + const auto latency=bus.getProperty("latencySamples",{}); + if(latency.isInt())g->setProperty("latencySamples",latency); g->setProperty("mainChannelId",mainId); g->setProperty("channels",juce::var(channels)); g->setProperty("destinations",juce::var(destinations)); diff --git a/src/ApprovedNativeV8Projection.h b/src/ApprovedNativeV8Projection.h index abe496c4b..792d5e291 100644 --- a/src/ApprovedNativeV8Projection.h +++ b/src/ApprovedNativeV8Projection.h @@ -87,6 +87,10 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { insert->setProperty("id",token);insert->setProperty("catalogId",catalog); insert->setProperty("name",label); insert->setProperty("bypassed",bypass); + const auto latency=item.getProperty("latencySamples",{}); + if(latency.isInt())insert->setProperty("latencySamples",latency); + const auto changed=item.getProperty("latencyChanged",{}); + if(changed.isBool())insert->setProperty("latencyChanged",changed); fx.add(juce::var(insert.release())); } ch->setProperty("inserts",juce::var(fx)); @@ -153,6 +157,8 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus) { if(!g||!t)return false; // All validation completed before anything becomes authoritative. g->setProperty("revision",rev);g->setProperty("rosterRevision",roster); + const auto latency=bus.getProperty("latencySamples",{}); + if(latency.isInt())g->setProperty("latencySamples",latency); g->setProperty("mainChannelId",mainId); g->setProperty("channels",juce::var(channels)); g->setProperty("destinations",juce::var(destinations)); diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index b3f2c89e2..4eb16f431 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1491,7 +1491,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback routeReconfiguring_.load(std::memory_order_acquire)|| diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal)return fail; - if(ep!=deviceStartCount_.load(std::memory_order_acquire)) + if(ep!=dryRoutingLab_.epoch()) {fail.error="NATIVE_VST3_DEVICE_CHANGED";return fail;} const auto rate=device->getCurrentSampleRate(); const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); @@ -1517,8 +1517,9 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback fail.error="NATIVE_VST3_INCOMPATIBLE_STEREO_LAYOUT";return fail; } instance->prepareToPlay(rate,frames); - if(instance->getLatencySamples()!=0) { - fail.error="NATIVE_VST3_REQUIRES_PDC";return fail; + if(instance->getLatencySamples()<0 || + instance->getLatencySamples()>armix::dsp::StereoLatencyDelay::maximumSamples) { + fail.error="NATIVE_VST3_LATENCY_EXCEEDS_BUDGET";return fail; } auto lease=std::make_shared< armix::mixer::LiveChannelFxGraph::FxInstance>( @@ -1883,7 +1884,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback o->setProperty ("masterLufs", loudness.integratedLufs); if (measuredDirect && loudness.truePeakValid) o->setProperty ("masterDbtp", loudness.dbtp); - o->setProperty ("latencySamples", totalLatency_.load()); + o->setProperty ("latencySamples", dryRoutingLab_.channelIdPhysicalPcmActive()? + dryRoutingLab_.nativePcmLatencySamples():totalLatency_.load()); o->setProperty ("chainCount", graphOwned_->count); o->setProperty ("graphSwitchPending", handoff_.busy()); o->setProperty ("completedGraphSwaps", static_cast (completedSwaps_.load())); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index c27ba7b8e..2eda22b6b 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -282,6 +282,8 @@ class LiveDryRoutingLab final { static_cast(command.getProperty("revision",juce::var(0)))); if(currentEpoch==0 || expectedEpoch!=currentEpoch) return "Audio device changed: reopen ROUTING to remap physical ports"; + if(expectedRevision!=revision()) + return "Routing revision changed before preparation; refresh accepted state"; armix::mixer::NativeDryRouteCommand decoded; juce::String validationError; if(!armix::mixer::NativeDryRouteCommand::decode( @@ -569,6 +571,8 @@ class LiveDryRoutingLab final { juce::JSON::toString(sourceTemplate_,false)); if(!command.isObject()) return "FX INSERT: accepted source template cannot be cloned"; + command.getDynamicObject()->setProperty("deviceEpoch",static_cast(expectedEpoch)); + command.getDynamicObject()->setProperty("revision",static_cast(expectedRevision)); // A vendor plugin prepare happens AFTER live native fader/PAN edits. // Recompile from the last accepted operator controls, not the stale // pre-fader sourceTemplate_ values. Rejection keeps the old PCM live. @@ -1266,23 +1270,13 @@ class LiveDryRoutingLab final { out.error="NATIVE_INSERT_REQUIRES_PREPARED_INTERNAL_FX";return out; } const auto* current=nativeAccepted_.graph.roster.find(target); - if(!current || (current->role!=ChannelRole::input && - current->role!=ChannelRole::group)) { + if(!current || current->role==ChannelRole::monitor) { out.error="NATIVE_INSERT_TARGET_UNAVAILABLE";return out; } - // Original ten strips use their existing M4 VST rack until native - // BUS/WIRE makes the ChannelId graph structurally authoritative. - // Thereafter new native inserts must attach to the SAME prepared - // ChannelId lease (not to an inactive M4 graph). Special CH1 external - // vendor chain stays isolated until an explicit combined-chain gate: - // appending there would otherwise double-render or hide the old FX. - for(const auto id:nativeAccepted_.graph.ids.inputs) - if(id==target && (!nativeStructureLive_ || - nativeAccepted_.fxOwners->externalChannel()==target)) { - out.error="M4_INSERT_USE_EXISTING_RACK";return out; - } - if(originalM4Aux(target)){ - out.error="M4_INSERT_USE_EXISTING_RACK";return out; + // PCM authority, not historical strip ordinal, owns every new FX. + // An occupied external CH1 chain still needs a combined lease contract. + if(nativeAccepted_.fxOwners->externalChannel()==target) { + out.error="EXTERNAL_CH1_INSERT_CHAIN_ALREADY_OWNED";return out; } if(catalogId.isEmpty()||catalogId.getNumBytesAsUTF8()>256) { out.error="INVALID_VST3_CATALOG_ID";return out; @@ -1313,6 +1307,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept{ (*static_cast(ctx))(id,l,r,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; const auto published=nativePublisher_.commit( @@ -1427,6 +1424,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { (*static_cast(ctx))(id,l,r,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; // Keep old PCM running throughout candidate validation/FX lease @@ -1519,6 +1519,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { (*static_cast(ctx))(id,l,r,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; if(beforePublish)beforePublish(); // no hardware mute during prepare @@ -1598,6 +1601,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { (*static_cast(ctx))(id,l,r,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch; fx.graphRevision=expectedPcmRevision+1; const auto published=nativePublisher_.commit( @@ -1681,6 +1687,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* left,float* right,int n) noexcept { (*static_cast(ctx))(id,left,right,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=expectedEpoch;fx.graphRevision=expectedPcmRevision+1; if(beforePublish)beforePublish(); // late PCM publication gate const auto published=nativePublisher_.commit( @@ -1751,6 +1760,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* rr,int n) noexcept{ (*static_cast(ctx))(id,l,rr,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=ep;fx.graphRevision=expectedPcmRev+1; const auto published=nativePublisher_.commit( roster,nativeAccepted_.graph.request,expectedPcmRev, @@ -1819,6 +1831,9 @@ class LiveDryRoutingLab final { fx.render=+[](void* ctx,ChannelId id,float* l,float* rr,int n) noexcept { (*static_cast(ctx))(id,l,rr,n); }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; fx.deviceEpoch=ep; fx.graphRevision=expectedPcmRev+1; const auto published=nativePublisher_.commit( @@ -1946,6 +1961,10 @@ class LiveDryRoutingLab final { } return false; } + int nativePcmLatencySamples() const noexcept { + return channelIdPhysicalPcmActive()? + nativePublisher_.latencySamples(epoch(),nativeAccepted_.pcmRevision):0; + } // CONTROL snapshot: genuine stable ChannelIds from the SAME publisher // as physical PCM. No guessed IDs, synthetic UI routes or JS DSP. juce::var nativeBusStatus() const { @@ -1959,6 +1978,7 @@ class LiveDryRoutingLab final { state->setProperty("rosterRevision",juce::String( std::to_string(routing->rosterRevision))); state->setProperty("structural",nativeStructureLive_); + state->setProperty("latencySamples",nativePublisher_.latencySamples(epoch(),nativeAccepted_.pcmRevision)); juce::Array allowed; // Only expose operations backed by a real DSP lease. Dynamic // FX_RETURN insertion is not available until a native VST3 owner @@ -2017,6 +2037,8 @@ class LiveDryRoutingLab final { item->setProperty("instanceId",(*lease)->instanceId); item->setProperty("id",(*lease)->catalogId); item->setProperty("name",(*lease)->name); + item->setProperty("latencySamples",(*lease)->latencySamples); + item->setProperty("latencyChanged",(*lease)->latencyChanged.load(std::memory_order_acquire)); item->setProperty("bypassed",(*lease)->bypassRequested.load( std::memory_order_relaxed)); liveInserts.add(juce::var(item.release())); diff --git a/src/Main.cpp b/src/Main.cpp index 4111ac8cd..1709e4c5b 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2200,8 +2200,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool opened=false; juce::String error="FX editor unavailable: device, revision or instance changed"; if(!nativeShowBusy_&&!studioBackupBusy_&&!engine_.isGraphSwitchPending()) { - const auto owner=engine_.leaseRoutedFxForEditor( - lane,slot,epoch,revision,token); + armix::mixer::LiveChannelFxGraph::InstanceLease owner; + const auto nativeId=args.getProperty("channelId",{}); + if(!nativeId.isVoid()) { + std::uint64_t id=0,ep=0,rev=0; + if(armix::console::approvedNativeId(nativeId,id)&& + armix::console::approvedNativeId(args.getProperty("deviceEpoch",{}),ep)&& + armix::console::approvedNativeId(args.getProperty("revision",{}),rev)&& + slot>=0&&slot(slot),token); + } else owner=engine_.leaseRoutedFxForEditor(lane,slot,epoch,revision,token); if(owner && owner->processor) { try { if(auto* editor=owner->processor->createEditorIfNeeded()) { diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py new file mode 100644 index 000000000..a70f9040e --- /dev/null +++ b/tests/approved_native_cold_start_smoke.py @@ -0,0 +1,101 @@ +"""Real compiled DOM from G0: first drag without OUT priming, first native +FX picker insert on original CH with structural=false, then vendor editor. +Backend isolation is emulated; actual latency/sample evidence is CTest. +""" +import copy +import importlib.util +import json +from pathlib import Path +import tempfile +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import snapshot, emit, ack, SOURCE, RECEIVER + +ROOT = Path(__file__).resolve().parents[1] + + +def drag(page, source, destination): + a = page.locator(f'#tracks .strip[data-id="{source}"] .wire-node-out').bounding_box() + b = page.locator(f'#tracks .strip[data-id="{destination}"] .wire-node-in').bounding_box() + assert a and b + page.mouse.move(a['x'] + a['width']/2, a['y'] + a['height']/2) + page.mouse.down() + page.mouse.move(b['x'] + b['width']/2, b['y'] + b['height']/2, steps=12) + page.mouse.up() + + +def main(): + spec = importlib.util.spec_from_file_location('bundle', ROOT/'scripts/build_approved_native_gui.py') + bundle = importlib.util.module_from_spec(spec) + spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory() as directory, sync_playwright() as p: + out = Path(directory) + bundle.stage(out) + browser = p.chromium.launch() + for width, height in [(1366,768),(1680,900),(1920,1080)]: + page = browser.new_page(viewport={'width':width,'height':height}) + errors=[] + page.on('pageerror', lambda e:errors.append(str(e))) + page.add_init_script("""window.__nativeListeners=new Map();window.__events=[];window.__nativeIntents=[]; + window.__JUCE__={backend:{emitEvent(name,payload){window.__events.push({name,payload}); + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out/'index.html').as_uri()) + page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + g0=json.loads((ROOT/'integration/console-v6/fixtures.json').read_text())['g0'] + g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} + g0['legacyM4']={'active':True,'routeAccepted':False,'routingRevision':'1'} + emit(page,'arMixConsoleSnapshot',g0) + if 'collapsed-send' in (page.locator('.console-body').get_attribute('class') or ''): + page.locator('.section-rail [data-section="send"]').click() + # Release before bootstrap SOURCE's later native readback arrives. + drag(page,1,2) + assert not page.evaluate('()=>window.__nativeIntents.length') + state=snapshot() + state['graph']['edges'].pop(1) # genuinely no existing channel send + state['graph']['capabilities']['supportedOps'] += ['LOAD_INSERT'] + state['legacyM4']={'active':True,'routeAccepted':True,'routingRevision':'77', + 'nativeBusStructural':False,'fxInstances':[[] for _ in range(14)]} + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function('()=>window.__nativeIntents.length===1') + route=page.evaluate('()=>window.__nativeIntents[0]') + assert route['operation']=='APPLY_WIRE_TRANSACTION' + assert route['payload']['changes'][0]['from']==SOURCE + assert route['payload']['changes'][0]['to']==RECEIVER + assert route['payload']['changes'][0]['op']=='CONNECT' + state['graph'].update(revision='3',rosterRevision='3') + state['graph']['edges'].append({'edgeId':'9223372036854775810','from':SOURCE,'to':RECEIVER, + 'primaryOutput':False,'enabled':True,'gainLinear':1,'tap':'POST_FADER','signalKind':'AUDIO'}) + state['mixerSession'].update(routeRevision='3',rosterRevision='3',channels=copy.deepcopy(state['graph']['channels'])) + ack(page,state,route) + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function('()=>!window.__ARMIX_NATIVE_M2__.state().pending') + # First FX on original CH: native authority even when the legacy + # structural marker is false and its independent revision is 77. + emit(page,'arMixCatalog',{'items':[{'id':'test-vst-64','name':'Latency VST','vendor':'Fixture', + 'category':'EQ','favorite':True}],'scanning':False}) + page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.click() + page.locator('#fastPicker [data-fast-id="test-vst-64"]').click() + page.wait_for_function('()=>window.__nativeIntents.length===2') + fx=page.evaluate('()=>window.__nativeIntents.at(-1)') + assert fx['operation']=='LOAD_INSERT' and fx['baseGraphRevision']=='3' + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='routingFxInsert')") + state['graph'].update(revision='4',rosterRevision='4') + state['graph']['channels'][0]['inserts']=[{'id':'g5c-actual','catalogId':'test-vst-64', + 'name':'Latency VST','bypassed':False,'latencySamples':64}] + state['mixerSession'].update(routeRevision='4',rosterRevision='4',channels=copy.deepcopy(state['graph']['channels'])) + ack(page,state,fx) + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function("()=>document.getElementById('fastPicker').hidden") + page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.click() + editor=page.evaluate("()=>window.__events.filter(e=>e.payload?.action==='routingFxEditor').at(-1)?.payload") + assert editor and editor['channelId']==SOURCE and editor['instanceId']=='g5c-actual' + assert editor['revision']=='4' and 'channel' not in editor + assert not errors, errors + page.screenshot(path=f'native-cold-start-{width}.png') + page.close() + browser.close() + print('PASS G0 first drag without OUT priming; original-channel native FX insert/editor; 3 sizes (UI isolation)') + + +if __name__=='__main__': + main() diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index ceca46185..5c812b804 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -200,7 +200,7 @@ test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual assert.match(activeProjection,/insert->setProperty\("catalogId",catalog\)/); assert.match(activeProjection,/ch->setProperty\("fxRackBypassed",rackBypassed\)/); assert.match(bridge,/controller\.intent\("LOAD_INSERT",nativeId,/); - assert.match(bridge,/legacy\(\)\?\.nativeBusStructural===true/); + assert.match(bridge,/if\(accepted\?\.admitted && nativeCh\)/); assert.match(lab,/nativeAccepted_\.fxOwners->externalChannel\(\)==target/); assert.match(bridge,/pendingFxInsert=\{authority:"CHANNEL_ID"/); assert.match(bridge,/inserted\?\.catalogId===p\.id/); @@ -215,7 +215,7 @@ test("Native FX GUI routes through ChannelId PCM with no operator MONITOR ritual engine.indexOf("bool bypassNativeVst3(",engine.indexOf("installNativeVst3("))); assert.doesNotMatch(install,/!allOutputsDisarmed\(\)/); assert.match(install,/secondaryOutput_\.armed\(\)/); - assert.match(install,/getLatencySamples\(\)!=0/); + assert.match(install,/getLatencySamples\(\)>armix::dsp::StereoLatencyDelay::maximumSamples/); }); test("Native VST3 insert ACK + readback distinguishes vendor catalog key from live instance token",()=>{ const base=acceptedFixture(); diff --git a/tests/dynamic_latency_compensation_test.cpp b/tests/dynamic_latency_compensation_test.cpp new file mode 100644 index 000000000..e2d1db28d --- /dev/null +++ b/tests/dynamic_latency_compensation_test.cpp @@ -0,0 +1,77 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/core/DynamicNativeSessionPublisher.h" +#ifdef NDEBUG +#undef NDEBUG +#endif +#include +#include +#include +#include +static std::size_t allocations=0; +void* operator new(std::size_t n){++allocations;if(auto* p=std::malloc(n?n:1))return p;throw std::bad_alloc();} +void* operator new[](std::size_t n){return ::operator new(n);} +void operator delete(void* p) noexcept {std::free(p);} +void operator delete[](void* p) noexcept {std::free(p);} +void operator delete(void* p,std::size_t) noexcept {std::free(p);} +void operator delete[](void* p,std::size_t) noexcept {std::free(p);} +using namespace armix::mixer; +struct Effects { + ChannelId a{},receiver{}; + armix::dsp::StereoLatencyDelay delayA,delayReceiver; + int latency(ChannelId id) const noexcept{return id==a?7:id==receiver?3:0;} + void render(ChannelId id,float* l,float* r,int n) noexcept { + auto* delay=id==a?&delayA:id==receiver?&delayReceiver:nullptr; + if(delay)for(int i=0;iprocess(l[i],r[i]); + } +}; +int main(){ + for(bool pre:{false,true}) { + DynamicChannelRoster roster; + std::vector edits; + for(int i=0;i<5;++i){ChannelEdit e;e.kind=ChannelEdit::Kind::add; + e.position=i;e.role=i==3?ChannelRole::main:i==4?ChannelRole::monitor:ChannelRole::input; + e.format=ProcessingFormat::stereo;e.text="node";edits.push_back(e);} + const auto added=roster.edit(0,edits);assert(added.ok()); + const auto ids=added.createdIds;const auto a=ids[0],b=ids[1],r=ids[2],main=ids[3],monitor=ids[4]; + std::vector sends; + const auto send=[&](ChannelId from,ChannelId to,bool before=false){ChannelEdit e; + e.kind=ChannelEdit::Kind::addSendReference;e.id=from;e.target=to;e.value=1;e.preFader=before;sends.push_back(e);}; + send(a,main);send(a,r,pre);send(b,r);send(r,main);send(b,monitor); + assert(roster.edit(1,sends).ok()); + // Physical receiver input is mixed alongside internally delayed PCM. + DynamicGraphRequest request;request.physicalInputs=6;request.maxFrames=16; + request.sources={{a,0,1,true},{b,2,3,true},{r,4,5,true}}; + auto fx=std::make_shared();fx->a=a;fx->receiver=r; + assert(fx->delayA.prepare(7)&&fx->delayReceiver.prepare(3)); + DynamicNativeSessionPublisher publisher; + DynamicNativeSessionPublisher::FxPlan plan; + plan.owner=fx;plan.context=fx.get();plan.deviceEpoch=9;plan.graphRevision=1; + plan.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept {static_cast(p)->render(id,l,r,n);}; + plan.latency=+[](void* p,ChannelId id) noexcept{return static_cast(p)->latency(id);}; + assert(publisher.commit(roster,request,0,9,9,true,plan).ok()); + assert(publisher.latencySamples(9,1)==10); + std::array inA{},inB{},inR{},l{},right{},ml{},mr{}; + int time=0; + for(int n:{3,1,7,5,16}){ + inA.fill(0);inB.fill(0);inR.fill(0); + if(time==0){inA[0]=1;inB[0]=2;inR[0]=4;} + const float* physical[]{inA.data(),inA.data(),inB.data(),inB.data(),inR.data(),inR.data()}; + const auto before=allocations; + assert(publisher.render(9,physical,6,l.data(),right.data(),n,false, + [](ChannelId,float*,float*,int) noexcept {},ml.data(),mr.data())); + assert(allocations==before); + for(int i=0;i& buffer,juce::MidiBuffer&)override{ for(int c=0;c makeGraph(float firstFx,float returnFx,bool withFx=true) { @@ -210,9 +216,8 @@ static void verifyUniversalChannelIdFxLeaseAndLivePcm() { alias[1].inserts=first.inserts; // same native processor twice assert(Bank::prepare(epoch,2,alias,blocked)==Bank::Fault::duplicateInstance); assert(blocked.lanes()==0); - // Native PDC is not yet installed. A real JUCE AudioProcessor reporting - // 64 samples of plugin delay must be rejected BEFORE accepted PCM/lease - // publication; mixing uncompensated Return with MAIN is phase-unsafe. + // A fixed-latency VST lease is admitted; the PCM publisher consumes its + // exact inventory to prepare fan-in compensation before publication. auto latentProcessor=std::make_unique(1.5f); latentProcessor->setLatencySamples(64); latentProcessor->prepareToPlay(48000.0,64); @@ -222,8 +227,8 @@ static void verifyUniversalChannelIdFxLeaseAndLivePcm() { std::move(latentProcessor),"latent-vst","latency-64",64)); const std::array latentScene{latent}; assert(Bank::prepare(epoch,2,latentScene,blocked)== - Bank::Fault::uncompensatedLatency); - assert(blocked.lanes()==0); // failed admission cannot mutate previous bank + Bank::Fault::none); + assert(blocked.latencySamples(ch11)==64); assert(Bank::prepare(epoch,2,assignments,blocked)==Bank::Fault::none); const auto token=original->insertInstanceId(0,0); auto migrated=*bank.ownerForControl(ch1,0); @@ -1885,6 +1890,28 @@ static void verifyChannelIdGroupPreservesHostedFx() { live.unpublish();live.pollRetirement(); } +static void verifyLatencyAlignedBypass() { + // Real JUCE processing (not merely reporting a latency value): an impulse + // remains at sample 7 through wet, individual bypass and rack bypass. + for(int mode=0;mode<3;++mode){ + auto p=std::make_unique(1.f,7);p->prepareToPlay(48000,64); + LiveChannelFxGraph::FxInstance fx(std::move(p),"delayed","7 samples",64); + fx.bypassRequested.store(mode==1); + std::array l{},r{}; + // Reach the bypass envelope's steady state first. + for(int block=0;block<10;++block){l.fill(0);r.fill(0);fx.render(l.data(),r.data(),64,mode==2);} + l.fill(0);r.fill(0);l[0]=r[0]=1; + const auto before=heapCalls.load(); + fx.render(l.data(),r.data(),64,mode==2); + assert(heapCalls.load()==before); + for(int i=0;i<64;++i)assert(near(l[i],i==7?1.f:0.f)&&near(l[i],r[i])); + fx.processor->setLatencySamples(8); + assert(fx.latencyChanged.load()); // no unaligned wet enters accepted PCM + l.fill(0);r.fill(0);l[0]=r[0]=1; + fx.render(l.data(),r.data(),64,mode==2); + for(int i=0;i<64;++i)assert(near(l[i],i==7?1.f:0.f)); + } +} int main(int argc,char** argv) { if(argc==2 && std::string(argv[1])=="--emit-console-s0-json") { verifyNativePuzzleV8FixtureAndWire(); @@ -2296,6 +2323,7 @@ int main(int argc,char** argv) { verifyFirstSoundOnePinNativeSourceDraft(); verifyNativePuzzleV8FixtureAndWire(); verifyChannelIdGroupPreservesHostedFx(); + verifyLatencyAlignedBypass(); // Tests above use a real JUCE AudioProcessor processing seam. Vendor // VST3 formats and sound quality require separate Windows hardware FAT. } diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 15f04e4fb..9db95b888 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -18,6 +18,37 @@ const uiByWireId = new Map(); const pendingWireGains=new Map(); let wireGainFlushQueued=false; + let startupWire=null, startupWireSerial=0; + function deferStartupWire(ops){ + if(!Array.isArray(ops)||ops.length!==1|| + !["CONNECT","ROUTE_ONLY"].includes(ops[0].type)||!deviceReady())return false; + const current=controller?.state()?.current,op=ops[0]; + const epoch=current?.device?.epoch||String(hardware?.device?.epoch||""); + if(!/^[1-9][0-9]*$/.test(epoch))return false; + const token=++startupWireSerial; + startupWire={ops:ops.map(x=>({...x})),epoch,token, + source:nativeByUiId.get(op.sourceId),destination:nativeByUiId.get(op.destId)}; + status("WIRE · completing initial native input admission"); + controller?.subscribe(); + window.setTimeout(()=>{ + if(startupWire?.token!==token)return; + startupWire=null;status("WIRE not applied · native admission timed out; previous audio preserved"); + },8000); + return true; + } + function flushStartupWire(){ + if(!startupWire)return; + const state=controller?.state(),current=state?.current,p=startupWire,op=p.ops[0]; + if(current?.device?.epoch!==p.epoch){startupWire=null;return;} + if(state.pending||activeNativeSource||nativeUiSourcePending|| + pendingNativeSources.size||pendingSourceQueue.size|| + !flags.acceptedGraphConnected||!current.admitted)return; + startupWire=null; + if((p.source&&nativeByUiId.get(op.sourceId)!==p.source)|| + (p.destination&&nativeByUiId.get(op.destId)!==p.destination))return; + nativeHooks.consumeWire(p.ops); + } + let lastPaintedSignature = "",lastNativeTopologySignature = "", lastNativeError = "NATIVE_NOT_SUBSCRIBED"; // B-stage: attached-node-only meter caches; a structural render invalidates @@ -228,6 +259,10 @@ const row=[...rack.querySelectorAll('.fxslot-row:not(.is-empty)')] .find(r=>r.dataset.slot===String(slot)); const effective=enabled&&!insert.bypassed; + if(insert.latencyChanged===true) + row.title="Plugin delay changed · aligned dry signal retained; reload the plugin before using its new delay"; + else if(Number.isInteger(insert.latencySamples)) + row.title="Plugin delay: "+insert.latencySamples+" samples · compensated"; row.dataset.fxSlotEnabled=String(!insert.bypassed); row.dataset.fxEffective=String(effective); row.classList.toggle("is-active",effective); @@ -1621,6 +1656,7 @@ if (signature===lastPaintedSignature) { // Telemetry often advances without a structural graph revision. paintNativeMeters(next); + if(startupWire)window.queueMicrotask(flushStartupWire); return; } if (!projectNativeGraphWithoutFocusLoss(next)) { @@ -1650,6 +1686,7 @@ ch?.inserts?.find(x=>x.id===p.insertId)?.bypassed; if(actual===p.bypassed)pendingNativeFxPower=null; } + if(startupWire)window.queueMicrotask(flushStartupWire); status((next.productLive?"NATIVE PRODUCT LIVE":"NATIVE PCM GRAPH ACCEPTED · FAT PENDING")+ " · device "+next.device.epoch+ " · graph "+next.graph.revision+" · roster "+next.graph.rosterRevision); @@ -1671,7 +1708,10 @@ state.lastError!=="ACCEPTED_READBACK" && state.lastError!=="NONE" && state.lastError!=="NATIVE_NOT_SUBSCRIBED"; + if(!state.pending&&state.lastError==="ACCEPTED_READBACK"&&startupWire) + window.queueMicrotask(flushStartupWire); if(failed){ + startupWire=null; pendingWireGains.clear(); if(pendingFxInsert?.authority==="CHANNEL_ID"){ pendingFxInsert=null; @@ -2077,6 +2117,15 @@ if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action)) return !["wireExpand","wireSource","wireRoute"].includes(action); if(action==="openPlugin"){ + if(mixerSession()?.authority==="CHANNEL_ID") { + const current=controller?.state()?.current,id=nativeIdFor(t),slot=Number(btn?.dataset.slot); + const insert=current?.graph?.channels.find(ch=>ch.id===id)?.inserts?.[slot]; + if(current?.admitted&&insert?.id&&Number.isInteger(slot)&&slot>=0&&slot<8) { + backend.emitEvent("arMixAction",{action:"routingFxEditor",channelId:id,slot, + instanceId:insert.id,deviceEpoch:current.device.epoch,revision:current.graph.revision}); + } else {discoverFxOnFirstPickerOpen();scope?.openFastPicker?.(t,slot,btn);} + return true; + } const slot=Number(btn?.dataset.slot),instance=verifiedFxFor(t,slot); if(instance){ const ep=safeNativeCounter(hardware?.device?.epoch), @@ -2143,6 +2192,13 @@ }, consumeWire(ops) { if (!connected)return false; + const state=controller?.state(); + // A first drag may arrive before SOURCE's later accepted snapshot. + // Preserve that one operator intent; resolve only against fresh native + // identities, never require a hidden OUT-dropdown priming operation. + if((!flags.acceptedGraphConnected||!state?.current?.admitted||state.pending|| + activeNativeSource||nativeUiSourcePending||pendingNativeSources.size||pendingSourceQueue.size)&& + deferStartupWire(ops))return true; if(Array.isArray(ops)&&ops.length===1&&ops[0].type==="GAIN"){ if(!requestWireGain(ops[0]))status("WIRE gain unavailable · accepted parallel send required"); return true; @@ -2252,14 +2308,14 @@ insertPlugin(id,target){ if(pendingFxInsert){status("FX INSERT · wait for previous native ACK");return true;} const plugin=nativeCatalog.get(id); - const track=scope?.tracks?.find(x=>x.id===target?.channelId); + const track=scope?.tracks?.find(x=>x.id===target?.channelId)|| + (scope?.master?.id===target?.channelId?scope.master:null); const channel=m4Index(track),slot=Number(target?.slot); const accepted=controller?.state().current; const nativeId=nativeIdFor(track); const nativeCh=accepted?.graph?.channels?.find(ch=>ch.id===nativeId); - if(accepted?.admitted && nativeCh && - (channel<0 || legacy()?.nativeBusStructural===true)) { - if(!plugin || !["INPUT","GROUP"].includes(nativeCh.role) || + if(accepted?.admitted && nativeCh) { + if(!plugin || !["INPUT","GROUP","FX_RETURN","MAIN"].includes(nativeCh.role) || !accepted.graph.capabilities.supportedOps.includes("LOAD_INSERT") || !Number.isInteger(slot)||slot<0||slot>=8 || !Array.isArray(nativeCh.inserts)||nativeCh.inserts.length!==slot){ From b89015951897d564fb605ec3dca27145d459e79e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 04:38:55 +0700 Subject: [PATCH 123/219] fix(fx): preserve native rack ownership during catalog refresh --- docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md | 7 ++++++- tests/approved_native_cold_start_smoke.py | 4 ++++ web/approved-native-bridge.js | 3 +++ 3 files changed, 13 insertions(+), 1 deletion(-) diff --git a/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md index fb4aed4f6..4b29e4680 100644 --- a/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md +++ b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md @@ -21,7 +21,12 @@ previously working OUT-dropdown transaction. 4. Clicking an admitted native insert still queried M4's FX array. Editor acquisition now uses exact ChannelId, native PCM revision, slot and opaque instance token. The existing JUCE editor window retains the real owner. -5. A first drag could reach the bridge while SOURCE admission or another +5. Catalog refresh called the M4 FX painter even while ChannelId owned PCM. + Its stale/empty FX array could erase an installed native rack in the GUI, + and equal-revision telemetry would not rebuild it. The M4 painter now + refuses to paint over native authority; a catalog-refresh regression + verifies the accepted name/token survives. +6. A first drag could reach the bridge while SOURCE admission or another native intent was pending. One bounded latest CONNECT/ROUTE_ONLY gesture is retained, requests independent readback and dispatches only after native projection is ready. Epoch changes, changed mapped endpoint identities, diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index a70f9040e..a44ce5b22 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -86,6 +86,10 @@ def main(): ack(page,state,fx) emit(page,'arMixConsoleSnapshot',state) page.wait_for_function("()=>document.getElementById('fastPicker').hidden") + emit(page,'arMixCatalog',{'items':[{'id':'test-vst-64','name':'Latency VST','vendor':'Fixture', + 'category':'EQ','favorite':True}],'scanning':False}) + assert page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST', 'catalog refresh overwrote the accepted native rack' + page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.click() editor=page.evaluate("()=>window.__events.filter(e=>e.payload?.action==='routingFxEditor').at(-1)?.payload") assert editor and editor['channelId']==SOURCE and editor['instanceId']=='g5c-actual' diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 9db95b888..c8bcb59ed 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -855,6 +855,9 @@ scope?.syncFaderVisual?.({...t,level:db}); } function paintM4FxInstances(m) { + // Catalog refresh is metadata, never permission to replace a native + // rack with an inactive compatibility graph's old/empty FX inventory. + if(mixerSession()?.authority==="CHANNEL_ID")return; if(!Array.isArray(m?.fxInstances)||!scope?.tracks)return; for(let lane=0;lane<10;lane++){ const t=scope.tracks.find(x=>x.id===m4TrackIds[lane]); From 2b1ef483ae53626babe9a29b574ad4f41edf371b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 04:45:57 +0700 Subject: [PATCH 124/219] fix(wire): rebase one cold connection after verified stale-revision readback --- docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md | 4 ++- tests/approved_native_cold_start_smoke.py | 25 ++++++++++++---- tests/approved_native_m2_contract.test.cjs | 21 ++++++++++++-- web/approved-native-bridge.js | 33 +++++++++++++++++----- 4 files changed, 66 insertions(+), 17 deletions(-) diff --git a/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md index 4b29e4680..7d86ca6d1 100644 --- a/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md +++ b/docs/P2_COLD_WIRE_NATIVE_VST3_20261107.md @@ -31,7 +31,9 @@ previously working OUT-dropdown transaction. is retained, requests independent readback and dispatches only after native projection is ready. Epoch changes, changed mapped endpoint identities, failure and timeout discard it. No automatic OUT rewrite, output arm or - optimistic wire is introduced. + optimistic wire is introduced. A new CONNECT rejected solely for a stale + native revision receives at most one rebase after independent readback; + removals/retargets, changed epochs and feedback rejection are never retried. ## Fixed-latency VST3 support diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index a44ce5b22..fc2c37a2b 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -62,10 +62,23 @@ def main(): assert route['payload']['changes'][0]['from']==SOURCE assert route['payload']['changes'][0]['to']==RECEIVER assert route['payload']['changes'][0]['op']=='CONNECT' + # Source admission can advance after the GUI's last readback. + # Reject once as stale, independently refresh, then rebase only + # the same explicit connection with a new request ID. + emit(page,'arMixConsoleAck',{'requestId':route['requestId'],'status':'REJECTED', + 'errorCode':'STALE_NATIVE_CONTROL_REVISION','deviceEpoch':state['device']['epoch'], + 'graphRevision':'3','rosterRevision':'3'}) state['graph'].update(revision='3',rosterRevision='3') + emit(page,'arMixConsoleSnapshot',state) + page.wait_for_function('()=>window.__nativeIntents.length===2') + retry=page.evaluate('()=>window.__nativeIntents.at(-1)') + assert retry['baseGraphRevision']=='3' and retry['requestId']!=route['requestId'] + assert retry['payload']==route['payload'] + route=retry + state['graph'].update(revision='4',rosterRevision='4') state['graph']['edges'].append({'edgeId':'9223372036854775810','from':SOURCE,'to':RECEIVER, 'primaryOutput':False,'enabled':True,'gainLinear':1,'tap':'POST_FADER','signalKind':'AUDIO'}) - state['mixerSession'].update(routeRevision='3',rosterRevision='3',channels=copy.deepcopy(state['graph']['channels'])) + state['mixerSession'].update(routeRevision='4',rosterRevision='4',channels=copy.deepcopy(state['graph']['channels'])) ack(page,state,route) emit(page,'arMixConsoleSnapshot',state) page.wait_for_function('()=>!window.__ARMIX_NATIVE_M2__.state().pending') @@ -75,14 +88,14 @@ def main(): 'category':'EQ','favorite':True}],'scanning':False}) page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.click() page.locator('#fastPicker [data-fast-id="test-vst-64"]').click() - page.wait_for_function('()=>window.__nativeIntents.length===2') + page.wait_for_function('()=>window.__nativeIntents.length===3') fx=page.evaluate('()=>window.__nativeIntents.at(-1)') - assert fx['operation']=='LOAD_INSERT' and fx['baseGraphRevision']=='3' + assert fx['operation']=='LOAD_INSERT' and fx['baseGraphRevision']=='4' assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='routingFxInsert')") - state['graph'].update(revision='4',rosterRevision='4') + state['graph'].update(revision='5',rosterRevision='5') state['graph']['channels'][0]['inserts']=[{'id':'g5c-actual','catalogId':'test-vst-64', 'name':'Latency VST','bypassed':False,'latencySamples':64}] - state['mixerSession'].update(routeRevision='4',rosterRevision='4',channels=copy.deepcopy(state['graph']['channels'])) + state['mixerSession'].update(routeRevision='5',rosterRevision='5',channels=copy.deepcopy(state['graph']['channels'])) ack(page,state,fx) emit(page,'arMixConsoleSnapshot',state) page.wait_for_function("()=>document.getElementById('fastPicker').hidden") @@ -93,7 +106,7 @@ def main(): page.locator('#tracks .strip[data-id="1"] .fx-section [data-action="openPlugin"]').first.click() editor=page.evaluate("()=>window.__events.filter(e=>e.payload?.action==='routingFxEditor').at(-1)?.payload") assert editor and editor['channelId']==SOURCE and editor['instanceId']=='g5c-actual' - assert editor['revision']=='4' and 'channel' not in editor + assert editor['revision']=='5' and 'channel' not in editor assert not errors, errors page.screenshot(path=f'native-cold-start-{width}.png') page.close() diff --git a/tests/approved_native_m2_contract.test.cjs b/tests/approved_native_m2_contract.test.cjs index 5c812b804..883ca5fe1 100644 --- a/tests/approved_native_m2_contract.test.cjs +++ b/tests/approved_native_m2_contract.test.cjs @@ -866,7 +866,7 @@ test("M2 code edits approved Pages *events* only, not a second native GUI/audio }); test("M3 native-only Pages scope performs real bridge projection, fader intent and ACK readback",()=>{ - const vm=require("node:vm"),sent=[],listeners=new Map(),timers=[]; + const vm=require("node:vm"),sent=[],listeners=new Map(),timers=[],microtasks=[]; let nextId=100,nextEdgeId=200,paints=0,rollbacks=0; const scope={ tracks:[],master:{id:1,name:"Master"},colors:["#568ead"], @@ -895,7 +895,7 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a }; const window={ __JUCE__:{backend:native},ArSonApprovedNativeContract:protocol, - __ARMIX_NATIVE_SCOPE__:scope,addEventListener(){},setTimeout(fn,ms){timers.push({fn,ms});return timers.length;} + __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"),{ window,document,performance:{now:()=>0},console @@ -978,9 +978,24 @@ test("M3 native-only Pages scope performs real bridge projection, fader intent a assert.equal(window.__ARMIX_NATIVE_M2__.consumeWire([ {type:"CONNECT",sourceId:sourceUi,destId:receiverUi,mode:"send"} ]),true); - const send=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + let send=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; assert.equal(send.payload.changes[0].to,receiver.id); assert.equal(scope.edges.length,0,"INPUT WIRE stays pending until native readback"); + const originalSend=send; + const flushMicro=()=>{while(microtasks.length)microtasks.shift()();}; + listeners.get("arMixConsoleAck")({requestId:send.requestId,status:"REJECTED", + errorCode:"STALE_NATIVE_CONTROL_REVISION",deviceEpoch:ready.device.epoch, + graphRevision:"7",rosterRevision:"8"}); + listeners.get("arMixConsoleSnapshot")(ready);flushMicro(); + assert.equal(sent.findLast(x=>x.name==="arMixConsoleIntent").payload.requestId,originalSend.requestId, + "unchanged snapshot cannot authorize replay"); + const fresh=clone(ready);fresh.graph.rosterRevision="8"; + listeners.get("arMixConsoleSnapshot")(fresh);flushMicro(); + send=sent.findLast(x=>x.name==="arMixConsoleIntent").payload; + assert.notEqual(send.requestId,originalSend.requestId,"new ledger ID for one verified rebase"); + assert.equal(send.baseRosterRevision,"8"); + assert.deepEqual(JSON.parse(JSON.stringify(send.payload)),JSON.parse(JSON.stringify(originalSend.payload))); + listeners.get("arMixConsoleAck")({ requestId:send.requestId,status:"ACCEPTED",errorCode:"NONE", deviceEpoch:ready.device.epoch,graphRevision:"8",rosterRevision:"8" diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index c8bcb59ed..8b28805e3 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -18,15 +18,15 @@ const uiByWireId = new Map(); const pendingWireGains=new Map(); let wireGainFlushQueued=false; - let startupWire=null, startupWireSerial=0; - function deferStartupWire(ops){ + let startupWire=null, startupWireSerial=0, activeWireAttempt=null; + function deferStartupWire(ops,retries=0){ if(!Array.isArray(ops)||ops.length!==1|| !["CONNECT","ROUTE_ONLY"].includes(ops[0].type)||!deviceReady())return false; const current=controller?.state()?.current,op=ops[0]; const epoch=current?.device?.epoch||String(hardware?.device?.epoch||""); if(!/^[1-9][0-9]*$/.test(epoch))return false; const token=++startupWireSerial; - startupWire={ops:ops.map(x=>({...x})),epoch,token, + startupWire={ops:ops.map(x=>({...x})),epoch,token,retries,identity:current?.identity, source:nativeByUiId.get(op.sourceId),destination:nativeByUiId.get(op.destId)}; status("WIRE · completing initial native input admission"); controller?.subscribe(); @@ -42,11 +42,16 @@ if(current?.device?.epoch!==p.epoch){startupWire=null;return;} if(state.pending||activeNativeSource||nativeUiSourcePending|| pendingNativeSources.size||pendingSourceQueue.size|| - !flags.acceptedGraphConnected||!current.admitted)return; + !flags.acceptedGraphConnected||!current?.admitted)return; + if(p.retries&¤t.identity===p.identity)return; // require a later revision before rebasing startupWire=null; if((p.source&&nativeByUiId.get(op.sourceId)!==p.source)|| (p.destination&&nativeByUiId.get(op.destId)!==p.destination))return; - nativeHooks.consumeWire(p.ops); + const from=nativeByUiId.get(op.sourceId),to=nativeByUiId.get(op.destId); + if(op.type==="CONNECT"&¤t.graph.edges.some(e=>e.enabled&&e.from===from&&e.to===to)) { + status("WIRE connected · independently accepted native route");return; + } + nativeHooks.consumeWire(p.ops,p.retries); } let lastPaintedSignature = "",lastNativeTopologySignature = "", @@ -1713,7 +1718,19 @@ state.lastError!=="NATIVE_NOT_SUBSCRIBED"; if(!state.pending&&state.lastError==="ACCEPTED_READBACK"&&startupWire) window.queueMicrotask(flushStartupWire); + if(!state.pending&&state.lastError==="ACCEPTED_READBACK")activeWireAttempt=null; + if(failed&&startupWire?.retries===1&& + ["STALE_NATIVE_CONTROL_REVISION","STALE_NATIVE_WIRE_GRAPH"].includes(state.lastError)) { + window.queueMicrotask(flushStartupWire);return; + } if(failed){ + const wire=activeWireAttempt;activeWireAttempt=null; + // One stale-revision rebase of a new connection only. A fresh + // independent snapshot must still prove device/endpoints. Never + // replay retarget/remove, a changed epoch, or a rejected cycle. + if(wire&&wire.retries===0&& + ["STALE_NATIVE_CONTROL_REVISION","STALE_NATIVE_WIRE_GRAPH"].includes(state.lastError)&& + state.current?.device?.epoch===wire.epoch&&deferStartupWire(wire.ops,1))return; startupWire=null; pendingWireGains.clear(); if(pendingFxInsert?.authority==="CHANNEL_ID"){ @@ -2193,7 +2210,7 @@ } status("NATIVE: "+action+" is not an accepted ChannelId operation");return true; }, - consumeWire(ops) { + consumeWire(ops,retries=0) { if (!connected)return false; const state=controller?.state(); // A first drag may arrive before SOURCE's later accepted snapshot. @@ -2201,7 +2218,7 @@ // identities, never require a hidden OUT-dropdown priming operation. if((!flags.acceptedGraphConnected||!state?.current?.admitted||state.pending|| activeNativeSource||nativeUiSourcePending||pendingNativeSources.size||pendingSourceQueue.size)&& - deferStartupWire(ops))return true; + deferStartupWire(ops,retries))return true; if(Array.isArray(ops)&&ops.length===1&&ops[0].type==="GAIN"){ if(!requestWireGain(ops[0]))status("WIRE gain unavailable · accepted parallel send required"); return true; @@ -2303,6 +2320,8 @@ return true; } const accepted=controller.intent("APPLY_WIRE_TRANSACTION",source,{changes}); + if(accepted.ok&&ops.length===1&&ops[0].type==="CONNECT") + activeWireAttempt={ops:ops.map(x=>({...x})),epoch:current.device.epoch,retries}; if (!accepted.ok)status("NATIVE: "+accepted.error+"; WIRE unchanged"); else window.setTimeout(()=>controller?.expire(accepted.requestId),8000); return true; From 9b86c7dc09a306e5f88e1e123059fa5017d64359 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:14:44 +0700 Subject: [PATCH 125/219] feat(peq): integrate ordered native 8-band EQ with compact SVG editor and DSP ACK --- .github/workflows/ui-smoke.yml | 2 + CMakeLists.txt | 12 +- engine/builtin_fx/BuiltInFxCatalog.h | 32 ++ engine/builtin_fx/ChannelEq.h | 389 +++++++++++++++++++ engine/builtin_fx/ChannelEqProcessor.h | 184 +++++++++ engine/core/LiveChannelFxGraph.h | 12 +- engine/core/RealtimeNativeFxControl.h | 13 + scripts/build_pages.py | 2 + scripts/compose_native_peq.py | 70 ++++ site/preview-v2/assets/mixer-native-peq.css | 76 ++++ site/preview-v2/assets/mixer-native-peq.js | 392 ++++++++++++++++++++ src/LiveAudioEngine.h | 45 +++ src/Main.cpp | 191 +++++++++- tests/builtin_channel_eq_test.cpp | 271 ++++++++++++++ tests/native_peq_assembly_test.py | 53 +++ web/approved-native-bridge.js | 8 +- 16 files changed, 1742 insertions(+), 10 deletions(-) create mode 100644 engine/builtin_fx/BuiltInFxCatalog.h create mode 100644 engine/builtin_fx/ChannelEq.h create mode 100644 engine/builtin_fx/ChannelEqProcessor.h create mode 100644 engine/core/RealtimeNativeFxControl.h create mode 100644 scripts/compose_native_peq.py create mode 100644 site/preview-v2/assets/mixer-native-peq.css create mode 100644 site/preview-v2/assets/mixer-native-peq.js create mode 100644 tests/builtin_channel_eq_test.cpp create mode 100644 tests/native_peq_assembly_test.py diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 8bfbfe055..d4fe8ea82 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -95,6 +95,8 @@ jobs: node --check web/approved-native-bridge.js node --check web/approved-native-contract.js node --check site/preview-v2/assets/gui-perf-probe.js + node --check site/preview-v2/assets/mixer-native-peq.js + python tests/native_peq_assembly_test.py python scripts/build_ui_css.py --check python tests/gui_baseline_lock_test.py - name: Check native UI contracts, workflow policy, and WIRE without Chromium diff --git a/CMakeLists.txt b/CMakeLists.txt index 9e6f1e467..b6286ec9e 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -26,7 +26,9 @@ file(GLOB_RECURSE ARMIX_APPROVED_GUI_SOURCE_INPUTS CONFIGURE_DEPENDS "${CMAKE_CURRENT_SOURCE_DIR}/site/preview-buttons/assets/*") list(APPEND ARMIX_APPROVED_GUI_SOURCE_INPUTS "${CMAKE_CURRENT_SOURCE_DIR}/web/approved-native-bridge.js" - "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_approved_native_gui.py") + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_approved_native_gui.py" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_pages.py" + "${CMAKE_CURRENT_SOURCE_DIR}/scripts/compose_native_peq.py") set_property(DIRECTORY APPEND PROPERTY CMAKE_CONFIGURE_DEPENDS ${ARMIX_APPROVED_GUI_SOURCE_INPUTS}) execute_process( COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/build_approved_native_gui.py" @@ -309,6 +311,14 @@ if(BUILD_TESTING) target_compile_features(ARMixShowStoreTests PRIVATE cxx_std_20) add_test(NAME P4ImmutableNativeShowsAndVendorStateRoundTrip COMMAND ARMixShowStoreTests) + # Eight-band native PEQ: deterministic sweep, stereo isolation, RT no-heap, + # smoothing and Nyquist guards. Built with the existing Windows native lane. + add_executable(ARMixNativeChannelEqTests tests/builtin_channel_eq_test.cpp + engine/builtin_fx/BuiltInFxCatalog.h engine/builtin_fx/ChannelEq.h) + target_compile_features(ARMixNativeChannelEqTests PRIVATE cxx_std_20) + add_test(NAME NativePEQEightBandsRTAndFrequencyResponse COMMAND ARMixNativeChannelEqTests) + add_dependencies(ARMixMixerRoutingTests ARMixNativeChannelEqTests) + add_executable(ARMixNativeMasterLoudnessTests tests/native_master_loudness_test.cpp engine/dsp/NativeMasterLoudness.h) target_compile_features(ARMixNativeMasterLoudnessTests PRIVATE cxx_std_20) add_test(NAME P1KMeasuredNativeBS1770StereoAnd4xTruePeak COMMAND ARMixNativeMasterLoudnessTests) diff --git a/engine/builtin_fx/BuiltInFxCatalog.h b/engine/builtin_fx/BuiltInFxCatalog.h new file mode 100644 index 000000000..23e39acbc --- /dev/null +++ b/engine/builtin_fx/BuiltInFxCatalog.h @@ -0,0 +1,32 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include + +// This is a compile-time catalog of NATIVE effects, not a VST3/FactoryFX manifest. +// Never advertise these as usable in the operator picker until the native PCM +// owner and ACK/snapshot adapter have actually been integrated. +namespace armix::builtin_fx { +inline constexpr std::string_view channelEqId = "armix.builtin.channel-eq.v1"; + +enum class FilterKind : std::uint8_t { highPass, lowShelf, bell, highShelf, lowPass }; +enum class Slope : std::uint8_t { db12 = 12, db24 = 24 }; +struct SlotSpec { + std::string_view id; + FilterKind kind; + float defaultHz; +}; +inline constexpr std::array channelEqSlots{{ + {"hpf", FilterKind::highPass, 80.0f}, + {"low-shelf", FilterKind::lowShelf, 160.0f}, + {"peq-1", FilterKind::bell, 250.0f}, + {"peq-2", FilterKind::bell, 500.0f}, + {"peq-3", FilterKind::bell, 1500.0f}, + {"peq-4", FilterKind::bell, 4500.0f}, + {"high-shelf",FilterKind::highShelf, 9500.0f}, + {"lpf", FilterKind::lowPass, 18000.0f} +}}; +static_assert(channelEqSlots.size() == 8); +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/ChannelEq.h b/engine/builtin_fx/ChannelEq.h new file mode 100644 index 000000000..a900304d8 --- /dev/null +++ b/engine/builtin_fx/ChannelEq.h @@ -0,0 +1,389 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "BuiltInFxCatalog.h" +#include +#include +#include +#include +#include +#include +#include + +// Channel strip EQ for the main native mixer ONLY. Deliberately no JUCE, +// VST3, ArSonEQ, FFT, WebView2, heap allocation or audio callback ownership. +// prepare()/setBand() operate on UNPUBLISHED instances (or in offline tests). +// For live edits, prepareBandEdit() performs all trig on CONTROL; applyPreparedBand() +// performs only bounded copies on the exclusive audio owner at a block boundary. +// No state mutation may race process(), and no UI thread reads live histories. +namespace armix::builtin_fx { +struct Band { + bool enabled = false; + float frequencyHz = 1000.0f; + float gainDb = 0.0f; + float q = 0.70710678f; + Slope slope = Slope::db12; // HPF/LPF only; other types ignore it. +}; + +class ChannelEq final { +public: + static constexpr std::size_t bandCount = channelEqSlots.size(); + static constexpr float maxGainDb = 18.0f; + static constexpr float minQ = 0.2f; + static constexpr float maxQ = 12.0f; + + ChannelEq() noexcept { + for (std::size_t i = 0; i < bandCount; ++i) { + current_.settings[i].frequencyHz = channelEqSlots[i].defaultHz; + current_.settings[i].q = channelEqSlots[i].kind == FilterKind::bell ? 1.0f : 0.70710678f; + } + } + + // CONTROL creates a precomputed change without accessing a live EQ. + // A bounded queue/immutable handoff outside this module transports it to + // the audio owner. sampleRate acts as a device-epoch-independent fence; + // the mixer adapter must ALSO validate ChannelId, epoch, and revision. + struct PreparedBandEdit final { + Band band{}; + std::size_t index=bandCount; + double sampleRate=0.0; + std::array,2> coefficients{}; // b0,b1,b2,a1,a2 + std::uint8_t sections=0; + bool valid=false; + }; + + static bool prepareBandEdit(std::size_t index, const Band& band, + double sampleRate, PreparedBandEdit& output) noexcept { + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || + sampleRate > 384000.0 || + !validBand(index,band,static_cast(std::min(20000.0,sampleRate*0.45)))) + return false; + Slot compiled{}; + if (band.enabled && !makeSlot(channelEqSlots[index].kind,band,sampleRate,compiled)) + return false; + PreparedBandEdit candidate{}; + candidate.band=band; + candidate.index=index; + candidate.sampleRate=sampleRate; + candidate.sections=compiled.count; + for (std::uint8_t i=0;i=bandCount || + edit.sampleRate!=sampleRate_ || + !validBand(edit.index,edit.band,maxFrequencyHz())) return false; + const auto kind=channelEqSlots[edit.index].kind; + const bool cut=kind==FilterKind::highPass||kind==FilterKind::lowPass; + const std::uint8_t expected=edit.band.enabled ? + static_cast(cut && edit.band.slope==Slope::db24 ? 2 : 1) : 0; + if (edit.sections!=expected) return false; + Slot newSlot{}; + newSlot.count=expected; + for(std::uint8_t i=0;i(i); + previous_=current_; + current_=next; + fadeRemaining_=fadeLength_; + return true; + } + + // Prepares without allocating. Enabled filters above the new Nyquist guard + // cause rejection (caller must explicitly choose a safe setting). + bool prepare(double sampleRate) noexcept { + if (!std::isfinite(sampleRate) || sampleRate < 8000.0 || sampleRate > 384000.0) + return false; + const float maxHz = static_cast(std::min(20000.0, sampleRate * 0.45)); + Bank next = current_; + for (std::size_t i = 0; i < bandCount; ++i) { + auto& band = next.settings[i]; + if (!band.enabled) band.frequencyHz = std::min(band.frequencyHz, maxHz); + if (!validBand(i, band, maxHz)) return false; + } + next.activeCount = 0; + for (std::size_t i = 0; i < bandCount; ++i) { + next.slots[i] = Slot{}; + if (next.settings[i].enabled) { + if (!makeSlot(channelEqSlots[i].kind, next.settings[i], sampleRate, next.slots[i])) + return false; + next.active[next.activeCount++] = static_cast(i); + } + } + sampleRate_ = sampleRate; + current_ = next; + previous_ = Bank{}; + fadeLength_ = std::max(1, static_cast(std::round(sampleRate * 0.005))); + fadeRemaining_ = 0; + prepared_ = true; + return true; + } + + // Offline/unpublished convenience, NOT for the live audio callback: + // this computes trigonometric coefficients. Use prepareBandEdit() on the + // CONTROL thread and applyPreparedBand() on AUDIO for live automation. + bool setBand(std::size_t index, const Band& band) noexcept { + if(!prepared_)return false; + PreparedBandEdit edit{}; + return prepareBandEdit(index,band,sampleRate_,edit) && applyPreparedBand(edit); + } + + bool resetToFlat() noexcept { + if (!prepared_) return false; + if (current_.activeCount == 0) return true; + previous_ = current_; + for (std::size_t i = 0; i < bandCount; ++i) { + current_.settings[i].enabled = false; + current_.slots[i] = Slot{}; + } + current_.activeCount = 0; + fadeRemaining_ = fadeLength_; + return true; + } + + [[nodiscard]] Band band(std::size_t index) const noexcept { + return index < bandCount ? current_.settings[index] : Band{}; + } + [[nodiscard]] bool isPrepared() const noexcept { return prepared_; } + [[nodiscard]] double sampleRate() const noexcept { return sampleRate_; } + [[nodiscard]] float maxFrequencyHz() const noexcept { + return static_cast(std::min(20000.0, sampleRate_ * 0.45)); + } + [[nodiscard]] std::size_t activeBands() const noexcept { return current_.activeCount; } + [[nodiscard]] int addedLatencySamples() const noexcept { return 0; } + [[nodiscard]] bool transitioning() const noexcept { + return fadeRemaining_>0 || externalFadeRemaining_>0; + } + // AUDIO-owner-only smooth gate, preserving individual band settings. + void setExternalBypass(bool bypass) noexcept { + const float target=bypass?0.0f:1.0f; + if(target==externalTarget_)return; + externalTarget_=target; + if(current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=target;externalFadeRemaining_=0; + } else externalFadeRemaining_=fadeLength_; + } + + // Processing and all biquad histories are audio-owner exclusive. + // left==right is explicitly one mono buffer, never double processed. + void processStereo(float* left, float* right, std::size_t frames) noexcept { + if (!prepared_ || !left || !right || frames == 0) return; + if (left == right) { processMono(left, frames); return; } + if (current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=externalTarget_;externalFadeRemaining_=0; + return; // exact bitwise bypass + } + + for (std::size_t i = 0; i < frames; ++i) { + const float dryL = left[i], dryR = right[i]; + const float wetL = render(current_, 0, dryL), wetR = render(current_, 1, dryR); + if (fadeRemaining_ > 0) { + const float oldL = render(previous_, 0, dryL); + const float oldR = render(previous_, 1, dryR); + const float mix = 1.0f - static_cast(fadeRemaining_ - 1) / + static_cast(fadeLength_); + const float processedL=oldL+(wetL-oldL)*mix; + const float processedR=oldR+(wetR-oldR)*mix; + const float gate=nextExternalMix(); + left[i]=dryL+(processedL-dryL)*gate; + right[i]=dryR+(processedR-dryR)*gate; + --fadeRemaining_; + } else { + const float gate=nextExternalMix(); + left[i]=dryL+(wetL-dryL)*gate; + right[i]=dryR+(wetR-dryR)*gate; + } + } + clearTiny(current_); + if (fadeRemaining_ != 0) clearTiny(previous_); + } + + void processMono(float* samples, std::size_t frames) noexcept { + if(!prepared_||!samples||frames==0)return; + if(current_.activeCount==0 && fadeRemaining_==0) { + externalWet_=externalTarget_;externalFadeRemaining_=0;return; + } + + for (std::size_t i = 0; i < frames; ++i) { + const float dry = samples[i]; + const float wet = render(current_, 0, dry); + if (fadeRemaining_ > 0) { + const float old = render(previous_, 0, dry); + const float mix = 1.0f - static_cast(fadeRemaining_ - 1) / + static_cast(fadeLength_); + const float processed=old+(wet-old)*mix; + const float gate=nextExternalMix(); + samples[i]=dry+(processed-dry)*gate; + --fadeRemaining_; + } else { + const float gate=nextExternalMix(); + samples[i]=dry+(wet-dry)*gate; + } + } + clearTiny(current_); + if (fadeRemaining_ != 0) clearTiny(previous_); + } + + // Control-side visualization only. Never call while an audio callback is + // mutating this instance. Host should snapshot coefficients off callback. + [[nodiscard]] double responseDb(double frequencyHz) const noexcept { + if (!prepared_ || !std::isfinite(frequencyHz) || frequencyHz <= 0.0 || + frequencyHz >= sampleRate_ * 0.5) return 0.0; + const double w = twoPi * frequencyHz / sampleRate_; + const std::complex z1 = std::polar(1.0, -w); + const auto z2 = z1 * z1; + double result = 0.0; + for (std::uint8_t k = 0; k < current_.activeCount; ++k) { + const auto& s = current_.slots[current_.active[k]]; + for (std::uint8_t j = 0; j < s.count; ++j) { + const auto& c = s.section[j]; + const auto numerator = c.b0 + c.b1 * z1 + c.b2 * z2; + const auto denominator = 1.0 + c.a1 * z1 + c.a2 * z2; + const double mag = std::abs(numerator / denominator); + result += 20.0 * std::log10(std::max(1.0e-12, mag)); + } + } + return std::clamp(result, -160.0, 80.0); + } + +private: + static constexpr double twoPi = 6.283185307179586476925286766559; + struct Section { + double b0=1, b1=0, b2=0, a1=0, a2=0; + double z1[2]{}, z2[2]{}; + float process(int channel, float input) noexcept { + const double x = static_cast(input); + const double out = b0 * x + z1[channel]; + z1[channel] = b1 * x - a1 * out + z2[channel]; + z2[channel] = b2 * x - a2 * out; + return static_cast(out); + } + void denormalGuard() noexcept { + for (int i = 0; i < 2; ++i) { + if (std::abs(z1[i]) < 1.0e-24) z1[i] = 0; + if (std::abs(z2[i]) < 1.0e-24) z2[i] = 0; + } + } + }; + struct Slot { std::array section{}; std::uint8_t count=0; }; + struct Bank { + std::array settings{}; + std::array slots{}; + std::array active{}; + std::uint8_t activeCount=0; + }; + Bank current_{}, previous_{}; + double sampleRate_ = 0.0; + int fadeLength_ = 1, fadeRemaining_ = 0; + float externalWet_=1.0f,externalTarget_=1.0f; + int externalFadeRemaining_=0; + bool prepared_ = false; + float nextExternalMix() noexcept { + if(externalFadeRemaining_>0) { + externalWet_+=(externalTarget_-externalWet_)/ + static_cast(externalFadeRemaining_); + if(--externalFadeRemaining_==0)externalWet_=externalTarget_; + } + return externalWet_; + } + + static bool validBand(std::size_t i, const Band& b, float maxHz) noexcept { + if (i >= bandCount || !std::isfinite(b.frequencyHz) || + !std::isfinite(b.gainDb) || !std::isfinite(b.q) || + b.frequencyHz < 20.0f || b.frequencyHz > maxHz || + b.gainDb < -maxGainDb || b.gainDb > maxGainDb || + b.q < minQ || b.q > maxQ) return false; + return b.slope == Slope::db12 || b.slope == Slope::db24; + } + static bool normalized(Section& s, double b0, double b1, double b2, + double a0, double a1, double a2) noexcept { + if (!std::isfinite(a0) || std::abs(a0) < 1.0e-12) return false; + s.b0 = b0 / a0; s.b1 = b1 / a0; s.b2 = b2 / a0; + s.a1 = a1 / a0; s.a2 = a2 / a0; + return std::isfinite(s.b0) && std::isfinite(s.b1) && std::isfinite(s.b2) && + std::isfinite(s.a1) && std::isfinite(s.a2); + } + static bool makeBiquad(FilterKind kind, const Band& b, double sampleRate, + double q, Section& out) noexcept { + const double omega = twoPi * b.frequencyHz / sampleRate; + const double c = std::cos(omega), s = std::sin(omega); + const double a = std::pow(10.0, static_cast(b.gainDb) / 40.0); + const double alpha = s / (2.0 * q); + switch (kind) { + case FilterKind::bell: + return normalized(out, 1.0+alpha*a, -2.0*c, 1.0-alpha*a, + 1.0+alpha/a, -2.0*c, 1.0-alpha/a); + case FilterKind::highPass: + return normalized(out, (1+c)*0.5, -(1+c), (1+c)*0.5, + 1+alpha, -2*c, 1-alpha); + case FilterKind::lowPass: + return normalized(out, (1-c)*0.5, 1-c, (1-c)*0.5, + 1+alpha, -2*c, 1-alpha); + case FilterKind::lowShelf: { + const double edge = s * std::sqrt(a) * std::sqrt(2.0); + return normalized(out, + a*((a+1)-(a-1)*c+edge), 2*a*((a-1)-(a+1)*c), + a*((a+1)-(a-1)*c-edge), + (a+1)+(a-1)*c+edge, -2*((a-1)+(a+1)*c), + (a+1)+(a-1)*c-edge); + } + case FilterKind::highShelf: { + const double edge = s * std::sqrt(a) * std::sqrt(2.0); + return normalized(out, + a*((a+1)+(a-1)*c+edge), -2*a*((a-1)+(a+1)*c), + a*((a+1)+(a-1)*c-edge), + (a+1)-(a-1)*c+edge, 2*((a-1)-(a+1)*c), + (a+1)-(a-1)*c-edge); + } + } + return false; + } + static bool makeSlot(FilterKind kind, const Band& b, double rate, Slot& result) noexcept { + const bool cut = kind == FilterKind::highPass || kind == FilterKind::lowPass; + result.count = static_cast(cut && b.slope == Slope::db24 ? 2 : 1); + if (result.count == 2) { + return makeBiquad(kind, b, rate, 0.541196100146197, result.section[0]) && + makeBiquad(kind, b, rate, 1.306562964876377, result.section[1]); + } + return makeBiquad(kind, b, rate, cut ? 0.7071067811865476 : b.q, + result.section[0]); + } + static float render(Bank& bank, int channel, float sample) noexcept { + for (std::uint8_t i = 0; i < bank.activeCount; ++i) { + auto& slot = bank.slots[bank.active[i]]; + for (std::uint8_t j = 0; j < slot.count; ++j) + sample = slot.section[j].process(channel, sample); + } + return sample; + } + static void clearTiny(Bank& bank) noexcept { + for (std::uint8_t i = 0; i < bank.activeCount; ++i) { + auto& slot = bank.slots[bank.active[i]]; + for (std::uint8_t j = 0; j < slot.count; ++j) + slot.section[j].denormalGuard(); + } + } +}; +} // namespace armix::builtin_fx diff --git a/engine/builtin_fx/ChannelEqProcessor.h b/engine/builtin_fx/ChannelEqProcessor.h new file mode 100644 index 000000000..8b2a76027 --- /dev/null +++ b/engine/builtin_fx/ChannelEqProcessor.h @@ -0,0 +1,184 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "ChannelEq.h" +#include "../core/RealtimeNativeFxControl.h" +#include +#include +#include +#include +#include +#include + +// One ordinary stereo FX processor in the EXISTING ordered ChannelId rack. +// The established FxInstance owns this processor, per-slot identity, bypass, +// graph latency and retirement. No second callback and no fixed pre-VST bank. +// Single message-thread producer; single audio callback consumer. +namespace armix::builtin_fx { +template class EqSpsc final { +public: + bool push(const T& value) noexcept { + const auto w=write_.load(std::memory_order_relaxed); + if(w-read_.load(std::memory_order_acquire)>=Capacity)return false; + data_[w%Capacity]=value; + write_.store(w+1,std::memory_order_release); + return true; + } + bool pop(T& value) noexcept { + const auto r=read_.load(std::memory_order_relaxed); + if(r==write_.load(std::memory_order_acquire))return false; + value=data_[r%Capacity]; + read_.store(r+1,std::memory_order_release); + return true; + } + bool canPush() const noexcept { + return write_.load(std::memory_order_relaxed)- + read_.load(std::memory_order_acquire) write_{0}; + alignas(64) std::atomic read_{0}; + std::array data_{}; +}; + +class ChannelEqProcessor final : public juce::AudioProcessor, + public armix::mixer::RealtimeNativeFxControl { +public: + static constexpr const char* catalogIdentity="armix.builtin.channel-eq.v1"; + struct Completion { + std::uint64_t requestId=0; + std::uint8_t bandIndex=0; + Band band{}; + bool applied=false; + }; + + ChannelEqProcessor() + : juce::AudioProcessor(BusesProperties() + .withInput("Input",juce::AudioChannelSet::stereo(),true) + .withOutput("Output",juce::AudioChannelSet::stereo(),true)) { + // All 8 defaults are owned by the same DSP definition as the graph. + for(std::size_t i=0;i& pcm,juce::MidiBuffer&) override { + juce::ScopedNoDenormals noDenormals; + if(!ready_||pcm.getNumChannels()<2||pcm.getNumSamples()<=0)return; + consumeRealtimeEdits(); + eq_.processStereo(pcm.getWritePointer(0),pcm.getWritePointer(1), + static_cast(pcm.getNumSamples())); + } + void processBlock(juce::AudioBuffer&,juce::MidiBuffer&) override {} + + // AUDIO thread: bounded one control packet per block. The host calls + // this also when fully bypassed; there is no second callback or worker. + void consumeRealtimeEdits() noexcept override { + Edit next; + if(!ready_||!completion_.canPush()||!queued_.pop(next))return; + const bool ok=eq_.applyPreparedBand(next.prepared); + completion_.push({next.requestId, + static_cast(next.prepared.index),next.prepared.band,ok}); + } + + // Control-thread only. Compiles coefficients off realtime, then publishes + // one bounded block-boundary command. Queued is NOT DSP-applied. + bool queueBand(std::size_t index,const Band& band,std::uint64_t id) noexcept { + if(!ready_||!id||index>=ChannelEq::bandCount)return false; + Edit e;e.requestId=id; + if(!ChannelEq::prepareBandEdit(index,band,rate_,e.prepared)) + return false; + return queued_.push(e); + } + // Control-thread only, after a callback completion: accepted_ is never + // accessed by processBlock, so Show/GUI reads cannot race DSP histories. + bool pollCompletion(Completion& result) noexcept { + if(!completion_.pop(result))return false; + if(result.applied&&result.bandIndex acceptedBands() const noexcept { + return accepted_; // CONTROL thread ONLY + } + double acceptedSampleRate() const noexcept {return rate_;} + bool isReady() const noexcept {return ready_;} + + // The native Show's vendor-state lease already serializes state on the + // control thread. Built-in DSP uses that same per-insert lease and schema, + // not a second fixed channel EQ snapshot. + void getStateInformation(juce::MemoryBlock& destination) override { + juce::MemoryOutputStream output(destination,false); + output.writeInt(0x41504551); // "APEQ" + output.writeInt(1); + for(const auto& b:accepted_) { + output.writeByte(b.enabled?1:0); + output.writeFloat(b.frequencyHz); + output.writeFloat(b.gainDb); + output.writeFloat(b.q); + output.writeByte(static_cast(b.slope)); + } + } + void setStateInformation(const void* data,int size) override { + if(!data||size!=8+static_cast(ChannelEq::bandCount)*14)return; + juce::MemoryInputStream input(data,static_cast(size),false); + if(input.readInt()!=0x41504551||input.readInt()!=1)return; + std::array next{}; + for(auto& b:next){ + b.enabled=input.readByte()!=0; + b.frequencyHz=input.readFloat();b.gainDb=input.readFloat(); + b.q=input.readFloat(); + const auto slope=input.readByte(); + if(slope!=12&&slope!=24)return; + b.slope=slope==24?Slope::db24:Slope::db12; + } + const double rate=rate_>0.?rate_:48000.; + for(std::size_t i=0;i queued_{}; + EqSpsc completion_{}; + std::array accepted_{}; + double rate_=0.; // control-owned immutable after prepare + bool ready_=false; // prepared before graph publication +}; +} // namespace armix::builtin_fx diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index bf9bb31e3..80a877d13 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -3,6 +3,7 @@ #include "PreparedMixerBlock.h" #include "FxBypassEnvelope.h" #include "StereoLatencyDelay.h" +#include "RealtimeNativeFxControl.h" #include #include #include @@ -31,6 +32,7 @@ class LiveChannelFxGraph final { struct FxInstance final : juce::AudioProcessorListener { std::unique_ptr processor; + RealtimeNativeFxControl* nativeControl=nullptr; // bound once OFF realtime juce::MidiBuffer midi; const juce::String catalogId; const juce::String name; @@ -57,7 +59,10 @@ class LiveChannelFxGraph final { if(!dryDelay.prepare(latencySamples))throw std::invalid_argument("VST3 latency exceeds prepared delay budget"); midi.ensureSize(1024); bypassFade.prepare(false,processor?processor->getSampleRate():48000.0,0); - if(processor)processor->addListener(this); + if(processor){ + nativeControl=dynamic_cast(processor.get()); + processor->addListener(this); + } } FxInstance(const FxInstance&)=delete; FxInstance& operator=(const FxInstance&)=delete; @@ -110,6 +115,11 @@ class LiveChannelFxGraph final { processing.clear(std::memory_order_release); return; } + // Drain at most one native EQ control edit even while bypassed. + // Fully bypassed plugins otherwise never call processBlock, which + // would strand pending GUI commands until users turned them ON. + if(nativeControl && bypassFade.fullyBypassed()) + nativeControl->consumeRealtimeEdits(); // Keep bypass at the SAME declared latency as wet, including // rack bypass and disabled slots. PDC never changes on a scalar. for(int i=0;i',probe_tag+'\n',1) canonical_html=apply_authoritative_fx_power(canonical_html) canonical_html=apply_fx_rack_interaction(canonical_html) +canonical_html=apply_native_peq(canonical_html) # Stage C: compile only DEPLOYED copies, never modify locked V28 source # owners or approved PNG artwork. No new CSS/override or second renderer. canonical_html,css_compilation=optimize_assets(canonical_html,buttons_dest/'assets',runtime_bundle=True) diff --git a/scripts/compose_native_peq.py b/scripts/compose_native_peq.py new file mode 100644 index 000000000..1880e1f33 --- /dev/null +++ b/scripts/compose_native_peq.py @@ -0,0 +1,70 @@ +"""One additive native Parametric EQ injection into approved /preview/ assembler. +No alternate GUI, pseudo FX row, fixed pre-VST DSP bank or demo audio engine. +An accepted EQ uses the same rack slot, ChannelId, and FX control as VST3. +""" +CATALOG="armix.builtin.channel-eq.v1" +STYLE='' +SCRIPT='' +PICKER_HEAD="function renderFastPicker(){" +PICKER_FN="""function insertChosenNativeEq(){ + const t=tracks.concat(master).find(x=>x.id===activeFxTarget?.channelId); + const slot=Number(activeFxTarget?.slot); + if(!t||!Number.isInteger(slot)||slot<0||slot>=8){ + say('Parametric EQ · choose an empty FX insert');return false; + } + if(window.__JUCE__?.backend?.emitEvent){ + const bridge=window.__ARMIX_NATIVE_M2__; + if(!bridge?.insertPlugin){ + say('Native FX host not ready · audio unchanged');return false; + } + bridge.insertPlugin('armix.builtin.channel-eq.v1',activeFxTarget); + // The existing native ACK + subsequent accepted snapshot will replace the + // empty slot. Do not optimistically draw an ACTIVE effect or open editor. + return true; + } + if(t.fx[slot]!=='None'){ + say('FX slot already occupied · choose an empty insert');return false; + } + t.fx[slot]='Parametric EQ';t.slotBypass[slot]=false; + t.fxInsertIds[slot]={id:'visual-eq-'+t.id+'-'+slot,name:'Parametric EQ'}; + refreshStrip(t);setFastPicker(false); + say('Parametric EQ · browser visual preview ONLY · no audio DSP'); + return true; +} +function renderFastPicker(){""" +PICKER_RENDER="plugEl('fastResults').innerHTML=list.length?list.map(p=>" +PICKER_RENDER_NEW="""const builtin=!q||['parametric eq','peq','channel eq','built-in fx'].some(n=>n.includes(q))? + '
BUILT-IN FX
':''; + plugEl('fastResults').innerHTML=builtin+'
VST3 PLUGINS
'+(list.length?list.map(p=>""" +PICKER_END=""").join(''):'
No matching effects
';""" +PICKER_END_NEW=""").join(''):'
No matching effects
');""" +PICKER_CLICK=" const btn=e.target.closest('[data-fast-id]');if(btn)insertCatalogPlugin(btn.dataset.fastId);" +PICKER_CLICK_NEW=""" if(e.target.closest('[data-fast-native-eq]')){insertChosenNativeEq();return;} + const btn=e.target.closest('[data-fast-id]');if(btn)insertCatalogPlugin(btn.dataset.fastId);""" +PICKER_ENTER="if(b){e.preventDefault();insertCatalogPlugin(b.dataset.fastId);}" +PICKER_ENTER_NEW="if(b){e.preventDefault();if(b.hasAttribute('data-fast-native-eq'))insertChosenNativeEq();else insertCatalogPlugin(b.dataset.fastId);}" +OPEN=" if(a==='openPlugin'){openFastPicker(t,Number(btn.dataset.slot),btn);return;}" +OPEN_NEW=""" if(a==='openPlugin'){ + const index=Number(btn.dataset.slot); + if(t.fx[index]==='Parametric EQ'){ + window.ArSonMixNativeEq?.open(t,index);return; + } + openFastPicker(t,index,btn);return; + }""" +def apply_native_peq(html: str)->str: + anchors=((PICKER_HEAD,PICKER_FN), + (PICKER_RENDER,PICKER_RENDER_NEW), + (PICKER_END,PICKER_END_NEW), + (PICKER_CLICK,PICKER_CLICK_NEW), + (PICKER_ENTER,PICKER_ENTER_NEW), + (OPEN,OPEN_NEW)) + if html.count('')!=1 or html.count('')!=1 or \ + STYLE in html or SCRIPT in html or 'insertChosenNativeEq' in html: + raise ValueError("Parametric EQ requires one pristine approved compiled GUI") + for before,after in anchors: + if html.count(before)!=1: + raise ValueError('Ambiguous approved picker/editor anchor: '+before[:90]) + html=html.replace(before,after,1) + html=html.replace('',STYLE+'\n',1) + html=html.replace('',SCRIPT+'\n',1) + return html diff --git a/site/preview-v2/assets/mixer-native-peq.css b/site/preview-v2/assets/mixer-native-peq.css new file mode 100644 index 000000000..16af57967 --- /dev/null +++ b/site/preview-v2/assets/mixer-native-peq.css @@ -0,0 +1,76 @@ +/* ArSonMix native Parametric EQ: one scoped owner for the sole /preview/ GUI. + No browser DSP, alternate mixer, heavy compositing filters or global overrides. */ +.mx-peq{position:fixed;top:clamp(20px,11vh,105px);left:clamp(12px,16vw,300px);z-index:3100; + width:min(795px,calc(100vw - 20px));max-height:calc(100dvh - 18px);display:flex;flex-direction:column; + box-sizing:border-box;overflow:hidden;color:#cce1e9;background:#10222d; + border:1px solid #476274;border-radius:9px; + box-shadow:0 18px 48px #050e16b8,0 1px 0 #8ebbc322 inset; + font:400 11px/1.25 Inter,'Segoe UI',sans-serif} +.mx-peq[hidden]{display:none} +.mx-peq *{box-sizing:border-box} +.mx-peq button{font:inherit;color:inherit;border:0;background:none;cursor:pointer} +.mx-peq button:focus-visible,.mx-peq input:focus-visible,.mx-peq [role=slider]:focus-visible{outline:2px solid #92dbea;outline-offset:2px} +.mx-peq-title{display:flex;align-items:center;gap:11px;flex:0 0 36px;height:36px;padding:0 9px 0 15px;cursor:move;touch-action:none;user-select:none; + border-bottom:1px solid #3c5563;background:linear-gradient(#263b47,#172c38)} +.mx-peq-brand{font-size:11px;font-weight:570;color:#e8f4f7;letter-spacing:.025em;white-space:nowrap} +.mx-peq-channel{font-size:10px;color:#81bdcb;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.mx-peq-global{margin-left:auto;font-size:20px!important;width:29px;height:27px;border-radius:4px!important;color:#82d7a7!important} +.mx-peq-close{width:27px;height:27px;border-radius:4px!important;font-size:20px!important;line-height:1!important;color:#aac2cd!important} +.mx-peq-global:hover,.mx-peq-close:hover{background:#ffffff13} +.mx-peq-body{display:grid;grid-template-columns:minmax(0,1fr) 143px;min-height:0;align-items:stretch;flex:0 1 auto} +.mx-peq-graph{min-width:0;background:#0f202b;border-right:1px solid #29404e;overflow:hidden} +.mx-peq-graph>svg{display:block;width:100%;height:auto;aspect-ratio:676/330;max-height:calc(100dvh - 165px);cursor:crosshair;touch-action:none} +.mx-peq-grid{fill:none;stroke:#426077;stroke-width:.65;opacity:.43;vector-effect:non-scaling-stroke} +.mx-peq-zero{fill:none;stroke:#7094a7;stroke-width:1.5;opacity:.8;vector-effect:non-scaling-stroke} +.mx-peq-tick{font:10px Inter,'Segoe UI',sans-serif;fill:#789cac} +.mx-peq-graph circle[data-eq-node]{cursor:grab;touch-action:none} +.mx-peq-graph circle[data-eq-node]:active{cursor:grabbing} +.mx-peq-knobs{background:linear-gradient(145deg,#1d3341,#152937);display:flex;align-items:center;flex-direction:column;gap:3px;padding:8px 5px 7px} +.mx-peq-selection{font:600 10px/1.2 Inter,'Segoe UI',sans-serif;letter-spacing:.035em;min-height:14px} +.mx-peq-knob{display:flex;flex-direction:column;align-items:center;gap:1px;width:100%;min-height:84px} +.mx-peq-knob-label{font-size:9px;color:#a1b7c4;letter-spacing:.085em} +.mx-peq-dial{width:62px;height:62px;outline:none;cursor:ns-resize;touch-action:none} +.mx-peq-dial svg{height:100%;width:100%;display:block} +.mx-peq-needle{stroke:#edf9fe;transform-origin:37px 37px;transform:rotate(var(--turn,-130deg))} +.mx-peq-value{background:transparent;border:0;border-bottom:1px solid transparent;color:#e5f3fa; + font:500 11px/15px Inter,'Segoe UI',sans-serif;text-align:center;outline:none;width:110px;height:18px;min-width:0;border-radius:2px} +.mx-peq-value:hover,.mx-peq-value:focus{border-bottom-color:#82b9cd} +.mx-peq-knob.disabled{opacity:.37} +.mx-peq-knob.disabled .mx-peq-dial{cursor:default} +.mx-peq-bands{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:3px;padding:7px 8px 6px;background:#142a37;border-top:1px solid #354c5a} +.mx-peq-band{--band:#90ccd9;min-width:0;display:flex;align-items:center;justify-content:center;gap:4px; + border:1px solid #2d4556;border-radius:5px;background:#182f3d} +.mx-peq-band.active{border-color:var(--band);background:#263d4b} +.mx-peq-select{display:flex;align-items:center;justify-content:center;gap:3px;min-width:0;flex:1 1 auto; + padding:3px 1px!important;color:var(--band)!important} +.mx-peq-select svg{width:26px;height:19px;flex:0 1 26px} +.mx-peq-select span{font-size:9px;white-space:nowrap;letter-spacing:-.02em} +.mx-peq-band-power{width:19px;height:26px;flex:0 0 19px;font-size:16px!important;color:#667e8b!important} +.mx-peq-band.enabled .mx-peq-band-power{color:var(--band)!important} +.mx-peq-status{padding:6px 11px;min-height:25px;flex:0 0 auto;color:#8facb9; + background:#0c1c26;border-top:1px solid #29404d;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +@media(max-width:650px){ + .mx-peq{left:6px;top:6px;width:calc(100vw - 12px);max-height:calc(100dvh - 12px);overflow-y:auto} + .mx-peq-body{grid-template-columns:minmax(0,1fr) 95px} + .mx-peq-knobs{gap:1px;padding:5px 2px} + .mx-peq-dial{width:48px;height:48px} + .mx-peq-knob{min-height:72px} + .mx-peq-value{width:85px;font-size:10px} + .mx-peq-bands{gap:1px;padding:4px 3px} + .mx-peq-band{gap:0;flex-direction:column} + .mx-peq-select{flex-direction:column} + .mx-peq-select span{font-size:8px} + .mx-peq-band-power{height:18px;width:100%;flex:0 0 18px} +} +@media(max-height:570px){ + .mx-peq{top:5px;max-height:calc(100dvh - 10px);overflow-y:auto} + .mx-peq-title{min-height:31px;height:31px;flex-basis:31px} + .mx-peq-body{grid-template-columns:minmax(0,1fr) 125px} + .mx-peq-graph>svg{max-height:calc(100dvh - 135px)} + .mx-peq-knobs{padding:2px} + .mx-peq-dial{width:45px;height:45px} + .mx-peq-knob{min-height:66px} +} +@media(prefers-reduced-motion:no-preference){ + .mx-peq-band,.mx-peq-dial,.mx-peq-close{transition:background-color .12s ease,border-color .12s ease} +} \ No newline at end of file diff --git a/site/preview-v2/assets/mixer-native-peq.js b/site/preview-v2/assets/mixer-native-peq.js new file mode 100644 index 000000000..b8c779517 --- /dev/null +++ b/site/preview-v2/assets/mixer-native-peq.js @@ -0,0 +1,392 @@ +/* ArSonMix native Parametric EQ — ONE approved /preview/ editor. + * SVG graph represents the same 8 RBJ biquads as engine/builtin_fx/ChannelEq.h. + * In native mode a graph gesture is never "ACTIVE" until audio ACK + readback. + * In static Pages mode interaction is explicitly DEMO, with NO audio engine. */ +(() => { +"use strict"; +const ID="armix.builtin.channel-eq.v1",NS="http://www.w3.org/2000/svg"; +const names=["HPF","LOW SHELF","BELL 1","BELL 2","BELL 3","BELL 4","HIGH SHELF","LPF"]; +const kinds=["hp","ls","bell","bell","bell","bell","hs","lp"]; +const defaults=[80,160,250,500,1500,4500,9500,18000]; +const colors=["#9b91f8","#fb81be","#f8be5c","#9de59e","#5bd6db","#68a9ff","#bc8af2","#ef82ba"]; +const ICONS=["M2 15 C7 15 7 4 14 4 H25","M2 14 H8 Q11 14 13 9 T25 5", +"M2 14 H7 Q10 14 13 6 Q16 0 19 6 T25 14","M2 14 H7 Q10 14 13 6 Q16 0 19 6 T25 14", +"M2 14 H7 Q10 14 13 6 Q16 0 19 6 T25 14","M2 14 H7 Q10 14 13 6 Q16 0 19 6 T25 14", +"M2 15 H9 Q12 15 14 10 T25 4","M2 4 H13 Q19 4 19 15 H25"]; +const clamp=(v,a,b)=>Math.max(a,Math.min(b,v)); +const fresh=()=>defaults.map((f,i)=>({enabled:false,frequencyHz:f,gainDb:0,q:i>=2&&i<=5?1:0.70710678,slope:12})); +const dom=(t,c,txt)=>{const e=document.createElement(t);if(c)e.className=c;if(txt!==undefined)e.textContent=txt;return e}; +const native=()=>Boolean(window.__JUCE__?.backend?.emitEvent); +const backend=()=>window.__JUCE__?.backend; +const state=()=>window.__ARMIX_NATIVE_M2__?.state?.()?.current; +const cap=()=>Math.min(20000,Math.max(20,Math.floor(sampleRate*.45))); +const CUT=i=>i===0||i===7, SHELF=i=>i===1||i===6; +const LOG=Math.log(1000),XL=34,XR=642,YT=21,YB=293,ZO=157,G=18; +const toX=f=>XL+clamp(Math.log(clamp(f,20,20000)/20)/LOG,0,1)*(XR-XL); +const toF=x=>20*Math.exp(clamp((x-XL)/(XR-XL),0,1)*LOG); +const toY=g=>ZO-clamp(g,-G,G)*(ZO-YT)/G; +const toDb=y=>clamp((ZO-y)*G/(ZO-YT),-G,G); +const prettyF=n=>n>=1000?(n/1000).toFixed(n>=10000?1:2).replace(/0+$/,"").replace(/\.$/,"")+"k":String(Math.round(n)); +const db=n=>(n>0?"+":"")+Number(n).toFixed(1); +const valid=(i,b)=>b&&typeof b.enabled==="boolean"&&Number.isFinite(b.frequencyHz)&& + b.frequencyHz>=20&&b.frequencyHz<=cap()&&Number.isFinite(b.gainDb)&&Math.abs(b.gainDb)<=18&& + Number.isFinite(b.q)&&b.q>=.2&&b.q<=12&&(b.slope===12||b.slope===24); +const escape=s=>String(s).replace(/[&<>"']/g,c=>({"&":"&","<":"<",">":">",'"':""","'":"'"}[c])); +// Exact coefficients from native ChannelEq::makeBiquad (same shelf convention). +function coefficient(kind,b,rate,q) { + const w=2*Math.PI*b.frequencyHz/rate,c=Math.cos(w),sin=Math.sin(w), + a=Math.pow(10,b.gainDb/40),al=sin/(2*q),edge=sin*Math.sqrt(a)*Math.SQRT2; + let v; + if(kind==="bell")v=[1+al*a,-2*c,1-al*a,1+al/a,-2*c,1-al/a]; + else if(kind==="hp")v=[(1+c)/2,-(1+c),(1+c)/2,1+al,-2*c,1-al]; + else if(kind==="lp")v=[(1-c)/2,1-c,(1-c)/2,1+al,-2*c,1-al]; + else if(kind==="ls")v=[a*((a+1)-(a-1)*c+edge),2*a*((a-1)-(a+1)*c),a*((a+1)-(a-1)*c-edge),(a+1)+(a-1)*c+edge,-2*((a-1)+(a+1)*c),(a+1)+(a-1)*c-edge]; + else v=[a*((a+1)+(a-1)*c+edge),-2*a*((a-1)+(a+1)*c),a*((a+1)+(a-1)*c-edge),(a+1)-(a-1)*c+edge,2*((a-1)-(a+1)*c),(a+1)-(a-1)*c-edge]; + return [v[0]/v[3],v[1]/v[3],v[2]/v[3],v[4]/v[3],v[5]/v[3]]; +} +const sections=(b,i)=>{ + if(!b.enabled)return []; + const kind=kinds[i]; + return (CUT(i)&&b.slope===24?[.541196100146197,1.306562964876377]:[CUT(i)?Math.SQRT1_2:b.q]) + .map(q=>coefficient(kind,b,sampleRate,q)); +}; +function response(freq,ss){ + const w=2*Math.PI*freq/sampleRate,cos=Math.cos(w),sin=Math.sin(w),c2=Math.cos(2*w),s2=Math.sin(2*w); + let total=0; + for(const a of ss) { + const nr=a[0]+a[1]*cos+a[2]*c2,ni=-(a[1]*sin+a[2]*s2); + const dr=1+a[3]*cos+a[4]*c2,di=-(a[3]*sin+a[4]*s2); + total+=10*Math.log10(Math.max(1e-24,(nr*nr+ni*ni)/Math.max(1e-24,dr*dr+di*di))); + } + return clamp(total,-160,80); +} +let sampleRate=48000,bands=fresh(),selected=2,current=null,gesture=null,draft=null,pending=null, + latest=null,raf=0,lastSend=0,seq=1,readbackRequest="",mode=""; +const demos=new Map(); +const root=dom("section","mx-peq");root.id="mxNativePeq";root.hidden=true;root.setAttribute("role","dialog"); +root.setAttribute("aria-label","ArSonMix Parametric EQ");root.setAttribute("aria-modal","false"); +const head=dom("header","mx-peq-title"),brand=dom("span","mx-peq-brand","ArSonMix / PARAMETRIC EQ"), + channel=dom("span","mx-peq-channel"),power=dom("button","mx-peq-global","⏻"), + close=dom("button","mx-peq-close","×");power.type=close.type="button"; + power.title="Toggle accepted insert bypass";close.title="Close EQ"; + head.append(brand,channel,power,close); +const body=dom("div","mx-peq-body"),graph=dom("div","mx-peq-graph"); +const svg=document.createElementNS(NS,"svg");svg.setAttribute("viewBox","0 0 676 330"); +svg.setAttribute("preserveAspectRatio","none");svg.setAttribute("role","group"); +svg.setAttribute("aria-label","Logarithmic EQ response; drag colored nodes to adjust"); +graph.append(svg); +const side=dom("aside","mx-peq-knobs"),bandName=dom("div","mx-peq-selection","BELL 1"); +side.append(bandName); +const knobs={}; +function makeKnob(key,title) { + const box=dom("div","mx-peq-knob");box.dataset.kind=key; + const lab=dom("span","mx-peq-knob-label",title); + const circle=dom("div","mx-peq-dial");circle.tabIndex=0;circle.setAttribute("role","slider"); + circle.setAttribute("aria-label",title); + circle.innerHTML=''; + const input=dom("input","mx-peq-value");input.type="text";input.inputMode="decimal";input.setAttribute("aria-label",title+" numeric value"); + box.append(lab,circle,input);side.append(box);knobs[key]={box,lab,circle,input}; +} +makeKnob("frequencyHz","FREQ");makeKnob("gainDb","GAIN");makeKnob("q","Q"); +const bar=dom("nav","mx-peq-bands");bar.setAttribute("aria-label","EQ filter bands"); +const controls=[]; +names.forEach((n,i)=>{ + const item=dom("div","mx-peq-band");item.style.setProperty("--band",colors[i]); + const choose=dom("button","mx-peq-select"); + choose.type="button";choose.title=n+" — select filter";choose.setAttribute("aria-label","Select "+n); + choose.innerHTML=''+(i>=2&&i<=5?"P"+(i-1):n==="LOW SHELF"?"LS":n==="HIGH SHELF"?"HS":n)+''; + const toggle=dom("button","mx-peq-band-power","⏻");toggle.type="button"; + toggle.title="Enable or bypass "+n;toggle.setAttribute("aria-label","Toggle "+n); + item.append(choose,toggle);bar.append(item);controls.push({item,choose,toggle}); + choose.addEventListener("click",()=>{selected=i;draft=null;draw()}); + toggle.addEventListener("click",()=>{selected=i;change(i,{enabled:!effective()[i].enabled})}); +}); +const status=dom("footer","mx-peq-status","PREVIEW · NO AUDIO"); +body.append(graph,side);root.append(head,body,bar,status); +function mount(){if(!root.isConnected)document.body.append(root)} +if(document.readyState==="loading")document.addEventListener("DOMContentLoaded",mount,{once:true});else mount(); +const context=()=>{ + if(!native()||!current)return null; + const n=state(),id=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(current.track)|| + n?.graph?.channels?.find(ch=>ch.id===current.channelId)?.id; + const channelId=current.channelId||id; + const insert=n?.graph?.channels?.find(ch=>ch.id===channelId)?.inserts?.[current.slot]; + if(!n?.admitted||!insert||insert.catalogId!==ID||!insert.id|| + (current.instanceId&&insert.id!==current.instanceId))return null; + return {channelId,deviceEpoch:n.device.epoch,graphRevision:n.graph.revision, + instanceId:insert.id,slot:current.slot}; +}; +const effective=()=>draft?.list||bands; +function updateKnobs(){ + const b=effective()[selected],c=context(),enabled=Boolean(c||!native()); + const ch=c?state()?.graph?.channels?.find(x=>x.id===c.channelId):null; + const insert=ch?.inserts?.[c?.slot]; + const fxActive=!native()?!current?.track?.slotBypass?.[current?.slot]: + Boolean(insert && !insert.bypassed && !ch.fxRackBypassed); + power.setAttribute("aria-pressed",String(fxActive)); + power.title=fxActive?"Bypass this EQ insert":"Enable this EQ insert"; + power.style.opacity=fxActive?"1":".5"; + bandName.textContent=names[selected];bandName.style.color=colors[selected]; + for(const [key,k] of Object.entries(knobs)){ + const cut=CUT(selected),disabled=(key==="gainDb"&&cut)||(key==="q"&&SHELF(selected))||(!enabled); + const slope=key==="q"&&cut,val=key==="frequencyHz"?b.frequencyHz:key==="gainDb"?b.gainDb:slope?b.slope:b.q; + k.lab.textContent=slope?"SLOPE":key==="frequencyHz"?"FREQ":key==="gainDb"?"GAIN":"Q"; + k.input.value=key==="frequencyHz"?prettyF(val)+" Hz":key==="gainDb"?db(val)+" dB":slope?val+" dB/oct":val.toFixed(2); + k.circle.setAttribute("aria-disabled",String(disabled));k.box.classList.toggle("disabled",disabled); + k.circle.tabIndex=disabled?-1:0;k.input.disabled=disabled; + let fraction=key==="frequencyHz"?Math.log(val/20)/LOG:key==="gainDb"?(val+18)/36:slope?(val===24?1:0):Math.log(val/.2)/Math.log(60); + fraction=clamp(fraction,0,1); + k.circle.style.setProperty("--turn",(-130+260*fraction)+"deg"); + const arc=k.circle.querySelector(".mx-peq-arc"); + arc.style.stroke=colors[selected];arc.style.strokeDasharray=(182*fraction)+" 182"; + } + controls.forEach(({item,toggle},i)=>{ + item.classList.toggle("active",selected===i); + item.classList.toggle("enabled",effective()[i].enabled); + toggle.setAttribute("aria-pressed",String(effective()[i].enabled)); + }); +} +function paint(){ + if(root.hidden)return; + updateKnobs(); + const values=effective(),compiled=values.map((b,i)=>sections(b,i)),all=compiled.flat(); + const grid=[]; + for(const f of [20,50,100,200,500,1000,2000,5000,10000,20000]){ + const x=toX(f);grid.push(''+(f<1000?f:(f/1000)+"k")+''); + } + for(const dbv of [-18,-12,-6,0,6,12,18]){ + const y=toY(dbv);grid.push(''+(dbv>0?"+":"")+dbv+''); + } + const paths=[],node=[]; + const sample=ss=>{ + let d=""; + for(let t=0;t<=210;t++){ + const x=XL+t*(XR-XL)/210,f=toF(x),dbv=response(Math.min(f,sampleRate*.49),ss); + d+=(t?"L":"M")+x.toFixed(2)+" "+toY(dbv).toFixed(2)+" "; + }return d; + }; + compiled.forEach((ss,i)=>{ + if(!ss.length)return; + const d=sample(ss); + paths.push(''); + paths.push(''); + }); + const combined=sample(all); + paths.push(''); + values.forEach((b,i)=>{ + const x=toX(b.frequencyHz),y=toY(CUT(i)?0:b.gainDb); + if(i===selected)node.push(''); + node.push(''); + node.push(''); + }); + svg.innerHTML=''+ + ''+grid.join("")+ + ''+paths.join("")+node.join("")+''; +} +function draw(){if(raf)cancelAnimationFrame(raf);raf=requestAnimationFrame(()=>{raf=0;paint()})} +function hint(t){status.textContent=t} +function requestSnapshot(){ + const c=context();if(!c)return; + const requestId="eqsnap-"+(Date.now())+"-"+(++seq); + readbackRequest=requestId; + backend().emitEvent("arMixAction",{action:"nativeEqSnapshot",requestId,...c}); +} +function send(i,value){ + const c=context();if(!c)return; + if(pending){latest={index:i,band:value};hint("DSP · APPLYING · FINAL EDIT HELD");return;} + const id="eq-"+String(Date.now()*1000+(seq++%1000)); + pending={id,index:i,band:value,context:c,ack:false}; + backend().emitEvent("arMixAction",{action:"nativeEqSetBand",requestId:id, ...c, + bandIndex:i,band:value}); + hint("DSP · QUEUED — AWAITING AUDIO ACK"); +} +function change(i,patch,preview=false){ + const arr=effective().map(b=>({...b}));const old=arr[i]; + const next={...old,...patch}; + next.frequencyHz=clamp(next.frequencyHz,20,cap()); + next.gainDb=CUT(i)?0:clamp(next.gainDb,-18,18); + next.q=clamp(next.q,.2,12);next.slope=next.slope===24?24:12; + if(!valid(i,next))return; + arr[i]=next;draft={list:arr};draw(); + if(!native()){bands=arr;demos.set(current?.track?.id+":"+current?.slot,arr.map(b=>({...b})));draft=null; + hint("BROWSER PREVIEW · VISUAL ONLY · NO AUDIO");draw();return;} + const now=performance.now(); + if(!preview||now-lastSend>90){lastSend=now;send(i,next);} + else latest={index:i,band:next}; +} +function movePoint(e){ + const r=svg.getBoundingClientRect(); + return {x:(e.clientX-r.left)*676/r.width,y:(e.clientY-r.top)*330/r.height}; +} +svg.addEventListener("pointerdown",e=>{ + const hit=e.target.closest?.("[data-eq-node]");if(!hit||e.button!==0)return; + const i=Number(hit.dataset.eqNode);if(!Number.isInteger(i)||i<0||i>=8)return; + selected=i;const p=movePoint(e),b=effective()[i]; + gesture={id:e.pointerId,kind:"node",index:i,from:p,band:{...b}}; + svg.setPointerCapture(e.pointerId);e.preventDefault();draw(); +}); +svg.addEventListener("pointermove",e=>{ + if(!gesture||gesture.kind!=="node"||gesture.id!==e.pointerId)return; + const p=movePoint(e),g=gesture,scale=e.shiftKey?.18:1; + const dx=(p.x-g.from.x)*scale,dy=(p.y-g.from.y)*scale; + const frequencyHz=clamp(toF(toX(g.band.frequencyHz)+dx),20,cap()); + const gainDb=CUT(g.index)?0:clamp(g.band.gainDb-dy*G/(ZO-YT),-18,18); + change(g.index,{frequencyHz,gainDb,enabled:true},true); + hint(prettyF(frequencyHz)+" Hz · "+db(gainDb)+" dB · Q "+effective()[g.index].q.toFixed(2)); + e.preventDefault(); +}); +function finish(e){ + if(!gesture||gesture.id!==e.pointerId)return; + const g=gesture;gesture=null; + if(g.kind==="node"&&draft){const b=effective()[g.index];change(g.index,b,false)} + else if(g.kind==="knob"&&draft){const b=effective()[selected];change(selected,b,false)} + try{svg.releasePointerCapture?.(e.pointerId)}catch{} +} +svg.addEventListener("pointerup",finish);svg.addEventListener("pointercancel",e=>{gesture=null;draft=null;draw()}); +svg.addEventListener("dblclick",e=>{ + const hit=e.target.closest?.("[data-eq-node]");if(!hit)return; + const i=Number(hit.dataset.eqNode);selected=i; + change(i,fresh()[i]);e.preventDefault(); +}); +svg.addEventListener("wheel",e=>{ + const hit=e.target.closest?.("[data-eq-node]");if(!hit)return; + const i=Number(hit.dataset.eqNode);selected=i;e.preventDefault(); + const b=effective()[i]; + if(CUT(i))change(i,{slope:b.slope===12?24:12,enabled:true}); + else if(!SHELF(i))change(i,{q:clamp(b.q*Math.exp((e.deltaY<0?1:-1)*(e.shiftKey?.025:.09)),.2,12),enabled:true}); +},{passive:false}); +svg.addEventListener("keydown",e=>{ + const hit=e.target.closest?.("[data-eq-node]");if(!hit||!["ArrowLeft","ArrowRight","ArrowUp","ArrowDown"].includes(e.key))return; + const i=Number(hit.dataset.eqNode),b=effective()[i],fine=e.shiftKey?.2:1; + e.preventDefault();selected=i; + const horizontal=e.key==="ArrowLeft"||e.key==="ArrowRight"; + const sign=e.key==="ArrowLeft"||e.key==="ArrowDown"?-1:1; + if(horizontal)change(i,{frequencyHz:b.frequencyHz*Math.exp(sign*.035*fine),enabled:true}); + else if(!CUT(i))change(i,{gainDb:b.gainDb+sign*.2*fine,enabled:true}); +}); +for(const [key,k] of Object.entries(knobs)){ + const adjust=(e,amount)=>{ + const b=effective()[selected],fine=e.shiftKey?.2:1; + if(key==="frequencyHz")change(selected,{frequencyHz:b.frequencyHz*Math.exp(amount*.018*fine),enabled:true},true); + else if(key==="gainDb"&&!CUT(selected))change(selected,{gainDb:b.gainDb+amount*.14*fine,enabled:true},true); + else if(key==="q"&&!SHELF(selected))change(selected,CUT(selected)?{slope:amount<0?12:24,enabled:true}: + {q:b.q*Math.exp(amount*.035*fine),enabled:true},true); + }; + k.circle.addEventListener("pointerdown",e=>{ + if(e.button!==0||k.box.classList.contains("disabled"))return; + gesture={id:e.pointerId,kind:"knob",key,start:e.clientY,last:e.clientY}; + k.circle.setPointerCapture(e.pointerId);e.preventDefault(); + }); + k.circle.addEventListener("pointermove",e=>{ + if(!gesture||gesture.kind!=="knob"||gesture.key!==key||gesture.id!==e.pointerId)return; + const dy=gesture.last-e.clientY;gesture.last=e.clientY;adjust(e,dy);e.preventDefault(); + }); + k.circle.addEventListener("pointerup",e=>{ + if(!gesture||gesture.kind!=="knob"||gesture.key!==key)return; + gesture=null;if(draft)change(selected,effective()[selected],false); + k.circle.releasePointerCapture?.(e.pointerId); + }); + k.circle.addEventListener("pointercancel",()=>{gesture=null;draft=null;draw()}); + k.circle.addEventListener("wheel",e=>{ + if(k.box.classList.contains("disabled"))return;e.preventDefault(); + adjust(e,e.deltaY<0?3:-3); + change(selected,effective()[selected],false); + },{passive:false}); + k.circle.addEventListener("keydown",e=>{ + if(!["ArrowUp","ArrowDown","ArrowLeft","ArrowRight"].includes(e.key))return; + e.preventDefault();adjust(e,e.key==="ArrowUp"||e.key==="ArrowRight"?3:-3); + change(selected,effective()[selected],false); + }); + k.input.addEventListener("change",()=>{ + const value=k.input.value.trim().toLowerCase(); + let raw=Number.parseFloat(value);if(key==="frequencyHz"&&/k(?:hz)?/.test(value))raw*=1000; + if(!Number.isFinite(raw)){draw();return;} + if(key==="frequencyHz")change(selected,{frequencyHz:raw},false); + if(key==="gainDb"&&!CUT(selected))change(selected,{gainDb:raw},false); + if(key==="q"&&!SHELF(selected))change(selected,CUT(selected)?{slope:raw>=18?24:12}:{q:raw},false); + }); +} +let windowGesture=null; +head.addEventListener("pointerdown",e=>{ + if(e.button!==0||e.target.closest("button"))return; + const r=root.getBoundingClientRect(); + windowGesture={id:e.pointerId,x:e.clientX-r.left,y:e.clientY-r.top}; + head.setPointerCapture(e.pointerId);e.preventDefault(); +}); +head.addEventListener("pointermove",e=>{ + if(!windowGesture||windowGesture.id!==e.pointerId)return; + const r=root.getBoundingClientRect(); + root.style.left=clamp(e.clientX-windowGesture.x,0,Math.max(0,innerWidth-r.width))+"px"; + root.style.top=clamp(e.clientY-windowGesture.y,0,Math.max(0,innerHeight-r.height))+"px"; + root.style.transform="none";e.preventDefault(); +}); +head.addEventListener("pointerup",e=>{windowGesture=null;head.releasePointerCapture?.(e.pointerId)}); +head.addEventListener("pointercancel",()=>{windowGesture=null}); +close.addEventListener("click",()=>{root.hidden=true;gesture=null}); +power.addEventListener("click",()=>{ + if(!current)return; + if(native())window.__ARMIX_NATIVE_M2__?.consumeAction?.(current.track,"slotPower",{dataset:{slot:String(current.slot)}}); + else {current.track.slotBypass[current.slot]=!current.track.slotBypass[current.slot]; + window.__ARMIX_NATIVE_EQ_REFRESH__?.(current.track.id);} +}); +window.addEventListener("resize",()=>{ + const r=root.getBoundingClientRect(); + if(!root.hidden&&r.width){root.style.left=clamp(r.left,0,Math.max(0,innerWidth-r.width))+"px"; + root.style.top=clamp(r.top,0,Math.max(0,innerHeight-r.height))+"px";root.style.transform="none";} + draw(); +}); +const api={ + id:ID, + open(track,slot){ + current={track,slot,channelId:null,instanceId:null};selected=2;pending=null;latest=null;draft=null; + const n=state();const nativeId=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(track); + const ch=n?.graph?.channels?.find(x=>x.id===nativeId); + if(native()&&n?.admitted&&ch?.inserts?.[slot]?.catalogId===ID){ + current.channelId=nativeId;current.instanceId=ch.inserts[slot].id; + mode="NATIVE";bands=fresh();sampleRate=48000; + hint("NATIVE · READING ACCEPTED DSP STATE");requestSnapshot(); + }else if(!native()){ + mode="DEMO";bands=(demos.get(track.id+":"+slot)||fresh()).map(b=>({...b})); + sampleRate=48000;hint("BROWSER PREVIEW · NO AUDIO ENGINE"); + }else{mode="UNAVAILABLE";bands=fresh();hint("NATIVE EQ NOT ACCEPTED · CHECK FX SLOT");} + channel.textContent=track.name+" · FX "+(slot+1); + root.hidden=false;draw(); + }, + close(){root.hidden=true;} +}; +window.ArSonMixNativeEq=Object.freeze(api); +backend()?.addEventListener?.("arMixBuiltinEqQueue",ack=>{ + if(!pending||ack?.requestId!==pending.id)return; + if(ack.status==="REJECTED"){pending=null;latest=null;draft=null; + hint("NATIVE REJECTED · "+(ack.errorCode||"UNKNOWN"));requestSnapshot();} +}); +backend()?.addEventListener?.("arMixBuiltinEqAck",ack=>{ + if(!pending||ack?.requestId!==pending.id)return; + if(ack.status!=="APPLIED"){pending=null;latest=null;draft=null; + hint("DSP DID NOT APPLY · "+(ack.errorCode||"UNKNOWN"));requestSnapshot();return;} + pending.ack=true;hint("DSP APPLIED · VERIFYING READBACK");requestSnapshot(); +}); +backend()?.addEventListener?.("arMixBuiltinEqSnapshot",s=>{ + if(!current||!native()||s?.requestId!==readbackRequest)return; + const c=context(); + if(!c||s.status!=="ACCEPTED"||s.channelId!==c.channelId|| + s.instanceId!==c.instanceId||s.deviceEpoch!==c.deviceEpoch|| + s.graphRevision!==c.graphRevision||!Array.isArray(s.bands)|| + s.bands.length!==8 || !Number.isFinite(s.sampleRate)) { + hint("NATIVE EQ STALE OR INVALID SNAPSHOT");return; + } + const rate=sampleRate;sampleRate=s.sampleRate; + if(!s.bands.every((b,i)=>valid(i,b))){sampleRate=rate;hint("NATIVE EQ PARAMETER READBACK INVALID");return;} + if(pending&&(!pending.ack||s.appliedRequestId!==pending.id))return; + bands=s.bands.map(b=>({...b}));pending=null; + if(latest){const update=latest;latest=null;send(update.index,update.band);} + else draft=null; + hint("NATIVE DSP ACCEPTED · "+c.instanceId); + draw(); +}); +backend()?.addEventListener?.("arMixConsoleSnapshot",()=>{ + if(root.hidden||!native()||!current?.instanceId)return; + queueMicrotask(()=>{if(!context()){pending=null;latest=null;draft=null; + hint("DEVICE/GRAPH CHANGED · REOPEN ACCEPTED FX");draw();}}); +}); +})(); \ No newline at end of file diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 61b2d84b0..dac2eb40f 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -9,6 +9,7 @@ #include "LiveDryRoutingLab.h" #include "NativeTopologyEditSafety.h" #include "../engine/dsp/NativeMasterLoudness.h" +#include "../engine/builtin_fx/ChannelEqProcessor.h" #include "DiagnosticTone.h" #include "../engine/device/JuceIndependentClockDevice.h" #include "../engine/device/LiveSecondaryOutputDevice.h" @@ -1476,6 +1477,50 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return rejected; } } + // Native built-in EQ travels through EXACTLY the same ordered FxInstance + // lease, ChannelId graph revision, bypass envelope, and PDC as VST3. + // It is not the legacy fixed pre-VST EQ bank. + LiveDryRoutingLab::NativeBusResult installNativeBuiltInEq( + std::uint64_t ep,std::uint64_t pcmRevision, + std::uint64_t rosterRevision,armix::mixer::ChannelId id) { + LiveDryRoutingLab::NativeBusResult fail{}; + fail.error="NATIVE_EQ_HOST_UNAVAILABLE"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(independent_.active()||!attached_||!device|| + !directFence_.permitted()||secondaryOutput_.armed()|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0|| + routeReconfiguring_.load(std::memory_order_acquire)|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal)return fail; + if(ep!=dryRoutingLab_.epoch()){ + fail.error="NATIVE_EQ_DEVICE_CHANGED";return fail; + } + const auto rate=device->getCurrentSampleRate(); + const int frames=juce::jmax(32,device->getCurrentBufferSizeSamples()); + if(!(rate>=8000. && rate<=384000.)|| + frames>LiveDryRoutingLab::Block::hardFrameLimit) { + fail.error="NATIVE_EQ_UNSUPPORTED_AUDIO_FORMAT";return fail; + } + try { + auto processor=std::make_unique(); + processor->prepareToPlay(rate,frames); + if(!processor->isReady()){ + fail.error="NATIVE_EQ_PREPARE_REJECTED";return fail; + } + auto lease=std::make_shared< + armix::mixer::LiveChannelFxGraph::FxInstance>( + std::move(processor), + juce::String(armix::builtin_fx::ChannelEqProcessor::catalogIdentity), + "Parametric EQ",LiveDryRoutingLab::Block::hardFrameLimit); + return dryRoutingLab_.attachNativeInsert(ep,pcmRevision, + rosterRevision,id, + armix::builtin_fx::ChannelEqProcessor::catalogIdentity, + std::move(lease),true); + } catch(...) { + fail.error="NATIVE_EQ_PREPARE_EXCEPTION";return fail; + } + } + // User-owned VST3 on a true dynamic ChannelId. Instantiation/scan/layout // work is CONTROL only; the callback receives an immutable fx lease. LiveDryRoutingLab::NativeBusResult installNativeVst3( diff --git a/src/Main.cpp b/src/Main.cpp index 8653554f7..87043b72b 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -282,6 +282,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // retained vendor processor lease. No vendor destructor runs on RT. armix::mixer::LiveChannelFxGraph::InstanceLease routedEditorOwner_; std::uint64_t routedEditorEpoch_=0; + struct PendingNativeEq { + armix::mixer::LiveChannelFxGraph::InstanceLease owner; + juce::String request,channelId,deviceEpoch,revision,instanceId; + int slot=-1; + juce::uint32 started=0; + } pendingNativeEq_; + juce::String lastNativeEqRequest_,lastNativeEqInstance_; + juce::String lastNativeEqEpoch_,lastNativeEqRevision_; std::unique_ptr editorWindow_; std::unique_ptr audioSetupWindow_; juce::String startupError_, lastAudioXml_; @@ -900,9 +908,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // fallback, secondary DSP or user-visible MONITOR ritual. const auto args=command.getProperty("payload",{}); const auto catalogId=args.getProperty("catalogId","").toString(); - const auto* plugin=catalog_.find(catalogId); + const bool builtInEq=catalogId== + armix::builtin_fx::ChannelEqProcessor::catalogIdentity; + const auto* plugin=builtInEq?nullptr:catalog_.find(catalogId); std::uint64_t ep=0,rev=0,roster=0,target=0; - if(!plugin||catalog_.busy()||nativeShowBusy_|| + if((!builtInEq&&!plugin)||catalog_.busy()||nativeShowBusy_|| studioBackupBusy_||engine_.isGraphSwitchPending()) { nativeError="NATIVE_VST3_CATALOG_OR_HOST_BUSY"; } else if(!armix::console::approvedNativeId( @@ -915,9 +925,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr command.getProperty("targetChannelId",{}),target)) { nativeError="NATIVE_VST3_INVALID_SESSION_ID"; } else { - const auto result=engine_.installNativeVst3( - ep,rev,roster,armix::mixer::ChannelId{target}, - plugin->path,plugin->uid,plugin->key()); + const auto result=builtInEq? + engine_.installNativeBuiltInEq( + ep,rev,roster,armix::mixer::ChannelId{target}): + engine_.installNativeVst3( + ep,rev,roster,armix::mixer::ChannelId{target}, + plugin->path,plugin->uid,plugin->key()); applied=result.accepted && result.error && result.error[0]==0; if(!applied)nativeError=result.error; @@ -1551,6 +1564,83 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return result; } + // One message-thread owner for native EQ commands/readback. The only + // parameter writer is the existing JUCE callback via ChannelEqProcessor's + // bounded SPSC mailbox. ACK is emitted only AFTER audio consumed the edit. + void emitNativeEqSnapshot(const juce::String& request, + const juce::String& channelId,const juce::String& epoch, + const juce::String& revision,int slot,const juce::String& instanceId, + armix::builtin_fx::ChannelEqProcessor* processor) { + auto reply=std::make_unique(); + reply->setProperty("requestId",request); + reply->setProperty("channelId",channelId); + reply->setProperty("deviceEpoch",epoch); + reply->setProperty("graphRevision",revision); + reply->setProperty("slot",slot); + reply->setProperty("instanceId",instanceId); + reply->setProperty("schemaVersion",1); + reply->setProperty("status",processor?"ACCEPTED":"REJECTED"); + if(processor) { + reply->setProperty("sampleRate",processor->acceptedSampleRate()); + juce::Array bands; + for(const auto& band:processor->acceptedBands()){ + auto item=std::make_unique(); + item->setProperty("enabled",band.enabled); + item->setProperty("frequencyHz",static_cast(band.frequencyHz)); + item->setProperty("gainDb",static_cast(band.gainDb)); + item->setProperty("q",static_cast(band.q)); + item->setProperty("slope",static_cast(band.slope)); + bands.add(juce::var(item.release())); + } + reply->setProperty("bands",juce::var(bands)); + if(instanceId==lastNativeEqInstance_ && + epoch==lastNativeEqEpoch_ && revision==lastNativeEqRevision_) + reply->setProperty("appliedRequestId",lastNativeEqRequest_); + } else reply->setProperty("error","NATIVE_EQ_INSTANCE_OR_REVISION_UNAVAILABLE"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinEqSnapshot",juce::var(reply.release())); + } + + void servicePendingNativeEq() { + if(!pendingNativeEq_.owner)return; + auto* processor=dynamic_cast( + pendingNativeEq_.owner->processor.get()); + if(!processor){pendingNativeEq_={};return;} + armix::builtin_fx::ChannelEqProcessor::Completion completion; + if(!processor->pollCompletion(completion)){ + if(juce::Time::getMillisecondCounter()-pendingNativeEq_.started<3000u) + return; + } + const auto request=pendingNativeEq_.request; + bool applied=completion.applied && completion.requestId && + request=="eq-"+juce::String(std::to_string(completion.requestId)); + // Reject stale graph/device ACKs even if DSP consumed the old command. + const auto snap=approvedNativeSnapshot(); + const auto device=snap.getProperty("device",{}); + const auto graph=snap.getProperty("graph",{}); + applied=applied && pendingNativeEq_.deviceEpoch== + device.getProperty("epoch","").toString() && + pendingNativeEq_.revision== + graph.getProperty("revision","").toString(); + if(applied){ + lastNativeEqRequest_=request; + lastNativeEqInstance_=pendingNativeEq_.instanceId; + lastNativeEqEpoch_=pendingNativeEq_.deviceEpoch; + lastNativeEqRevision_=pendingNativeEq_.revision; + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",pendingNativeEq_.channelId); + ack->setProperty("deviceEpoch",pendingNativeEq_.deviceEpoch); + ack->setProperty("graphRevision",pendingNativeEq_.revision); + ack->setProperty("instanceId",pendingNativeEq_.instanceId); + ack->setProperty("status",applied?"APPLIED":"REJECTED"); + ack->setProperty("errorCode",applied?"NONE":"DSP_EDIT_NOT_APPLIED_OR_STALE"); + pendingNativeEq_={}; + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinEqAck",juce::var(ack.release())); + } + void onAction (const juce::var& args) { const auto action = args.getProperty ("action", {}).toString(); @@ -1565,7 +1655,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr action == "routingFxBypass" || action == "routingNativeFxRackBypass" || action == "routingNativeFxInsertBypass" || - action == "routingFxRackBypass")) + action == "routingFxRackBypass" || + action == "nativeEqSetBand")) { const auto reason=juce::String( "Studio backup in progress. Finish backup before editing saved FX or VST library."); @@ -1629,6 +1720,93 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // G0, before ChannelId admission. Do not send GUI demo parameters // or mutate a second DSP. One control-thread atomic update only. + // Real built-in rack node, not a GUI-only pre-VST channel EQ. + // All identity fields are validated by the accepted native lease. + if(action=="nativeEqSnapshot"||action=="nativeEqSetBand") { + const auto rawChannel=args.getProperty("channelId",{}); + const auto rawEpoch=args.getProperty("deviceEpoch",{}); + const auto rawRevision=args.getProperty("graphRevision",{}); + const auto rawInstance=args.getProperty("instanceId",{}); + const auto request=args.getProperty("requestId",{}).toString(); + const int eqSlot=static_cast(args.getProperty("slot",-1)); + std::uint64_t ch=0,ep=0,rev=0; + const bool valid=armix::console::approvedNativeId(rawChannel,ch)&& + armix::console::approvedNativeId(rawEpoch,ep)&& + armix::console::approvedNativeId(rawRevision,rev)&& + rawInstance.isString()&&rawInstance.toString().isNotEmpty()&& + eqSlot>=0&&eqSlot(eqSlot), + rawInstance.toString()): + armix::mixer::LiveChannelFxGraph::InstanceLease{}; + auto* processor=owner?dynamic_cast( + owner->processor.get()):nullptr; + if(action=="nativeEqSnapshot") { + emitNativeEqSnapshot(request,rawChannel.toString(), + rawEpoch.toString(),rawRevision.toString(), + eqSlot,rawInstance.toString(),processor); + return; + } + const auto bandData=args.getProperty("band",{}); + const int index=static_cast(args.getProperty("bandIndex",-1)); + const auto enabled=bandData.getProperty("enabled",{}); + const auto frequency=bandData.getProperty("frequencyHz",{}); + const auto gain=bandData.getProperty("gainDb",{}); + const auto q=bandData.getProperty("q",{}); + const auto slope=bandData.getProperty("slope",{}); + double f=0.,g=0.,quality=0.; + auto validNumber=[](const juce::var& v,double& d) { + if(!v.isDouble()&&!v.isInt())return false; + d=static_cast(v);return std::isfinite(d); + }; + bool queued=false; + if(processor&&!pendingNativeEq_.owner&&!nativeShowBusy_&&!studioBackupBusy_ && + !engine_.independentClockActive() && index>=0&&index<8 && + enabled.isBool()&&slope.isInt() && + (static_cast(slope)==12||static_cast(slope)==24) && + validNumber(frequency,f)&&validNumber(gain,g)&& + validNumber(q,quality) && request.startsWith("eq-")) { + armix::builtin_fx::Band b; + b.enabled=static_cast(enabled); + b.frequencyHz=static_cast(f); + b.gainDb=static_cast(g); + b.q=static_cast(quality); + b.slope=static_cast(slope)==24? + armix::builtin_fx::Slope::db24:armix::builtin_fx::Slope::db12; + // Id strings are decimal after "eq-", unlike canonical + // ChannelIds; never convert 64-bit ChannelId to JS Number. + const auto wire=request.substring(3).toStdString(); + std::uint64_t numeric=0; + if(!wire.empty()&&wire.size()<=19&& + wire.find_first_not_of("0123456789")==std::string::npos) { + try{numeric=std::stoull(wire);}catch(...){numeric=0;} + } + queued=numeric>0&&processor->queueBand( + static_cast(index),b,numeric); + if(queued) { + pendingNativeEq_.owner=owner; + pendingNativeEq_.request=request; + pendingNativeEq_.channelId=rawChannel.toString(); + pendingNativeEq_.deviceEpoch=rawEpoch.toString(); + pendingNativeEq_.revision=rawRevision.toString(); + pendingNativeEq_.instanceId=rawInstance.toString(); + pendingNativeEq_.slot=eqSlot; + pendingNativeEq_.started=juce::Time::getMillisecondCounter(); + } + } + auto ack=std::make_unique(); + ack->setProperty("requestId",request); + ack->setProperty("channelId",rawChannel); + ack->setProperty("instanceId",rawInstance); + ack->setProperty("status",queued?"QUEUED":"REJECTED"); + ack->setProperty("errorCode",queued?"NONE": + pendingNativeEq_.owner?"EQ_CONTROL_BUSY":"INVALID_OR_STALE_NATIVE_EQ"); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixBuiltinEqQueue",juce::var(ack.release())); + return; + } + // Route the approved channel FX picker to the SAME prepared M4 // graph as physical IN/OUT. ID resolves exclusively in the JUCE // catalog; browser paths/names are never trusted as plugin identity. @@ -3104,6 +3282,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr guiPerf_.prevTickMs = tickStart; } ++timerTicks_; + servicePendingNativeEq(); // A hidden JUCE/WebView2 peer may defer first navigation. Expose the // compositor behind the opaque startup splash after the first tick; // the user sees the completed mixer only after the ready handshake. diff --git a/tests/builtin_channel_eq_test.cpp b/tests/builtin_channel_eq_test.cpp new file mode 100644 index 000000000..bd6c280d4 --- /dev/null +++ b/tests/builtin_channel_eq_test.cpp @@ -0,0 +1,271 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/builtin_fx/ChannelEq.h" +#include +#include +#include +#include +#include +#include +#include +#include + +namespace { +std::atomic noHeap{false}; +[[noreturn]] void fail(const char* test) noexcept { + std::fprintf(stderr, "FAIL: %s\n", test); + std::abort(); +} +void check(bool ok, const char* test) noexcept { if (!ok) fail(test); } +bool near(double actual, double expected, double tolerance) noexcept { + return std::abs(actual-expected) <= tolerance; +} +} // namespace + +// Optional hard tripwire: processing/configuration must never request heap. +void* operator new(std::size_t n) { + if (noHeap.load(std::memory_order_relaxed)) fail("heap allocation in built-in DSP"); + if (auto* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void* operator new[](std::size_t n) { + if (noHeap.load(std::memory_order_relaxed)) fail("heap allocation in built-in DSP[]"); + if (auto* p=std::malloc(n?n:1)) return p; + throw std::bad_alloc(); +} +void operator delete(void* p) noexcept { std::free(p); } +void operator delete[](void* p) noexcept { std::free(p); } +void operator delete(void* p, std::size_t) noexcept { std::free(p); } +void operator delete[](void* p, std::size_t) noexcept { std::free(p); } + +using namespace armix::builtin_fx; +static Band onBand(ChannelEq& eq, std::size_t slot, float freq, float gain=0.0f, + float q=1.0f, Slope slope=Slope::db12) { + Band b=eq.band(slot); + b.enabled=true; b.frequencyHz=freq; b.gainDb=gain; b.q=q; b.slope=slope; + check(eq.setBand(slot,b),"set band accepted"); + return b; +} +static void runUntilSettled(ChannelEq& eq) { + std::array l{},r{}; + while(eq.transitioning())eq.processStereo(l.data(),r.data(),l.size()); +} +static void testCatalogAndDefault() { + check(channelEqId=="armix.builtin.channel-eq.v1","stable built-in ID"); + check(ChannelEq::bandCount==8,"eight slots exactly"); + check(channelEqSlots[0].kind==FilterKind::highPass,"fixed HPF slot"); + check(channelEqSlots[7].kind==FilterKind::lowPass,"fixed LPF slot"); + for(int rate : {44100,48000,96000}) { + ChannelEq eq; + check(eq.prepare(rate),"prepare sample rate"); + check(eq.activeBands()==0,"all filters off on first launch"); + check(eq.addedLatencySamples()==0,"no buffering/lookahead"); + std::array l{},r{}; + for (std::size_t i=0;i(i)*0.001f - 0.05f; + r[i]=1.0f-l[i]; + } + const auto unchangedL=l,unchangedR=r; + eq.processStereo(l.data(),r.data(),l.size()); + check(l==unchangedL&&r==unchangedR,"exact transparent disabled stereo"); + eq.processMono(l.data(),l.size()); + check(l==unchangedL,"exact transparent disabled mono"); + eq.processStereo(nullptr,nullptr,128); + eq.processMono(nullptr,128); + } + ChannelEq lowSample; + check(lowSample.prepare(8000),"8k rate supported"); + check(lowSample.band(7).frequencyHz<=3600.f,"disabled default clamps below Nyquist"); + check(!lowSample.prepare(0)&&!lowSample.prepare(std::numeric_limits::infinity()),"invalid sample rate rejected"); +} +static void testResponse() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + check(near(eq.responseDb(1000),0,1e-10),"off response flat"); + onBand(eq,2,1000,6,1); + check(near(eq.responseDb(1000),6,0.07),"PEQ +6 dB center"); + check(std::abs(eq.responseDb(30))<1,"bell does not affect DC region much"); + onBand(eq,1,160,5,1); + check(eq.responseDb(30)>4,"low shelf +5dB low frequency"); + onBand(eq,6,8000,-5,1); + check(eq.responseDb(15000)<-3,"high shelf attenuates high frequencies"); + ChannelEq cuts; + check(cuts.prepare(48000),"prepare cuts"); + onBand(cuts,0,100,0,.707f,Slope::db12); + const double hpf12=cuts.responseDb(25); + check(hpf12<-22 && hpf12>-29,"HPF 12 dB/oct falloff"); + onBand(cuts,0,100,0,.707f,Slope::db24); + check(cuts.responseDb(25)::infinity(), + std::numeric_limits::quiet_NaN()}) { + auto b=base;b.enabled=true;b.frequencyHz=invalid; + check(!eq.setBand(3,b),"invalid frequency rejected"); + } + auto b=base;b.enabled=true;b.gainDb=21.f; + check(!eq.setBand(3,b),"invalid gain rejected"); + b=base;b.enabled=true;b.q=0.0f; + check(!eq.setBand(3,b),"invalid q rejected"); + b=base;b.enabled=true;b.slope=static_cast(99); + check(!eq.setBand(3,b),"invalid slope rejected"); + check(!eq.setBand(8,base),"invalid slot rejected"); + check(eq.activeBands()==0,"failed writes leave existing state unchanged"); + onBand(eq,2,1000,9); + runUntilSettled(eq); + const auto before=eq.band(2); + auto wrong=before;wrong.frequencyHz=30000; + check(!eq.setBand(2,wrong),"failed update leaves active filter untouched"); + check(eq.band(2).frequencyHz==before.frequencyHz,"readback unchanged on rejected edit"); + check(eq.resetToFlat(),"reset all in one transition"); + runUntilSettled(eq); + check(eq.activeBands()==0 && near(eq.responseDb(1000),0,0.0001),"flat reset"); + check(!eq.transitioning(),"reset fade completed"); +} +static void testAudibleProcessingAndIndependence() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + onBand(eq,2,1000,12,0.7f); + runUntilSettled(eq); + constexpr int n=128; + std::array left{}, right{}; + left[0]=1.0f; + eq.processStereo(left.data(),right.data(),left.size()); + check(left[0]>0.0f,"first sample delivered, no initial buffer/latency"); + check(std::all_of(right.begin(),right.end(),[](float v){return v==0.f;}),"no L->R leakage"); + ChannelEq mono; + check(mono.prepare(48000),"mono prepare"); + onBand(mono,2,1000,12,0.7f); + runUntilSettled(mono); + std::array x{};x[0]=1; + mono.processStereo(x.data(),x.data(),x.size()); // alias -> once only + check(near(x[0],left[0],1e-6),"alias-safe stereo uses mono path once"); + + ChannelEq gate; + check(gate.prepare(48000),"gate prepare"); + onBand(gate,1,160,6,1); + runUntilSettled(gate); + std::array held{};held.fill(1.f); + for(int i=0;i<16;++i) { held.fill(1.f); gate.processMono(held.data(),held.size()); } + check(held.back()>1.7,"actual LF shelf modifies PCM"); + const float previousWet = held.back(); + check(gate.resetToFlat(),"bypass request"); + held.fill(1.f); + gate.processMono(held.data(),held.size()); + check(std::abs(held[0]-previousWet)<0.1f,"start bypass transition follows last wet output"); + check(near(held.back(),1.0,1e-6),"finished bypass returns exact dry PCM"); + check(!gate.transitioning(),"bypass ramp completed"); +} +static void testFourteenIndependentChannels() { + // 10 CH + 4 AUX. Test per-channel filter/history isolation, not 14 EQs + // accidentally chained into a single PCM buffer. + std::array lanes{}; + for(auto& eq:lanes)check(eq.prepare(48000),"14 independent preparations"); + onBand(lanes[0],2,1000,9,0.7f); + runUntilSettled(lanes[0]); + onBand(lanes[13],0,120,0,0.707f,Slope::db24); + runUntilSettled(lanes[13]); + std::array,14> left{},right{}; + std::array reference1000{},reference60{}; + for(unsigned repeat=0;repeat<64;++repeat) { + for(std::size_t i=0;i(repeat*reference1000.size()+i)/48000.0; + reference1000[i]=0.1f*std::sin(6.283185307179586*t*1000.0); + reference60[i]=0.1f*std::sin(6.283185307179586*t*60.0); + } + for(std::size_t lane=0;lane(reference1000[i])*reference1000[i]; + boost1000+=static_cast(left[0][i])*left[0][i]; + dry60+=static_cast(reference60[i])*reference60[i]; + cut60+=static_cast(left[13][i])*left[13][i]; + } + check(boost1000>dry1000*4,"CH01 independent PEQ boost is audible PCM"); + check(cut60 l{},r{}; + l[0]=1.f; + noHeap.store(true,std::memory_order_release); + const bool accepted=eq.applyPreparedBand(packet); + if(accepted)eq.processStereo(l.data(),r.data(),l.size()); + noHeap.store(false,std::memory_order_release); + check(accepted,"audio owner applies precomputed packet"); + check(eq.activeBands()==1&&eq.band(4).gainDb==7.0f,"accepted DSP readback"); + check(l[0]>0.0f,"precomputed audio sample delivered"); + + ChannelEq changedRate; + check(changedRate.prepare(44100),"changed rate instance"); + check(!changedRate.applyPreparedBand(packet),"stale sample rate packet rejected"); + check(changedRate.activeBands()==0,"stale packet no partial application"); + ChannelEq::PreparedBandEdit invalidPacket=packet; + invalidPacket.sections=99; + check(!eq.applyPreparedBand(invalidPacket),"untrusted section count rejected"); + invalidPacket=packet; + invalidPacket.coefficients[0][0]=std::numeric_limits::quiet_NaN(); + // Force meaningful change so duplicate same-state shortcut cannot conceal + // a malformed coefficient payload. + invalidPacket.band.gainDb=8.0f; + check(!eq.applyPreparedBand(invalidPacket),"malformed filter coefficient rejected"); + check(eq.band(4).gainDb==7.0f,"rejected packet does not replace DSP state"); +} +static void testNoHeapAndVariableQuantum() { + ChannelEq eq; + check(eq.prepare(48000),"prepare"); + std::array l{},r{}; + for (auto count : {32u,64u,128u,512u}) { + l.fill(0.12f);r.fill(-0.07f); + auto hp=eq.band(0);hp.enabled=true;hp.frequencyHz=90+static_cast(count)/10.f; + hp.slope=Slope::db24; + ChannelEq::PreparedBandEdit prepared{}; + check(ChannelEq::prepareBandEdit(0,hp,48000,prepared),"control precomputes HPF"); + noHeap.store(true,std::memory_order_release); + const bool ok=eq.applyPreparedBand(prepared); + if(ok)eq.processStereo(l.data(),r.data(),count); + noHeap.store(false,std::memory_order_release); + check(ok,"parameter writes without allocation"); + check(std::isfinite(l[0])&&std::isfinite(l[count-1])&& + std::isfinite(r[count-1]),"variable quantum finite stereo"); + } +} +int main() { + testCatalogAndDefault(); + testResponse(); + testValidationAndReset(); + testAudibleProcessingAndIndependence(); + testPrecomputedControlToAudioBoundary(); + testNoHeapAndVariableQuantum(); + testFourteenIndependentChannels(); + std::puts("PASS: ArSonMix built-in 8-slot native Channel EQ; no ArSonEQ/VST3 dependency"); +} diff --git a/tests/native_peq_assembly_test.py b/tests/native_peq_assembly_test.py new file mode 100644 index 000000000..0acd238bd --- /dev/null +++ b/tests/native_peq_assembly_test.py @@ -0,0 +1,53 @@ +#!/usr/bin/env python3 +"""Native PEQ vertical-integration invariants in the one approved Pages GUI.""" +from pathlib import Path +import sys +import unittest + +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/"scripts")) +from compose_native_peq import apply_native_peq +from approved_fx_rack_power import apply_authoritative_fx_power + +class NativeParametricEqIntegration(unittest.TestCase): + @classmethod + def setUpClass(cls): + cls.original=(ROOT/"site/preview-v2/index.html").read_text("utf-8") + cls.assembled=apply_native_peq(apply_authoritative_fx_power(cls.original)) + + def test_one_authoritative_mixer(self): + self.assertEqual(self.assembled.count("function sectionFx(t){"),1) + self.assertEqual(self.assembled.count("function renderFastPicker(){"),1) + self.assertEqual(self.assembled.count("function insertChosenNativeEq(){"),1) + self.assertEqual(self.assembled.count('id="fastPicker"'),1) + self.assertNotIn("preview-v3",self.assembled) + self.assertEqual(self.assembled.count('src="assets/mixer-native-peq.js?v=eq-graph1"'),1) + + def test_native_rack_uses_regular_insert_slot(self): + self.assertIn("bridge.insertPlugin('armix.builtin.channel-eq.v1',activeFxTarget)",self.assembled) + self.assertIn("if(t.fx[index]==='Parametric EQ')",self.assembled) + # Does not fabricate a second EQ rack row or a special before-VST bank. + self.assertNotIn("builtinEq.slotMarkup",self.assembled) + self.assertNotIn("PRE VST3",self.assembled) + self.assertEqual(self.assembled.count('data-fast-native-eq="1"'),1) + + def test_single_style_owner(self): + self.assertEqual(self.assembled.count('href="assets/mixer-native-peq.css?v=eq-graph1"'),1) + css=(ROOT/"site/preview-v2/assets/mixer-native-peq.css").read_text("utf-8") + self.assertIn(".mx-peq[hidden]{display:none}",css) + self.assertIn("grid-template-columns:minmax(0,1fr) 143px",css) + script=(ROOT/"site/preview-v2/assets/mixer-native-peq.js").read_text("utf-8") + self.assertIn('const LOG=Math.log(1000)',script) + self.assertIn('document.createElementNS(NS,"svg")',script) + self.assertIn('arMixBuiltinEqAck',script) + self.assertNotIn("new AudioContext",script) + + def test_fail_closed_on_repeat(self): + with self.assertRaises(ValueError): + apply_native_peq(self.assembled) + with self.assertRaises(ValueError): + apply_native_peq(self.original.replace("function renderFastPicker(){", + "function renderFastPickerRenamed(){")) + +if __name__=="__main__": + unittest.main() diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index e73947033..5e2f36124 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2162,7 +2162,9 @@ const current=controller?.state()?.current,id=nativeIdFor(t),slot=Number(btn?.dataset.slot); const insert=current?.graph?.channels.find(ch=>ch.id===id)?.inserts?.[slot]; if(current?.admitted&&insert?.id&&Number.isInteger(slot)&&slot>=0&&slot<8) { - backend.emitEvent("arMixAction",{action:"routingFxEditor",channelId:id,slot, + if(insert.catalogId==='armix.builtin.channel-eq.v1') { + window.ArSonMixNativeEq?.open(t,slot); + } else backend.emitEvent("arMixAction",{action:"routingFxEditor",channelId:id,slot, instanceId:insert.id,deviceEpoch:current.device.epoch,revision:current.graph.revision}); } else {discoverFxOnFirstPickerOpen();scope?.openFastPicker?.(t,slot,btn);} return true; @@ -2353,9 +2355,11 @@ const source=all.find(t=>t?.id===sourceId),dest=all.find(t=>t?.id===destId); return !!source&&!!dest&&editNativeFx(source,slot,dest,position,token); }, + nativeIdFor(t){return nativeIdFor(t);}, insertPlugin(id,target){ if(pendingFxInsert){status("FX INSERT · wait for previous native ACK");return true;} - const plugin=nativeCatalog.get(id); + const plugin=nativeCatalog.get(id) || + (id==='armix.builtin.channel-eq.v1'?{id,name:'Parametric EQ'}:null); const track=scope?.tracks?.find(x=>x.id===target?.channelId)|| (scope?.master?.id===target?.channelId?scope.master:null); const channel=m4Index(track),slot=Number(target?.slot); From 6383106a3676f49d348d5f8e00969844fb676403 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:16:18 +0700 Subject: [PATCH 126/219] fix(fx): preserve fresh clicks after rack drag; reconcile latest EQ integration --- scripts/approved_fx_rack_interaction.js | 4 +++- tests/approved_native_fx_edit_smoke.py | 1 - 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/scripts/approved_fx_rack_interaction.js b/scripts/approved_fx_rack_interaction.js index 9a8873852..07ead3b38 100644 --- a/scripts/approved_fx_rack_interaction.js +++ b/scripts/approved_fx_rack_interaction.js @@ -64,6 +64,8 @@ function paintFxPointer(){ } document.addEventListener('pointerdown',e=>{ if(e.button!==0)return; + // A fresh gesture must never inherit suppression of the previous drag's click. + fxPointerSuppressUntil=0; const handle=e.target.closest?.('.fx-grip,.fx-pick:not(.empty)'),row=handle?.closest('.fxslot-row:not(.is-empty)'),t=row&&findTrack(row); if(!row||!t)return;ensureFxInsertIds(t); const slot=Number(row.dataset.slot),token=t.fxInsertIds[slot]?.id;if(!token)return; @@ -111,7 +113,7 @@ document.addEventListener('dragstart',e=>{ if(e.target.closest?.('.fx-grip,.fx-pick')){e.preventDefault();e.stopImmediatePropagation();} },true); document.addEventListener('click',e=>{ - if(performance.now()window.__actions.at(-1)') assert editor['action']=='routingFxEditor' and editor['channelId']==RECEIVER and editor['instanceId']=='actual-a' From fa935fe66347b7b0016d1eb2d34b8ca853728939 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:16:50 +0700 Subject: [PATCH 127/219] fix(peq): preserve approved 18 CSS owners in public and WebView2 assembler --- scripts/compose_native_peq.py | 4 +- site/preview-v2/assets/mixer-fx-rack.css | 77 +++++++++++++++++++++ site/preview-v2/assets/mixer-native-peq.css | 76 -------------------- tests/native_peq_assembly_test.py | 6 +- 4 files changed, 82 insertions(+), 81 deletions(-) delete mode 100644 site/preview-v2/assets/mixer-native-peq.css diff --git a/scripts/compose_native_peq.py b/scripts/compose_native_peq.py index 1880e1f33..0e46d4234 100644 --- a/scripts/compose_native_peq.py +++ b/scripts/compose_native_peq.py @@ -3,7 +3,6 @@ An accepted EQ uses the same rack slot, ChannelId, and FX control as VST3. """ CATALOG="armix.builtin.channel-eq.v1" -STYLE='' SCRIPT='' PICKER_HEAD="function renderFastPicker(){" PICKER_FN="""function insertChosenNativeEq(){ @@ -59,12 +58,11 @@ def apply_native_peq(html: str)->str: (PICKER_ENTER,PICKER_ENTER_NEW), (OPEN,OPEN_NEW)) if html.count('')!=1 or html.count('')!=1 or \ - STYLE in html or SCRIPT in html or 'insertChosenNativeEq' in html: + SCRIPT in html or 'insertChosenNativeEq' in html: raise ValueError("Parametric EQ requires one pristine approved compiled GUI") for before,after in anchors: if html.count(before)!=1: raise ValueError('Ambiguous approved picker/editor anchor: '+before[:90]) html=html.replace(before,after,1) - html=html.replace('',STYLE+'\n',1) html=html.replace('',SCRIPT+'\n',1) return html diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index 694692037..ed435d3be 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -173,3 +173,80 @@ .fxslot-row.fx-drag-ghost.fx-drop-invalid{opacity:.55;} .fx-drop-marker{position:fixed;height:2px;z-index:19999;pointer-events:none;background:#7bc7dc;box-shadow:0 0 4px #7bc7dc66;} .fx-grip{touch-action:none;} + +/* Scoped Parametric EQ plugin visual owner — shares the approved FX component sheet. + The public/native assembler retains its 18 authoritative CSS owners. */ +.mx-peq{position:fixed;top:clamp(20px,11vh,105px);left:clamp(12px,16vw,300px);z-index:3100; + width:min(795px,calc(100vw - 20px));max-height:calc(100dvh - 18px);display:flex;flex-direction:column; + box-sizing:border-box;overflow:hidden;color:#cce1e9;background:#10222d; + border:1px solid #476274;border-radius:9px; + box-shadow:0 18px 48px #050e16b8,0 1px 0 #8ebbc322 inset; + font:400 11px/1.25 Inter,'Segoe UI',sans-serif} +.mx-peq[hidden]{display:none} +.mx-peq *{box-sizing:border-box} +.mx-peq button{font:inherit;color:inherit;border:0;background:none;cursor:pointer} +.mx-peq button:focus-visible,.mx-peq input:focus-visible,.mx-peq [role=slider]:focus-visible{outline:2px solid #92dbea;outline-offset:2px} +.mx-peq-title{display:flex;align-items:center;gap:11px;flex:0 0 36px;height:36px;padding:0 9px 0 15px;cursor:move;touch-action:none;user-select:none; + border-bottom:1px solid #3c5563;background:linear-gradient(#263b47,#172c38)} +.mx-peq-brand{font-size:11px;font-weight:570;color:#e8f4f7;letter-spacing:.025em;white-space:nowrap} +.mx-peq-channel{font-size:10px;color:#81bdcb;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} +.mx-peq-global{margin-left:auto;font-size:20px!important;width:29px;height:27px;border-radius:4px!important;color:#82d7a7!important} +.mx-peq-close{width:27px;height:27px;border-radius:4px!important;font-size:20px!important;line-height:1!important;color:#aac2cd!important} +.mx-peq-global:hover,.mx-peq-close:hover{background:#ffffff13} +.mx-peq-body{display:grid;grid-template-columns:minmax(0,1fr) 143px;min-height:0;align-items:stretch;flex:0 1 auto} +.mx-peq-graph{min-width:0;background:#0f202b;border-right:1px solid #29404e;overflow:hidden} +.mx-peq-graph>svg{display:block;width:100%;height:auto;aspect-ratio:676/330;max-height:calc(100dvh - 165px);cursor:crosshair;touch-action:none} +.mx-peq-grid{fill:none;stroke:#426077;stroke-width:.65;opacity:.43;vector-effect:non-scaling-stroke} +.mx-peq-zero{fill:none;stroke:#7094a7;stroke-width:1.5;opacity:.8;vector-effect:non-scaling-stroke} +.mx-peq-tick{font:10px Inter,'Segoe UI',sans-serif;fill:#789cac} +.mx-peq-graph circle[data-eq-node]{cursor:grab;touch-action:none} +.mx-peq-graph circle[data-eq-node]:active{cursor:grabbing} +.mx-peq-knobs{background:linear-gradient(145deg,#1d3341,#152937);display:flex;align-items:center;flex-direction:column;gap:3px;padding:8px 5px 7px} +.mx-peq-selection{font:600 10px/1.2 Inter,'Segoe UI',sans-serif;letter-spacing:.035em;min-height:14px} +.mx-peq-knob{display:flex;flex-direction:column;align-items:center;gap:1px;width:100%;min-height:84px} +.mx-peq-knob-label{font-size:9px;color:#a1b7c4;letter-spacing:.085em} +.mx-peq-dial{width:62px;height:62px;outline:none;cursor:ns-resize;touch-action:none} +.mx-peq-dial svg{height:100%;width:100%;display:block} +.mx-peq-needle{stroke:#edf9fe;transform-origin:37px 37px;transform:rotate(var(--turn,-130deg))} +.mx-peq-value{background:transparent;border:0;border-bottom:1px solid transparent;color:#e5f3fa; + font:500 11px/15px Inter,'Segoe UI',sans-serif;text-align:center;outline:none;width:110px;height:18px;min-width:0;border-radius:2px} +.mx-peq-value:hover,.mx-peq-value:focus{border-bottom-color:#82b9cd} +.mx-peq-knob.disabled{opacity:.37} +.mx-peq-knob.disabled .mx-peq-dial{cursor:default} +.mx-peq-bands{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:3px;padding:7px 8px 6px;background:#142a37;border-top:1px solid #354c5a} +.mx-peq-band{--band:#90ccd9;min-width:0;display:flex;align-items:center;justify-content:center;gap:4px; + border:1px solid #2d4556;border-radius:5px;background:#182f3d} +.mx-peq-band.active{border-color:var(--band);background:#263d4b} +.mx-peq-select{display:flex;align-items:center;justify-content:center;gap:3px;min-width:0;flex:1 1 auto; + padding:3px 1px!important;color:var(--band)!important} +.mx-peq-select svg{width:26px;height:19px;flex:0 1 26px} +.mx-peq-select span{font-size:9px;white-space:nowrap;letter-spacing:-.02em} +.mx-peq-band-power{width:19px;height:26px;flex:0 0 19px;font-size:16px!important;color:#667e8b!important} +.mx-peq-band.enabled .mx-peq-band-power{color:var(--band)!important} +.mx-peq-status{padding:6px 11px;min-height:25px;flex:0 0 auto;color:#8facb9; + background:#0c1c26;border-top:1px solid #29404d;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} +@media(max-width:650px){ + .mx-peq{left:6px;top:6px;width:calc(100vw - 12px);max-height:calc(100dvh - 12px);overflow-y:auto} + .mx-peq-body{grid-template-columns:minmax(0,1fr) 95px} + .mx-peq-knobs{gap:1px;padding:5px 2px} + .mx-peq-dial{width:48px;height:48px} + .mx-peq-knob{min-height:72px} + .mx-peq-value{width:85px;font-size:10px} + .mx-peq-bands{gap:1px;padding:4px 3px} + .mx-peq-band{gap:0;flex-direction:column} + .mx-peq-select{flex-direction:column} + .mx-peq-select span{font-size:8px} + .mx-peq-band-power{height:18px;width:100%;flex:0 0 18px} +} +@media(max-height:570px){ + .mx-peq{top:5px;max-height:calc(100dvh - 10px);overflow-y:auto} + .mx-peq-title{min-height:31px;height:31px;flex-basis:31px} + .mx-peq-body{grid-template-columns:minmax(0,1fr) 125px} + .mx-peq-graph>svg{max-height:calc(100dvh - 135px)} + .mx-peq-knobs{padding:2px} + .mx-peq-dial{width:45px;height:45px} + .mx-peq-knob{min-height:66px} +} +@media(prefers-reduced-motion:no-preference){ + .mx-peq-band,.mx-peq-dial,.mx-peq-close{transition:background-color .12s ease,border-color .12s ease} +} diff --git a/site/preview-v2/assets/mixer-native-peq.css b/site/preview-v2/assets/mixer-native-peq.css deleted file mode 100644 index 16af57967..000000000 --- a/site/preview-v2/assets/mixer-native-peq.css +++ /dev/null @@ -1,76 +0,0 @@ -/* ArSonMix native Parametric EQ: one scoped owner for the sole /preview/ GUI. - No browser DSP, alternate mixer, heavy compositing filters or global overrides. */ -.mx-peq{position:fixed;top:clamp(20px,11vh,105px);left:clamp(12px,16vw,300px);z-index:3100; - width:min(795px,calc(100vw - 20px));max-height:calc(100dvh - 18px);display:flex;flex-direction:column; - box-sizing:border-box;overflow:hidden;color:#cce1e9;background:#10222d; - border:1px solid #476274;border-radius:9px; - box-shadow:0 18px 48px #050e16b8,0 1px 0 #8ebbc322 inset; - font:400 11px/1.25 Inter,'Segoe UI',sans-serif} -.mx-peq[hidden]{display:none} -.mx-peq *{box-sizing:border-box} -.mx-peq button{font:inherit;color:inherit;border:0;background:none;cursor:pointer} -.mx-peq button:focus-visible,.mx-peq input:focus-visible,.mx-peq [role=slider]:focus-visible{outline:2px solid #92dbea;outline-offset:2px} -.mx-peq-title{display:flex;align-items:center;gap:11px;flex:0 0 36px;height:36px;padding:0 9px 0 15px;cursor:move;touch-action:none;user-select:none; - border-bottom:1px solid #3c5563;background:linear-gradient(#263b47,#172c38)} -.mx-peq-brand{font-size:11px;font-weight:570;color:#e8f4f7;letter-spacing:.025em;white-space:nowrap} -.mx-peq-channel{font-size:10px;color:#81bdcb;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} -.mx-peq-global{margin-left:auto;font-size:20px!important;width:29px;height:27px;border-radius:4px!important;color:#82d7a7!important} -.mx-peq-close{width:27px;height:27px;border-radius:4px!important;font-size:20px!important;line-height:1!important;color:#aac2cd!important} -.mx-peq-global:hover,.mx-peq-close:hover{background:#ffffff13} -.mx-peq-body{display:grid;grid-template-columns:minmax(0,1fr) 143px;min-height:0;align-items:stretch;flex:0 1 auto} -.mx-peq-graph{min-width:0;background:#0f202b;border-right:1px solid #29404e;overflow:hidden} -.mx-peq-graph>svg{display:block;width:100%;height:auto;aspect-ratio:676/330;max-height:calc(100dvh - 165px);cursor:crosshair;touch-action:none} -.mx-peq-grid{fill:none;stroke:#426077;stroke-width:.65;opacity:.43;vector-effect:non-scaling-stroke} -.mx-peq-zero{fill:none;stroke:#7094a7;stroke-width:1.5;opacity:.8;vector-effect:non-scaling-stroke} -.mx-peq-tick{font:10px Inter,'Segoe UI',sans-serif;fill:#789cac} -.mx-peq-graph circle[data-eq-node]{cursor:grab;touch-action:none} -.mx-peq-graph circle[data-eq-node]:active{cursor:grabbing} -.mx-peq-knobs{background:linear-gradient(145deg,#1d3341,#152937);display:flex;align-items:center;flex-direction:column;gap:3px;padding:8px 5px 7px} -.mx-peq-selection{font:600 10px/1.2 Inter,'Segoe UI',sans-serif;letter-spacing:.035em;min-height:14px} -.mx-peq-knob{display:flex;flex-direction:column;align-items:center;gap:1px;width:100%;min-height:84px} -.mx-peq-knob-label{font-size:9px;color:#a1b7c4;letter-spacing:.085em} -.mx-peq-dial{width:62px;height:62px;outline:none;cursor:ns-resize;touch-action:none} -.mx-peq-dial svg{height:100%;width:100%;display:block} -.mx-peq-needle{stroke:#edf9fe;transform-origin:37px 37px;transform:rotate(var(--turn,-130deg))} -.mx-peq-value{background:transparent;border:0;border-bottom:1px solid transparent;color:#e5f3fa; - font:500 11px/15px Inter,'Segoe UI',sans-serif;text-align:center;outline:none;width:110px;height:18px;min-width:0;border-radius:2px} -.mx-peq-value:hover,.mx-peq-value:focus{border-bottom-color:#82b9cd} -.mx-peq-knob.disabled{opacity:.37} -.mx-peq-knob.disabled .mx-peq-dial{cursor:default} -.mx-peq-bands{display:grid;grid-template-columns:repeat(8,minmax(0,1fr));gap:3px;padding:7px 8px 6px;background:#142a37;border-top:1px solid #354c5a} -.mx-peq-band{--band:#90ccd9;min-width:0;display:flex;align-items:center;justify-content:center;gap:4px; - border:1px solid #2d4556;border-radius:5px;background:#182f3d} -.mx-peq-band.active{border-color:var(--band);background:#263d4b} -.mx-peq-select{display:flex;align-items:center;justify-content:center;gap:3px;min-width:0;flex:1 1 auto; - padding:3px 1px!important;color:var(--band)!important} -.mx-peq-select svg{width:26px;height:19px;flex:0 1 26px} -.mx-peq-select span{font-size:9px;white-space:nowrap;letter-spacing:-.02em} -.mx-peq-band-power{width:19px;height:26px;flex:0 0 19px;font-size:16px!important;color:#667e8b!important} -.mx-peq-band.enabled .mx-peq-band-power{color:var(--band)!important} -.mx-peq-status{padding:6px 11px;min-height:25px;flex:0 0 auto;color:#8facb9; - background:#0c1c26;border-top:1px solid #29404d;font-size:10px;white-space:nowrap;overflow:hidden;text-overflow:ellipsis} -@media(max-width:650px){ - .mx-peq{left:6px;top:6px;width:calc(100vw - 12px);max-height:calc(100dvh - 12px);overflow-y:auto} - .mx-peq-body{grid-template-columns:minmax(0,1fr) 95px} - .mx-peq-knobs{gap:1px;padding:5px 2px} - .mx-peq-dial{width:48px;height:48px} - .mx-peq-knob{min-height:72px} - .mx-peq-value{width:85px;font-size:10px} - .mx-peq-bands{gap:1px;padding:4px 3px} - .mx-peq-band{gap:0;flex-direction:column} - .mx-peq-select{flex-direction:column} - .mx-peq-select span{font-size:8px} - .mx-peq-band-power{height:18px;width:100%;flex:0 0 18px} -} -@media(max-height:570px){ - .mx-peq{top:5px;max-height:calc(100dvh - 10px);overflow-y:auto} - .mx-peq-title{min-height:31px;height:31px;flex-basis:31px} - .mx-peq-body{grid-template-columns:minmax(0,1fr) 125px} - .mx-peq-graph>svg{max-height:calc(100dvh - 135px)} - .mx-peq-knobs{padding:2px} - .mx-peq-dial{width:45px;height:45px} - .mx-peq-knob{min-height:66px} -} -@media(prefers-reduced-motion:no-preference){ - .mx-peq-band,.mx-peq-dial,.mx-peq-close{transition:background-color .12s ease,border-color .12s ease} -} \ No newline at end of file diff --git a/tests/native_peq_assembly_test.py b/tests/native_peq_assembly_test.py index 0acd238bd..715a50f13 100644 --- a/tests/native_peq_assembly_test.py +++ b/tests/native_peq_assembly_test.py @@ -32,8 +32,10 @@ def test_native_rack_uses_regular_insert_slot(self): self.assertEqual(self.assembled.count('data-fast-native-eq="1"'),1) def test_single_style_owner(self): - self.assertEqual(self.assembled.count('href="assets/mixer-native-peq.css?v=eq-graph1"'),1) - css=(ROOT/"site/preview-v2/assets/mixer-native-peq.css").read_text("utf-8") + # The approved CSS compiler requires exactly 18 component-owner links. + # Native EQ styles live within the existing FX rack owner, not a 19th link. + self.assertNotIn('href="assets/mixer-native-peq.css',self.assembled) + css=(ROOT/"site/preview-v2/assets/mixer-fx-rack.css").read_text("utf-8") self.assertIn(".mx-peq[hidden]{display:none}",css) self.assertIn("grid-template-columns:minmax(0,1fr) 143px",css) script=(ROOT/"site/preview-v2/assets/mixer-native-peq.js").read_text("utf-8") From 31d3cc23898956d5973fdc63eff74fb742fe006d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:18:48 +0700 Subject: [PATCH 128/219] fix(peq): preserve public/native GUI contract and verify assembled source parity --- scripts/compose_native_peq.py | 6 +++--- site/preview-v2/assets/mixer-native-peq.js | 5 +++++ tests/native_peq_assembly_test.py | 3 ++- tests/single_preview_publication_contract_test.py | 2 ++ 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/scripts/compose_native_peq.py b/scripts/compose_native_peq.py index 0e46d4234..07706e92b 100644 --- a/scripts/compose_native_peq.py +++ b/scripts/compose_native_peq.py @@ -12,11 +12,11 @@ say('Parametric EQ · choose an empty FX insert');return false; } if(window.__JUCE__?.backend?.emitEvent){ - const bridge=window.__ARMIX_NATIVE_M2__; - if(!bridge?.insertPlugin){ + const host=window.ArSonMixNativeEq; + if(!host?.insert){ say('Native FX host not ready · audio unchanged');return false; } - bridge.insertPlugin('armix.builtin.channel-eq.v1',activeFxTarget); + host.insert(activeFxTarget); // The existing native ACK + subsequent accepted snapshot will replace the // empty slot. Do not optimistically draw an ACTIVE effect or open editor. return true; diff --git a/site/preview-v2/assets/mixer-native-peq.js b/site/preview-v2/assets/mixer-native-peq.js index b8c779517..2a37edc08 100644 --- a/site/preview-v2/assets/mixer-native-peq.js +++ b/site/preview-v2/assets/mixer-native-peq.js @@ -337,6 +337,11 @@ window.addEventListener("resize",()=>{ }); const api={ id:ID, + // Public catalog delegates insertion to this one native-only bridge method. + // The public Pages HTML contains no native authority or private bridge name. + insert(target){ + return Boolean(window.__ARMIX_NATIVE_M2__?.insertPlugin?.(ID,target)); + }, open(track,slot){ current={track,slot,channelId:null,instanceId:null};selected=2;pending=null;latest=null;draft=null; const n=state();const nativeId=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(track); diff --git a/tests/native_peq_assembly_test.py b/tests/native_peq_assembly_test.py index 715a50f13..f3d3dd576 100644 --- a/tests/native_peq_assembly_test.py +++ b/tests/native_peq_assembly_test.py @@ -24,7 +24,8 @@ def test_one_authoritative_mixer(self): self.assertEqual(self.assembled.count('src="assets/mixer-native-peq.js?v=eq-graph1"'),1) def test_native_rack_uses_regular_insert_slot(self): - self.assertIn("bridge.insertPlugin('armix.builtin.channel-eq.v1',activeFxTarget)",self.assembled) + self.assertIn("host.insert(activeFxTarget)",self.assembled) + self.assertNotIn("__ARMIX_NATIVE_M2__",self.assembled) self.assertIn("if(t.fx[index]==='Parametric EQ')",self.assembled) # Does not fabricate a second EQ rack row or a special before-VST bank. self.assertNotIn("builtinEq.slotMarkup",self.assembled) diff --git a/tests/single_preview_publication_contract_test.py b/tests/single_preview_publication_contract_test.py index 6bea191a3..e6830ab19 100644 --- a/tests/single_preview_publication_contract_test.py +++ b/tests/single_preview_publication_contract_test.py @@ -5,6 +5,7 @@ from compile_approved_css import LINK, optimize_css, compile_runtime_bundle, link_runtime_bundle, RUNTIME_CSS from approved_fx_rack_power import apply_authoritative_fx_power from approved_fx_rack_interaction import apply_fx_rack_interaction +from compose_native_peq import apply_native_peq ROOT=Path(__file__).resolve().parents[1] DST=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else ROOT/'dist-pages' gui=DST/'preview' @@ -40,6 +41,7 @@ def require(ok,why): 'opt-in performance probe was not copied byte-for-byte') expected=apply_authoritative_fx_power(expected) expected=apply_fx_rack_interaction(expected) +expected=apply_native_peq(expected) # Stage C: the source HTML remains byte-exact, but the 18 deployed CSS files # contain only proven cascade winners. Verify every *generated* byte and query # hash; never approve an extra stylesheet, different owner or PNG mutation. From e99032d0b88274fc486e7b31acf2df738a6cc64f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:22:12 +0700 Subject: [PATCH 129/219] fix(css): distinguish responsive conditions in ownership gate using publisher parser --- scripts/check_preview_css_ownership.py | 34 ++++++++----------- ...ed_preview_css_owner_nonregression_test.py | 15 ++++++-- 2 files changed, 26 insertions(+), 23 deletions(-) diff --git a/scripts/check_preview_css_ownership.py b/scripts/check_preview_css_ownership.py index 4b47f85f8..a26d4eb29 100644 --- a/scripts/check_preview_css_ownership.py +++ b/scripts/check_preview_css_ownership.py @@ -15,6 +15,9 @@ import json from pathlib import Path import re +import sys +sys.path.insert(0,str(Path(__file__).resolve().parent)) +from compile_approved_css import _declarations ROOT = Path(__file__).resolve().parents[1] PAGE = ROOT / "site/preview-v2/index.html" @@ -63,29 +66,20 @@ def inspect() -> tuple[list[str], dict[str, list[str]]]: return names, dict(sorted(overlap.items())) +def same_context_repeat_count(css: str) -> int: + """Reuse the publisher parser: media/support/layer scopes are distinct keys.""" + keys = [declaration.key for declaration in _declarations(css, "ownership")] + return len(keys) - len(set(keys)) + + def count_same_file_repeated_declarations(names: list[str]) -> dict[str, int]: - """Conservative same-file stacking counter; CSS context still needs QA. + """Reject repeated declarations within the same selector and CSS context. - An identical normalized selector + property repeated later in the same - owner is debt even if the current cascade intentionally uses it. New debt - is not permitted, but removing existing duplicate declarations is. + Responsive variants are separate conditions, not late unconditional stacks. + Existing caps remain upper bounds; no baseline debt is increased. """ - totals: dict[str, int] = {} - for name in names: - css = COMMENT.sub("", source_path(name).read_text(encoding="utf-8")) - seen: set[str] = set() - repeated = 0 - for match in LEAF.finditer(css): - selector = " ".join(match.group(1).split()) - if not selector or selector.startswith("@"): - continue - for prop in PROP.finditer(match.group(2)): - key = selector + "||" + prop.group(1) - if key in seen: - repeated += 1 - seen.add(key) - totals[name] = repeated - return totals + return {name: same_context_repeat_count(source_path(name).read_text(encoding="utf-8")) + for name in names} def verify() -> dict: diff --git a/tests/approved_preview_css_owner_nonregression_test.py b/tests/approved_preview_css_owner_nonregression_test.py index c27dcd856..2926362b5 100644 --- a/tests/approved_preview_css_owner_nonregression_test.py +++ b/tests/approved_preview_css_owner_nonregression_test.py @@ -18,7 +18,7 @@ def test_approved_png_owner_and_locked_cross_file_stack(self): self.assertEqual(result["crossOwnerBaseline"], 114) self.assertEqual(result["newCrossOwnerConflicts"], 0) self.assertEqual(result["sameOwnerRepeatedBaseline"], 252) - self.assertEqual(result["sameOwnerRepeatedCurrent"], 252) + self.assertLessEqual(result["sameOwnerRepeatedCurrent"], 252) self.assertEqual(result["newSameOwnerStacking"], 0) self.assertTrue(str(OWNER.source_path("mixer-control-keys.css")) .endswith("site/preview-buttons/assets/mixer-control-keys.css")) @@ -47,7 +47,7 @@ def test_new_same_file_stack_is_rejected_without_visual_patch(self): names, _ = OWNER.inspect() present = OWNER.count_same_file_repeated_declarations(names) invented = dict(present) - invented["mixer-fader-assembly.css"] += 1 + invented["mixer-fader-assembly.css"] = 10000 with patch.object(OWNER, "count_same_file_repeated_declarations", return_value=invented): with self.assertRaisesRegex(ValueError, "NEW SAME-OWNER"): @@ -62,7 +62,16 @@ def test_deleting_existing_same_file_duplicates_is_allowed(self): return_value=reduced): result = OWNER.verify() self.assertEqual(result["newSameOwnerStacking"], 0) - self.assertEqual(result["sameOwnerRepeatedCurrent"], 251) + self.assertEqual(result["sameOwnerRepeatedCurrent"], sum(present.values())-1) + + def test_media_context_is_distinct_but_repeated_context_still_rejected(self): + self.assertEqual(OWNER.same_context_repeat_count( + '.eq{width:100px}@media(max-width:650px){.eq{width:80px}}'),0) + self.assertEqual(OWNER.same_context_repeat_count( + '@media(max-width:650px){.eq{width:80px}}' + '@media(max-width:650px){.eq{width:70px}}'),1) + self.assertEqual(OWNER.same_context_repeat_count( + '.eq{width:100px}.eq{width:90px}'),1) def test_late_stylesheet_and_inline_css_are_rejected(self): with self.assertRaisesRegex(ValueError, "inline CSS"): From d14f56d52d753e8ab12e2cd6b4c8c1abd04859bf Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:27:53 +0700 Subject: [PATCH 130/219] test(peq): qualify actual WebView2 SVG, native FX ACK and responsive screenshots --- .github/workflows/ui-smoke.yml | 3 + tests/approved_native_peq_smoke.py | 194 +++++++++++++++++++++++++++++ 2 files changed, 197 insertions(+) create mode 100644 tests/approved_native_peq_smoke.py diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index d4fe8ea82..c678ad8df 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -179,6 +179,8 @@ jobs: run: python tests/approved_fx_rack_master_power_smoke.py - name: Native FX pointer transfer, delete and editor identity run: python tests/approved_native_fx_edit_smoke.py + - name: Native EQ real Chromium SVG gestures, ACK, graph and responsive editor + run: python tests/approved_native_peq_smoke.py - name: Cold start first WIRE and original-channel VST3 picker editor run: python tests/approved_native_cold_start_smoke.py - name: Native WIRE gain and OUT share accepted PCM identity (real Chromium) @@ -469,5 +471,6 @@ jobs: native-wire-gain-*.png native-cold-start-*.png native-fx-edit-*.png + native-peq-*.png if-no-files-found: ignore retention-days: 3 diff --git a/tests/approved_native_peq_smoke.py b/tests/approved_native_peq_smoke.py new file mode 100644 index 000000000..b384bcd29 --- /dev/null +++ b/tests/approved_native_peq_smoke.py @@ -0,0 +1,194 @@ +"""Real assembled WebView2 DOM: native EQ picker, instance, SVG, gestures, ACK. + +This runs in Chromium against the EXACT approved GUI bundle used by Windows. +The isolated backend is an *explicit test double* for native event timing; +this is NOT evidence of audio DSP/ASIO performance. DSP is tested by CTest. +Actual PNGs are rendered by Chromium and uploaded only on successful tests. +""" +from pathlib import Path +import copy +import importlib.util +import tempfile +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import snapshot, emit, ack, SOURCE + +ROOT=Path(__file__).resolve().parents[1] +EQ_ID="armix.builtin.channel-eq.v1" +INSTANCE="eq-native-1" +DEFAULTS=[80,160,250,500,1500,4500,9500,18000] + +def bands_initial(): + return [{"enabled":False,"frequencyHz":float(f),"gainDb":0., + "q":1. if 2<=i<=5 else 0.70710678,"slope":12} + for i,f in enumerate(DEFAULTS)] + +def eq_context(s): + return {"channelId":SOURCE,"instanceId":INSTANCE,"slot":0, + "deviceEpoch":s["device"]["epoch"], + "graphRevision":s["graph"]["revision"]} + +def last_action(page,kind): + all_actions=page.evaluate( + "kind=>window.__actions.filter(x=>x.action===kind)",kind) + assert all_actions,kind+" action not emitted" + return all_actions[-1] + +def emit_snapshot(page,state,bands,applied=None): + action=last_action(page,"nativeEqSnapshot") + payload={**eq_context(state),"requestId":action["requestId"], + "status":"ACCEPTED","schemaVersion":1,"sampleRate":48000, + "bands":copy.deepcopy(bands)} + if applied:payload["appliedRequestId"]=applied + emit(page,"arMixBuiltinEqSnapshot",payload) + +def flush_edits(page,state,bands,handled): + # Coalesced gestures may queue one last edit AFTER an audio readback. + for _ in range(8): + actions=page.evaluate("""()=>window.__actions.filter(x=> + x.action==='nativeEqSetBand')""") + unseen=[a for a in actions if a["requestId"] not in handled] + if not unseen:break + edit=unseen[-1];handled.add(edit["requestId"]) + assert edit["instanceId"]==INSTANCE + assert edit["channelId"]==SOURCE + assert edit["deviceEpoch"]==state["device"]["epoch"] + assert edit["graphRevision"]==state["graph"]["revision"] + # The control request itself must not count as a DSP ACK. + emit(page,"arMixBuiltinEqQueue", + {"requestId":edit["requestId"],"status":"QUEUED"}) + emit(page,"arMixBuiltinEqAck", + {"requestId":edit["requestId"],"status":"APPLIED"}) + bands[edit["bandIndex"]]=edit["band"] + emit_snapshot(page,state,bands,edit["requestId"]) + else: + raise AssertionError("EQ control coalescing failed to settle") + return handled + +def main(): + spec=importlib.util.spec_from_file_location("bundle",ROOT/"scripts/build_approved_native_gui.py") + bundle=importlib.util.module_from_spec(spec);spec.loader.exec_module(bundle) + with tempfile.TemporaryDirectory(prefix="arsonmix-true-eq-") as directory, sync_playwright() as pw: + out=Path(directory);bundle.stage(out) + browser=pw.chromium.launch(headless=True) + for width,height in [(1366,768),(1680,900),(1920,1080),(390,844)]: + page=browser.new_page(viewport={"width":width,"height":height}) + errors=[] + page.on("pageerror",lambda e:errors.append(str(e))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[];window.__actions=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){ + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload); + if(name==='arMixAction')window.__actions.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out/"index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled && window.ArSonMixNativeEq") + state=snapshot() + state["graph"]["capabilities"]["supportedOps"]+=["LOAD_INSERT","MOVE_INSERT","REMOVE_INSERT"] + emit(page,"arMixConsoleSnapshot",state) + strip=page.locator('#tracks .strip[data-id="1"]') + if width<=500: + # This is the existing operator bank UI, not a second mixer. + page.locator("#bankSelect").select_option("0") + strip.locator('.fx-pick.empty').first.click() + picker=page.locator("#fastResults [data-fast-native-eq]") + picker.wait_for(state="visible") + assert picker.count()==1 + picker.click() + intents=page.evaluate("""()=>window.__nativeIntents.filter(x=> + x.operation==='LOAD_INSERT')""") + assert len(intents)==1,("missing ordered native insert",intents) + assert intents[0]["payload"]["catalogId"]==EQ_ID + assert strip.locator(".fxslot-row[data-insert-id='eq-native-1']").count()==0,\ + "GUI marked EQ active before native accept" + assert page.locator("#mxNativePeq").is_hidden(),\ + "editor auto-opened on INSERT" + state["graph"].update(revision="3",rosterRevision="3") + state["graph"]["channels"][0]["inserts"].append({ + "id":INSTANCE,"catalogId":EQ_ID,"name":"Parametric EQ","bypassed":False}) + state["mixerSession"].update(routeRevision="3",rosterRevision="3", + channels=copy.deepcopy(state["graph"]["channels"])) + ack(page,state,intents[0]) + emit(page,"arMixConsoleSnapshot",state) + row=strip.locator('.fxslot-row[data-insert-id="eq-native-1"]') + row.wait_for(state="visible") + assert strip.locator(".fxslot-row:not(.is-empty)").count()==1 + page.keyboard.press("Escape") + if width==1366: + page.screenshot(path="native-peq-01-accepted-rack.png") + row.locator('[data-action="openPlugin"]').click() + editor=page.locator("#mxNativePeq") + editor.wait_for(state="visible") + values=bands_initial() + handled=set() + emit_snapshot(page,state,values) + assert page.locator(".mx-peq-knob").count()==3 + assert page.locator(".mx-peq-band").count()==8 + assert page.locator(".mx-peq-graph svg").count()==1 + assert page.locator(".mx-peq-zero").count()==1 + assert page.locator(".mx-peq-graph circle[data-eq-node]").count()==16 + bbox=editor.bounding_box() + assert bbox and bbox["x"]>=0 and bbox["y"]>=0,\ + "EQ window starts outside viewport" + if width==1366: + page.screenshot(path="native-peq-02-open-editor.png") + # Enable bell band with an acknowledged native write. + page.locator(".mx-peq-band").nth(2).locator(".mx-peq-band-power").click() + flush_edits(page,state,values,handled) + gain=page.locator('.mx-peq-knob[data-kind="gainDb"] .mx-peq-value') + gain.fill("5.5");gain.press("Tab") + flush_edits(page,state,values,handled) + assert values[2]["enabled"] and values[2]["gainDb"]==5.5 + page.screenshot(path="native-peq-03-bell-colors.png") + # One real native EQ instance containing HPF + LS + bell + HS. + for index,gain_value in [(0,None),(1,3.0),(6,-4.0)]: + band=page.locator(".mx-peq-band").nth(index) + band.locator(".mx-peq-select").click() + band.locator(".mx-peq-band-power").click() + flush_edits(page,state,values,handled) + if gain_value is not None: + knob=page.locator('.mx-peq-knob[data-kind="gainDb"] .mx-peq-value') + knob.fill(str(gain_value));knob.press("Tab") + flush_edits(page,state,values,handled) + assert values[0]["enabled"] and values[1]["enabled"] and values[6]["enabled"] + page.screenshot(path="native-peq-04-combined-curve.png") + page.locator(".mx-peq-band").nth(2).locator(".mx-peq-select").click() + page.screenshot(path="native-peq-05-three-knobs.png") + # Actual operator drag and wheel; first send is PENDING until DSP ACK. + node=page.locator('.mx-peq-graph circle[data-eq-node="2"]').last + box=node.bounding_box();assert box + x=box["x"]+box["width"]/2;y=box["y"]+box["height"]/2 + page.mouse.move(x,y);page.mouse.down() + page.mouse.move(x+70,y-24,steps=9);page.mouse.up() + flush_edits(page,state,values,handled) + node=page.locator('.mx-peq-graph circle[data-eq-node="2"]').last + box=node.bounding_box();assert box + page.mouse.move(box["x"]+box["width"]/2,box["y"]+box["height"]/2) + page.mouse.wheel(0,-100) + flush_edits(page,state,values,handled) + assert values[2]["frequencyHz"]>250,values[2] + assert values[2]["q"]>1,values[2] + page.screenshot(path="native-peq-06-drag-wheel-q.png") + # Modeless window can move and reopening reads real accepted snapshot. + bar=page.locator(".mx-peq-title");rect=bar.bounding_box();assert rect + page.mouse.move(rect["x"]+100,rect["y"]+15);page.mouse.down() + page.mouse.move(rect["x"]+140,rect["y"]+30,steps=5);page.mouse.up() + assert editor.bounding_box()["x"]>bbox["x"]+25 + editor.locator(".mx-peq-close").click();assert editor.is_hidden() + row.locator('[data-action="openPlugin"]').click() + emit_snapshot(page,state,values) + assert page.locator('.mx-peq-knob[data-kind="frequencyHz"] .mx-peq-value').input_value(),\ + "parameter readback lost after reopen" + else: + # Narrow + desktop screenshots come from the exact compiled GUI. + rect=editor.bounding_box();assert rect and rect["width"]<=width and rect["height"]<=height,\ + (width,height,rect) + page.screenshot(path=f"native-peq-editor-{width}.png") + assert not errors,(width,height,errors) + page.close() + browser.close() + print("PASS assembled native EQ GUI: one ordered FX insert; SVG log graph;" + " native emulated apply/ACK/readback; gestures; 4 viewports." + " Physical PCM/ASIO remains hardware FAT PENDING.") + +if __name__=="__main__": + main() From 277d879fa712258c50b3f64a479851db4ea398de Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:38:04 +0700 Subject: [PATCH 131/219] test(peq): prove native ordered PCM effect, bypassed callback ACK and RT no-heap --- tests/live_channel_fx_graph_test.cpp | 81 ++++++++++++++++++++++++++++ 1 file changed, 81 insertions(+) diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index 2863d041a..c86796db8 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/core/LiveChannelFxGraph.h" +#include "../engine/builtin_fx/ChannelEqProcessor.h" #include "../engine/core/DynamicChannelFxLeaseBank.h" #include "../engine/core/NativeFxRackTransaction.h" #include "../engine/core/DynamicNativeSessionPublisher.h" @@ -1968,6 +1969,85 @@ static void verifyNativeFxRackTransactions() { edit(source,0,b->instanceId,{},0);samples(.45f);assert(!bank->retainsEditor(b)); edit(dest,0,a->instanceId,{},0);samples(.35f);assert(!bank->retainsEditor(a)); } + +// Native eight-band Parametric EQ must be the exact ordered rack lease in PCM, +// not an independent "pre-VST" bank, a JS preview or a second audio callback. +// Verifies asynchronous audio-owned ACK while the same insert is bypassed, +// graph revision-safe reorder, and no allocations in the hot render call. +static void verifyNativeBuiltinEqOrderedPcmAndBypassAck() { + using Bank=DynamicChannelFxLeaseBank; + using Eq=armix::builtin_fx::ChannelEqProcessor; + constexpr std::uint64_t ep=10997,revision=11; + const ChannelId ch{12345678901234ULL}; + std::unique_ptr eq=std::make_unique(); + eq->prepareToPlay(48000.,64); + assert(eq->isReady()); + Eq* live=eq.get(); + auto eqLease=std::make_shared( + std::move(eq),Eq::catalogIdentity,"Parametric EQ",64); + auto other=std::make_unique(1.0f,0,.2f); + other->prepareToPlay(48000.,64); + auto offsetLease=std::make_shared( + std::move(other),"nonlinear-order-probe","Offset after EQ",64); + Bank::Assignment a;a.id=ch;a.format=ProcessingFormat::stereo; + a.inserts={eqLease,offsetLease}; + std::array assignment{a}; + Bank graph; + assert(Bank::prepare(ep,revision,assignment,graph)==Bank::Fault::none); + assert(graph.insertCount(ch)==2 && graph.latencySamples(ch)==0); + assert((*graph.ownerForControl(ch,0))->instanceId==eqLease->instanceId); + assert((*graph.ownerForControl(ch,1))->instanceId==offsetLease->instanceId); + armix::builtin_fx::Band hp{}; + hp.enabled=true;hp.frequencyHz=1000.f;hp.gainDb=0.f; + hp.q=.70710678f;hp.slope=armix::builtin_fx::Slope::db12; + assert(live->queueBand(0,hp,1)); + std::array l{},r{}; + const auto renderBlocks=[&](const Bank& bank,int blocks) { + const auto allocations=heapCalls.load(std::memory_order_relaxed); + for(int b=0;bpollCompletion(done)&&done.applied&&done.requestId==1); + assert(done.bandIndex==0&&live->acceptedBands()[0].enabled); + // A constant .5 enters HPF, then post-EQ vendor offset +.2 survives. + assert(std::abs(l.back()-.2f)<.04f &&std::abs(r.back()-.2f)<.04f); + const auto token=eqLease->instanceId; + assert(!graph.setInsertBypass(ep,revision-1,ch,0,token,true)); + assert(!graph.setInsertBypass(ep,revision,ch,0,"wrong",true)); + assert(graph.setInsertBypass(ep,revision,ch,0,token,true)); + renderBlocks(graph,64); + assert(std::abs(l.back()-.7f)<.04f); + // Fully bypassed native EQ still consumes audio-synchronized commands; + // no ACK may be fabricated from the control-thread enqueue itself. + hp.frequencyHz=1600.f; + assert(live->queueBand(0,hp,2)); + assert(!live->pollCompletion(done)); + renderBlocks(graph,2); + assert(live->pollCompletion(done)&&done.applied&&done.requestId==2); + assert(std::abs(live->acceptedBands()[0].frequencyHz-1600.f)<.01f); + assert(graph.setInsertBypass(ep,revision,ch,0,token,false)); + renderBlocks(graph,64); + assert(std::abs(l.back()-.2f)<.04f); + Bank moved; + assert(Bank::editOwned(ep,revision+1,graph,ch,0,token, + ch,1,ProcessingFormat::stereo,moved)==Bank::Fault::none); + assert(moved.insertCount(ch)==2); + assert((*moved.ownerForControl(ch,1)).get()==eqLease.get()); + assert((*moved.ownerForControl(ch,0)).get()==offsetLease.get()); + // Exact EQ now comes AFTER the offset-producing FX, so the HPF removes + // DC from both input and offset. This distinguishes true PCM FX ordering. + renderBlocks(moved,64); + assert(std::abs(l.back())<.04f && std::abs(r.back())<.04f); + assert(!moved.setInsertBypass(ep,revision,ch,1,token,true)); + assert(moved.leaseEditor(ep,revision+1,ch,1,token).get()==eqLease.get()); +} + int main(int argc,char** argv) { if(argc==2 && std::string(argv[1])=="--emit-console-s0-json") { verifyNativePuzzleV8FixtureAndWire(); @@ -2381,6 +2461,7 @@ int main(int argc,char** argv) { verifyChannelIdGroupPreservesHostedFx(); verifyLatencyAlignedBypass(); verifyNativeFxRackTransactions(); + verifyNativeBuiltinEqOrderedPcmAndBypassAck(); // Tests above use a real JUCE AudioProcessor processing seam. Vendor // VST3 formats and sound quality require separate Windows hardware FAT. } From 3b9532ab90155d7cdf3550f04f37bedae0e7a88b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:44:33 +0700 Subject: [PATCH 132/219] test(ui): assert native bank active semantics instead of gradient backgroundColor --- tests/mixer_io_smoke.py | 15 ++++++++++++--- 1 file changed, 12 insertions(+), 3 deletions(-) diff --git a/tests/mixer_io_smoke.py b/tests/mixer_io_smoke.py index 6f47d8cdb..42f0cbee5 100644 --- a/tests/mixer_io_smoke.py +++ b/tests/mixer_io_smoke.py @@ -53,9 +53,18 @@ async def main(): assert all(abs(a-b)<1 for a,b in zip(sizes,after)),(sizes,after) await page.locator('[data-mix-mode="ROUTE"]').click() assert "UNPATCHED" in await page.locator('[data-strip="1"] .arBankOutput').inner_text() - palette=await page.evaluate("""() => ['FX','ROUTE'].map(x=>getComputedStyle( - document.querySelector('[data-mix-mode="'+x+'"]')).backgroundColor)""") - assert palette[0]!=palette[1],palette + # Physical BTN-180 is a layered gradient. backgroundColor alone is + # not the live visual state; verify the actual active token and ARIA. + modes=await page.evaluate("""() => ['FX','ROUTE'].map(x=>{ + const button=document.querySelector('[data-mix-mode="'+x+'"]'); + const css=getComputedStyle(button); + return {active:button.classList.contains('active'), + pressed:button.getAttribute('aria-pressed'), + edge:css.getPropertyValue('--b180-border').trim()}; + })""") + assert modes[0]['active'] is False and modes[0]['pressed']=='false',modes + assert modes[1]['active'] is True and modes[1]['pressed']=='true',modes + assert modes[0]['edge']!=modes[1]['edge'],modes await page.locator('[data-strip="0"] select.arBankSource').select_option("MONO:0") assert "PENDING" in await page.locator('[data-strip="0"] .arBankStage').inner_text() assert await page.locator('[data-strip="0"] .arBankSource').is_disabled() From d4cef7a49eb3e2304678eb9f0c8d0be44a07ecd4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:46:26 +0700 Subject: [PATCH 133/219] fix(peq): coalesce independent band gestures without losing pending audio ACK updates --- site/preview-v2/assets/mixer-native-peq.js | 23 +++++++++++++--------- tests/approved_native_peq_smoke.py | 5 +++++ 2 files changed, 19 insertions(+), 9 deletions(-) diff --git a/site/preview-v2/assets/mixer-native-peq.js b/site/preview-v2/assets/mixer-native-peq.js index 2a37edc08..179ac8a01 100644 --- a/site/preview-v2/assets/mixer-native-peq.js +++ b/site/preview-v2/assets/mixer-native-peq.js @@ -61,7 +61,10 @@ function response(freq,ss){ return clamp(total,-160,80); } let sampleRate=48000,bands=fresh(),selected=2,current=null,gesture=null,draft=null,pending=null, - latest=null,raf=0,lastSend=0,seq=1,readbackRequest="",mode=""; + raf=0,lastSend=0,seq=1,readbackRequest="",mode=""; +// Preserve the FINAL edit for EACH band while one audio ACK is in flight. +// A scalar 'latest' loses changes when the user switches bands rapidly. +const latest=new Map(); const demos=new Map(); const root=dom("section","mx-peq");root.id="mxNativePeq";root.hidden=true;root.setAttribute("role","dialog"); root.setAttribute("aria-label","ArSonMix Parametric EQ");root.setAttribute("aria-modal","false"); @@ -193,7 +196,7 @@ function requestSnapshot(){ } function send(i,value){ const c=context();if(!c)return; - if(pending){latest={index:i,band:value};hint("DSP · APPLYING · FINAL EDIT HELD");return;} + if(pending){latest.set(i,value);hint("DSP · APPLYING · EDITS HELD UNTIL ACK");return;} const id="eq-"+String(Date.now()*1000+(seq++%1000)); pending={id,index:i,band:value,context:c,ack:false}; backend().emitEvent("arMixAction",{action:"nativeEqSetBand",requestId:id, ...c, @@ -212,7 +215,7 @@ function change(i,patch,preview=false){ hint("BROWSER PREVIEW · VISUAL ONLY · NO AUDIO");draw();return;} const now=performance.now(); if(!preview||now-lastSend>90){lastSend=now;send(i,next);} - else latest={index:i,band:next}; + else latest.set(i,next); } function movePoint(e){ const r=svg.getBoundingClientRect(); @@ -343,7 +346,7 @@ const api={ return Boolean(window.__ARMIX_NATIVE_M2__?.insertPlugin?.(ID,target)); }, open(track,slot){ - current={track,slot,channelId:null,instanceId:null};selected=2;pending=null;latest=null;draft=null; + current={track,slot,channelId:null,instanceId:null};selected=2;pending=null;latest.clear();draft=null; const n=state();const nativeId=window.__ARMIX_NATIVE_M2__?.nativeIdFor?.(track); const ch=n?.graph?.channels?.find(x=>x.id===nativeId); if(native()&&n?.admitted&&ch?.inserts?.[slot]?.catalogId===ID){ @@ -362,12 +365,12 @@ const api={ window.ArSonMixNativeEq=Object.freeze(api); backend()?.addEventListener?.("arMixBuiltinEqQueue",ack=>{ if(!pending||ack?.requestId!==pending.id)return; - if(ack.status==="REJECTED"){pending=null;latest=null;draft=null; + if(ack.status==="REJECTED"){pending=null;latest.clear();draft=null; hint("NATIVE REJECTED · "+(ack.errorCode||"UNKNOWN"));requestSnapshot();} }); backend()?.addEventListener?.("arMixBuiltinEqAck",ack=>{ if(!pending||ack?.requestId!==pending.id)return; - if(ack.status!=="APPLIED"){pending=null;latest=null;draft=null; + if(ack.status!=="APPLIED"){pending=null;latest.clear();draft=null; hint("DSP DID NOT APPLY · "+(ack.errorCode||"UNKNOWN"));requestSnapshot();return;} pending.ack=true;hint("DSP APPLIED · VERIFYING READBACK");requestSnapshot(); }); @@ -384,14 +387,16 @@ backend()?.addEventListener?.("arMixBuiltinEqSnapshot",s=>{ if(!s.bands.every((b,i)=>valid(i,b))){sampleRate=rate;hint("NATIVE EQ PARAMETER READBACK INVALID");return;} if(pending&&(!pending.ack||s.appliedRequestId!==pending.id))return; bands=s.bands.map(b=>({...b}));pending=null; - if(latest){const update=latest;latest=null;send(update.index,update.band);} - else draft=null; + if(latest.size){ + const [index,value]=latest.entries().next().value; + latest.delete(index);send(index,value); + }else draft=null; hint("NATIVE DSP ACCEPTED · "+c.instanceId); draw(); }); backend()?.addEventListener?.("arMixConsoleSnapshot",()=>{ if(root.hidden||!native()||!current?.instanceId)return; - queueMicrotask(()=>{if(!context()){pending=null;latest=null;draft=null; + queueMicrotask(()=>{if(!context()){pending=null;latest.clear();draft=null; hint("DEVICE/GRAPH CHANGED · REOPEN ACCEPTED FX");draw();}}); }); })(); \ No newline at end of file diff --git a/tests/approved_native_peq_smoke.py b/tests/approved_native_peq_smoke.py index b384bcd29..b9812626e 100644 --- a/tests/approved_native_peq_smoke.py +++ b/tests/approved_native_peq_smoke.py @@ -133,7 +133,12 @@ def main(): page.screenshot(path="native-peq-02-open-editor.png") # Enable bell band with an acknowledged native write. page.locator(".mx-peq-band").nth(2).locator(".mx-peq-band-power").click() + # Rapid independent band changes must not overwrite one + # another while the FIRST DSP ACK is still outstanding. + page.locator(".mx-peq-band").nth(3).locator(".mx-peq-band-power").click() + page.locator(".mx-peq-band").nth(4).locator(".mx-peq-band-power").click() flush_edits(page,state,values,handled) + assert all(values[i]["enabled"] for i in (2,3,4)),values gain=page.locator('.mx-peq-knob[data-kind="gainDb"] .mx-peq-value') gain.fill("5.5");gain.press("Tab") flush_edits(page,state,values,handled) From 2ef72935dd4a27d858c8da6c4c6f4ddeed1a7ab6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:49:04 +0700 Subject: [PATCH 134/219] test(peq): select target bell after multi-band coalescing before gain assertion --- tests/approved_native_peq_smoke.py | 3 +++ 1 file changed, 3 insertions(+) diff --git a/tests/approved_native_peq_smoke.py b/tests/approved_native_peq_smoke.py index b9812626e..de992c9f8 100644 --- a/tests/approved_native_peq_smoke.py +++ b/tests/approved_native_peq_smoke.py @@ -139,6 +139,9 @@ def main(): page.locator(".mx-peq-band").nth(4).locator(".mx-peq-band-power").click() flush_edits(page,state,values,handled) assert all(values[i]["enabled"] for i in (2,3,4)),values + # The three power clicks leave band 4 selected. Explicitly + # select bell 2 before checking its independent gain edit. + page.locator(".mx-peq-band").nth(2).locator(".mx-peq-select").click() gain=page.locator('.mx-peq-knob[data-kind="gainDb"] .mx-peq-value') gain.fill("5.5");gain.press("Tab") flush_edits(page,state,values,handled) From 48b096a6bede405ca5acf8442bf787396c17c72b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:51:46 +0700 Subject: [PATCH 135/219] fix(peq): guard native Show binary capture against unacknowledged DSP edits and restore unpublished processor state --- engine/builtin_fx/ChannelEqProcessor.h | 63 +++++++++++++++++++------- engine/core/LiveChannelFxGraph.h | 8 ++++ engine/core/RealtimeNativeFxControl.h | 6 +++ tests/live_channel_fx_graph_test.cpp | 63 ++++++++++++++++++++++++++ 4 files changed, 123 insertions(+), 17 deletions(-) diff --git a/engine/builtin_fx/ChannelEqProcessor.h b/engine/builtin_fx/ChannelEqProcessor.h index 8b2a76027..43aaad554 100644 --- a/engine/builtin_fx/ChannelEqProcessor.h +++ b/engine/builtin_fx/ChannelEqProcessor.h @@ -34,6 +34,10 @@ template class EqSpsc final { return write_.load(std::memory_order_relaxed)- read_.load(std::memory_order_acquire) write_{0}; alignas(64) std::atomic read_{0}; @@ -131,6 +135,12 @@ class ChannelEqProcessor final : public juce::AudioProcessor, } double acceptedSampleRate() const noexcept {return rate_;} bool isReady() const noexcept {return ready_;} + void sealForRealtime() noexcept override {published_=true;} + bool stateSnapshotQuiescent() const noexcept override { + // CONTROL only; the caller owns FxInstance's non-blocking capture + // gate, so it cannot race the consumer inside processBlock. + return queued_.empty()&&completion_.empty(); + } // The native Show's vendor-state lease already serializes state on the // control thread. Built-in DSP uses that same per-insert lease and schema, @@ -147,29 +157,47 @@ class ChannelEqProcessor final : public juce::AudioProcessor, output.writeByte(static_cast(b.slope)); } } - void setStateInformation(const void* data,int size) override { - if(!data||size!=8+static_cast(ChannelEq::bandCount)*14)return; + // Only a NEW, unpublished processor is permitted to receive a binary + // Show restore. Mutating a live published DSP would race its callback. + // The Show builder may call this before OR after prepareToPlay; both + // restore the complete bank, and the next audio block starts settled. + // For future ChannelId Show preflight, use the bool-returning method + // rather than JUCE's legacy void setter so errors are not hidden. + bool restoreUnpublishedState(const void* data,int size) { + if(published_||!data|| + size!=8+static_cast(ChannelEq::bandCount)*14 || + !queued_.empty()||!completion_.empty())return false; juce::MemoryInputStream input(data,static_cast(size),false); - if(input.readInt()!=0x41504551||input.readInt()!=1)return; + if(input.readInt()!=0x41504551||input.readInt()!=1)return false; std::array next{}; - for(auto& b:next){ - b.enabled=input.readByte()!=0; - b.frequencyHz=input.readFloat();b.gainDb=input.readFloat(); + for(auto& b:next) { + const int enabled=input.readByte(); + if(enabled!=0&&enabled!=1)return false; + b.enabled=enabled!=0; + b.frequencyHz=input.readFloat(); + b.gainDb=input.readFloat(); b.q=input.readFloat(); - const auto slope=input.readByte(); - if(slope!=12&&slope!=24)return; + const int slope=input.readByte(); + if(slope!=12&&slope!=24)return false; b.slope=slope==24?Slope::db24:Slope::db12; } - const double rate=rate_>0.?rate_:48000.; - for(std::size_t i=0;i accepted_{}; double rate_=0.; // control-owned immutable after prepare bool ready_=false; // prepared before graph publication + bool published_=false; // CONTROL-only, sealed by FxInstance off callback }; } // namespace armix::builtin_fx diff --git a/engine/core/LiveChannelFxGraph.h b/engine/core/LiveChannelFxGraph.h index 80a877d13..769bc927a 100644 --- a/engine/core/LiveChannelFxGraph.h +++ b/engine/core/LiveChannelFxGraph.h @@ -61,6 +61,7 @@ class LiveChannelFxGraph final { bypassFade.prepare(false,processor?processor->getSampleRate():48000.0,0); if(processor){ nativeControl=dynamic_cast(processor.get()); + if(nativeControl)nativeControl->sealForRealtime(); processor->addListener(this); } } @@ -89,6 +90,13 @@ class LiveChannelFxGraph final { return false; bool ok=false; try { + // Even under the exclusive processor gate, async EQ edits + // can still be QUEUED or have an unconsumed completion. + // Never serialize a stale binary state into a native Show. + if(nativeControl && !nativeControl->stateSnapshotQuiescent()) { + processing.clear(std::memory_order_release); + return false; + } juce::MemoryBlock candidate; processor->getStateInformation(candidate); if(candidate.getSize()<=8U*1024U*1024U) { diff --git a/engine/core/RealtimeNativeFxControl.h b/engine/core/RealtimeNativeFxControl.h index 2235dff05..b15eab95d 100644 --- a/engine/core/RealtimeNativeFxControl.h +++ b/engine/core/RealtimeNativeFxControl.h @@ -9,5 +9,11 @@ namespace armix::mixer { struct RealtimeNativeFxControl { virtual ~RealtimeNativeFxControl() = default; virtual void consumeRealtimeEdits() noexcept = 0; + // CONTROL-only lifecycle: after FxInstance accepts this processor, a + // vendor-state restore must not mutate published audio-owned filters. + virtual void sealForRealtime() noexcept {} + // CONTROL-only Show capture guard: pending DSP edits must first be + // consumed AND acknowledged, otherwise a saved state could be stale. + virtual bool stateSnapshotQuiescent() const noexcept {return true;} }; } // namespace armix::mixer diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index c86796db8..d789c4dce 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -2048,6 +2048,68 @@ static void verifyNativeBuiltinEqOrderedPcmAndBypassAck() { assert(moved.leaseEditor(ep,revision+1,ch,1,token).get()==eqLease.get()); } +// Binary EQ state is captured only when the audio mailbox has settled. +// The verifier covers the pending/ACK window, state fidelity and the +// pre-publication restore rule without touching live device or worker threads. +static void verifyNativeEqCaptureRequiresAcceptedDspAndOfflineRestore() { + using Eq=armix::builtin_fx::ChannelEqProcessor; + auto processor=std::make_unique(); + processor->prepareToPlay(48000.0,64); + assert(processor->isReady()); + Eq* live=processor.get(); + auto owner=std::make_shared( + std::move(processor),Eq::catalogIdentity,"Parametric EQ",64); + armix::builtin_fx::Band b{}; + b.enabled=true;b.frequencyHz=2500.f;b.gainDb=5.f;b.q=1.2f; + b.slope=armix::builtin_fx::Slope::db12; + assert(live->queueBand(2,b,501)); + juce::MemoryBlock saved; + assert(!owner->tryCaptureState(saved)); // queued, not audio-owned + std::array left{},right{}; + left.fill(.1f);right.fill(.1f); + const auto heapBefore=heapCalls.load(std::memory_order_relaxed); + owner->render(left.data(),right.data(),64); + assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); + assert(!owner->tryCaptureState(saved)); // applied but not ACK-consumed + Eq::Completion ack{}; + assert(live->pollCompletion(ack)&&ack.applied&&ack.requestId==501); + assert(ack.bandIndex==2&&ack.band.gainDb==5.f); + assert(owner->tryCaptureState(saved)); // control state now stable + assert(saved.getSize()==8+8*14); + assert(!live->restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); // published LIVE = immutable + + // A newly built Show candidate may restore before preparation. + Eq restored; + assert(restored.restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); + assert(restored.acceptedBands()[2].enabled); + assert(restored.acceptedBands()[2].frequencyHz==2500.f); + assert(restored.acceptedBands()[2].gainDb==5.f); + restored.prepareToPlay(44100.0,64); + assert(restored.isReady()); + assert(restored.acceptedBands()[2].q==1.2f); + + // The existing Show pipeline restores vendor states after preparation. + // That must work too, but only while the candidate is NOT published. + auto prepared=std::make_unique(); + prepared->prepareToPlay(96000.0,128); + assert(prepared->restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); + assert(prepared->acceptedBands()[2].gainDb==5.f); + juce::MemoryBlock bad(saved); + static_cast(bad.getData())[0]^=0x5f; + assert(!prepared->restoreUnpublishedState(bad.getData(), + static_cast(bad.getSize()))); + assert(prepared->acceptedBands()[2].gainDb==5.f); + auto sealed=std::make_shared( + std::move(prepared),Eq::catalogIdentity,"Restored EQ",128); + auto* sealedEq=dynamic_cast(sealed->processor.get()); + assert(sealedEq&&!sealedEq->restoreUnpublishedState(saved.getData(), + static_cast(saved.getSize()))); + assert(sealed->tryCaptureState(bad)); // restored bank is quiescent +} + int main(int argc,char** argv) { if(argc==2 && std::string(argv[1])=="--emit-console-s0-json") { verifyNativePuzzleV8FixtureAndWire(); @@ -2462,6 +2524,7 @@ int main(int argc,char** argv) { verifyLatencyAlignedBypass(); verifyNativeFxRackTransactions(); verifyNativeBuiltinEqOrderedPcmAndBypassAck(); + verifyNativeEqCaptureRequiresAcceptedDspAndOfflineRestore(); // Tests above use a real JUCE AudioProcessor processing seam. Vendor // VST3 formats and sound quality require separate Windows hardware FAT. } From 55868b65cab238f950e4b7c5d2372b6d67c517bf Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 06:54:30 +0700 Subject: [PATCH 136/219] test(peq): hit actual SVG node via viewport transform in Chromium drag and wheel --- tests/approved_native_peq_smoke.py | 32 ++++++++++++++++++++++++------ 1 file changed, 26 insertions(+), 6 deletions(-) diff --git a/tests/approved_native_peq_smoke.py b/tests/approved_native_peq_smoke.py index de992c9f8..3d163c1e9 100644 --- a/tests/approved_native_peq_smoke.py +++ b/tests/approved_native_peq_smoke.py @@ -27,6 +27,29 @@ def eq_context(s): "deviceEpoch":s["device"]["epoch"], "graphRevision":s["graph"]["revision"]} +def node_pixel(page,index): + """Use the actual SVG user-space->screen transform, not Playwright's + bounding_box on a transparent SVG circle (Chromium may return None). + Mouse events below remain real browser pointer interactions. + """ + selector=f'.mx-peq-graph circle[data-eq-node="{index}"]' + page.locator(selector).last.wait_for(state="attached") + position=page.locator(selector).last.evaluate("""el=>{ + const svg=el.ownerSVGElement,matrix=svg?.getScreenCTM(); + if(!matrix)return null; + const point=svg.createSVGPoint(); + point.x=Number(el.getAttribute('cx')); + point.y=Number(el.getAttribute('cy')); + const screen=point.matrixTransform(matrix); + const target=document.elementFromPoint(screen.x,screen.y); + return {x:screen.x,y:screen.y, + hit:target?.getAttribute('data-eq-node')===el.getAttribute('data-eq-node')}; + }""") + assert position and position["x"]>0 and position["y"]>0,position + assert position["hit"],"EQ node not actually pointer-targetable: "+str(position) + return position["x"],position["y"] + + def last_action(page,kind): all_actions=page.evaluate( "kind=>window.__actions.filter(x=>x.action===kind)",kind) @@ -162,15 +185,12 @@ def main(): page.locator(".mx-peq-band").nth(2).locator(".mx-peq-select").click() page.screenshot(path="native-peq-05-three-knobs.png") # Actual operator drag and wheel; first send is PENDING until DSP ACK. - node=page.locator('.mx-peq-graph circle[data-eq-node="2"]').last - box=node.bounding_box();assert box - x=box["x"]+box["width"]/2;y=box["y"]+box["height"]/2 + x,y=node_pixel(page,2) page.mouse.move(x,y);page.mouse.down() page.mouse.move(x+70,y-24,steps=9);page.mouse.up() flush_edits(page,state,values,handled) - node=page.locator('.mx-peq-graph circle[data-eq-node="2"]').last - box=node.bounding_box();assert box - page.mouse.move(box["x"]+box["width"]/2,box["y"]+box["height"]/2) + x,y=node_pixel(page,2) + page.mouse.move(x,y) page.mouse.wheel(0,-100) flush_edits(page,state,values,handled) assert values[2]["frequencyHz"]>250,values[2] From b04b83bf5c47c6b4346464dacc72a1405fbe0af2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 07:01:27 +0700 Subject: [PATCH 137/219] fix(peq): restore disabled bands safely across 44.1/48/96 kHz without retuning enabled filters --- engine/builtin_fx/ChannelEqProcessor.h | 11 +++++++++++ tests/live_channel_fx_graph_test.cpp | 21 +++++++++++++++++++++ 2 files changed, 32 insertions(+) diff --git a/engine/builtin_fx/ChannelEqProcessor.h b/engine/builtin_fx/ChannelEqProcessor.h index 43aaad554..8a44e371e 100644 --- a/engine/builtin_fx/ChannelEqProcessor.h +++ b/engine/builtin_fx/ChannelEqProcessor.h @@ -183,7 +183,18 @@ class ChannelEqProcessor final : public juce::AudioProcessor, } if(!input.isExhausted())return false; const double validationRate=ready_?rate_:48000.; + const float maxHz=static_cast( + std::min(20000.0,validationRate*0.45)); for(std::size_t i=0;i20000.f) + return false; + if(!next[i].enabled) + next[i].frequencyHz=std::min(next[i].frequencyHz,maxHz); ChannelEq::PreparedBandEdit prepared{}; if(!ChannelEq::prepareBandEdit(i,next[i],validationRate,prepared)) return false; // all-or-nothing preflight diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index d789c4dce..60a76f11a 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -2108,6 +2108,27 @@ static void verifyNativeEqCaptureRequiresAcceptedDspAndOfflineRestore() { assert(sealedEq&&!sealedEq->restoreUnpublishedState(saved.getData(), static_cast(saved.getSize()))); assert(sealed->tryCaptureState(bad)); // restored bank is quiescent + + // At 48 kHz a disabled high band can remember 20 kHz; restoring the + // same Show at 44.1 kHz clamps ONLY that inactive band to the safe cap. + auto source=std::make_unique(); + source->prepareToPlay(48000.0,64); + auto* sourceEq=source.get(); + auto sourceOwner=std::make_shared( + std::move(source),Eq::catalogIdentity,"High band",64); + armix::builtin_fx::Band inactive{}; + inactive.enabled=false;inactive.frequencyHz=20000.f; + assert(sourceEq->queueBand(7,inactive,502)); + sourceOwner->render(left.data(),right.data(),64); + Eq::Completion highAck{}; + assert(sourceEq->pollCompletion(highAck)&&highAck.applied); + juce::MemoryBlock highState; + assert(sourceOwner->tryCaptureState(highState)); + Eq lowerRate; + lowerRate.prepareToPlay(44100.0,64); + assert(lowerRate.restoreUnpublishedState(highState.getData(), + static_cast(highState.getSize()))); + assert(lowerRate.acceptedBands()[7].frequencyHz<=19845.f); } int main(int argc,char** argv) { From 4f7f3cb4e2745a4ebdd7eade422b50e62df001cc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 07:20:00 +0700 Subject: [PATCH 138/219] fix(audio): recover closed ASIO4ALL device on explicit Apply, fence stale aggregate pins --- engine/device/AudioSetupRecoveryPolicy.h | 26 +++++++++++ src/Main.cpp | 57 ++++++++++++++++++++---- tests/asio_backend_registration_test.cpp | 19 ++++++++ web/approved-native-bridge.js | 9 ++++ 4 files changed, 102 insertions(+), 9 deletions(-) create mode 100644 engine/device/AudioSetupRecoveryPolicy.h diff --git a/engine/device/AudioSetupRecoveryPolicy.h b/engine/device/AudioSetupRecoveryPolicy.h new file mode 100644 index 000000000..a67a52db7 --- /dev/null +++ b/engine/device/AudioSetupRecoveryPolicy.h @@ -0,0 +1,26 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once + +namespace armix::device { +// A pure CONTROL-thread decision: the selected ASIO driver may keep the same +// JUCE name while its ASIO4ALL/WDM pins were reconfigured externally. +// Never reuse the old live pin mask when the device is no longer open. +// A closed prior device is not a valid rollback target. +struct AudioSetupRecoveryPolicy final { + struct Plan final { + bool reuseActivePins; + bool recreateDevice; + bool priorKnownOpen; + bool verifyAsioPinIdentity; + }; + static constexpr Plan select(bool sameEndpoint, bool priorOpen, + bool isAsio, bool completePinSelection) noexcept { + return { + sameEndpoint && priorOpen && completePinSelection, + sameEndpoint && (!priorOpen || isAsio), + priorOpen, + sameEndpoint && priorOpen && isAsio && completePinSelection + }; + } +}; +} // namespace armix::device diff --git a/src/Main.cpp b/src/Main.cpp index 87043b72b..8dc65d7bb 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -16,6 +16,7 @@ #include "../engine/core/DearVrPolarPolicy.h" #include "DiagnosticsRecorder.h" #include "../engine/device/DirectRestoreBackoff.h" +#include "../engine/device/AudioSetupRecoveryPolicy.h" #include "../engine/device/PeriodCapabilityEvidence.h" #include "../engine/diagnostics/CrackleEvidenceWindow.h" #if defined(_WIN32) @@ -1178,6 +1179,12 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto previousType=manager.getCurrentAudioDeviceType(); const bool sameEndpoint=unchangedDevice&&before.inputDeviceName==capture &&before.outputDeviceName==playback; + auto* previousDevice=manager.getCurrentAudioDevice(); + const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); + const auto originalInputNames=previousWasOpen + ?previousDevice->getInputChannelNames():juce::StringArray{}; + const auto originalOutputNames=previousWasOpen + ?previousDevice->getOutputChannelNames():juce::StringArray{}; juce::AudioDeviceManager::AudioDeviceSetup candidate=before; candidate.inputDeviceName=capture; candidate.outputDeviceName=playback; @@ -1188,12 +1195,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Its first APPLY uses safe defaults; then users refine real pin masks. const auto pinInput=config.getProperty("enabledInputs",{}); const auto pinOutput=config.getProperty("enabledOutputs",{}); - if(sameEndpoint && pinInput.isArray() && pinOutput.isArray()) { - auto* active=manager.getCurrentAudioDevice(); - if(active==nullptr||!active->isOpen()) - return send(false,"REJECTED","Current device is not open; refresh"); - const auto inCount=juce::jmin(64,active->getInputChannelNames().size()); - const auto outCount=juce::jmin(64,active->getOutputChannelNames().size()); + // External ASIO4ALL changes can leave the same endpoint name in JUCE + // with a closed object. Reopen with safe default masks first; the + // previous (possibly reordered) physical pin indices are not valid. + const auto recovery=armix::device::AudioSetupRecoveryPolicy::select( + sameEndpoint,previousWasOpen,typeName=="ASIO", + pinInput.isArray()&&pinOutput.isArray()); + if(recovery.reuseActivePins) { + const auto inCount=juce::jmin(64,previousDevice->getInputChannelNames().size()); + const auto outCount=juce::jmin(64,previousDevice->getOutputChannelNames().size()); auto parsePins=[](const juce::var& values,int limit,juce::BigInteger& mask)->bool { const auto* array=values.getArray(); if(array==nullptr||array->size()>64)return false; @@ -1236,12 +1246,29 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr const auto start=monotonicMilliseconds(); engine_.beginManualAudioSetup(); if(!unchangedDevice)manager.setCurrentAudioDeviceType(typeName,false); + // JUCE setAudioDeviceSetup() can return success without reopening when + // setup == currentSetup and currentAudioDevice != nullptr, even when + // that driver object has stopped. closeAudioDevice() deletes it but + // keeps the setup for an explicit, fresh driver instance on APPLY. + // For ASIO this also observes changed ASIO4ALL aggregate WDM pins. + // Only the operator initiates this; never auto-reopen/arm on a timer. + if(recovery.recreateDevice && manager.getCurrentAudioDeviceType()==typeName) { + diagnostics_.record("CUSTOM_AUDIO_RECREATE", + typeName+" | "+(previousWasOpen?"REFRESH_ASIO_PINS":"CLOSED_DEVICE_RECOVERY")); + manager.closeAudioDevice(); + } auto error=manager.getCurrentAudioDeviceType()==typeName ?manager.setAudioDeviceSetup(candidate,true) :juce::String("Selected audio backend could not be opened"); juce::AudioDeviceManager::AudioDeviceSetup actual; manager.getAudioDeviceSetup(actual); auto* opened=manager.getCurrentAudioDevice(); + const bool changedAsioPinLayout=error.isEmpty()&&recovery.verifyAsioPinIdentity&& + opened!=nullptr&&opened->isOpen()&& + (opened->getInputChannelNames()!=originalInputNames|| + opened->getOutputChannelNames()!=originalOutputNames); + if(changedAsioPinLayout) + error="ASIO pin layout changed. Output remains muted; review the NEW capture and playback pins and Apply again"; if(error.isEmpty()&&(opened==nullptr||!opened->isOpen()|| manager.getCurrentAudioDeviceType()!=typeName|| actual.inputDeviceName!=capture||actual.outputDeviceName!=playback|| @@ -1265,11 +1292,19 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); return send(true,"ACCEPTED_MUTED",{}); } + // A changed ASIO layout cannot be 'restored' by replaying indices + // that now refer to different WDM pins. Keep the fresh device MUTED, + // unauthorised, and show its new pin names for deliberate remapping. + if(changedAsioPinLayout) { + diagnostics_.record("CUSTOM_AUDIO_ASIO_TOPOLOGY_CHANGED",error); + return send(false,"RECOVERY_REQUIRED",error); + } // One rollback, never blind default endpoint fallback, no auto-unmute. + // A previously CLOSED device was never a verified rollback target. engine_.beginManualAudioSetup(); - if(manager.getCurrentAudioDeviceType()!=previousType&&previousType.isNotEmpty()) + if(recovery.priorKnownOpen&&manager.getCurrentAudioDeviceType()!=previousType&&previousType.isNotEmpty()) manager.setCurrentAudioDeviceType(previousType,false); - const auto restored=previousType.isNotEmpty()&& + const auto restored=recovery.priorKnownOpen&&previousType.isNotEmpty()&& manager.getCurrentAudioDeviceType()==previousType&& manager.setAudioDeviceSetup(before,true).isEmpty(); juce::AudioDeviceManager::AudioDeviceSetup checked; @@ -1280,7 +1315,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr checked.inputChannels==before.inputChannels&& checked.outputChannels==before.outputChannels&& manager.getCurrentAudioDevice()!=nullptr&& - manager.getCurrentAudioDevice()->isOpen()&&engine_.finishManualAudioSetup(); + manager.getCurrentAudioDevice()->isOpen()&& + (previousType!="ASIO"|| + (manager.getCurrentAudioDevice()->getInputChannelNames()==originalInputNames&& + manager.getCurrentAudioDevice()->getOutputChannelNames()==originalOutputNames))&& + engine_.finishManualAudioSetup(); diagnostics_.record("CUSTOM_AUDIO_APPLY_FAIL",error+" | rollback="+ (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); diff --git a/tests/asio_backend_registration_test.cpp b/tests/asio_backend_registration_test.cpp index e936486ee..b861f8d41 100644 --- a/tests/asio_backend_registration_test.cpp +++ b/tests/asio_backend_registration_test.cpp @@ -1,8 +1,27 @@ // SPDX-License-Identifier: AGPL-3.0-only #include "../engine/device/AsioPriorityDeviceManager.h" +#include "../engine/device/AudioSetupRecoveryPolicy.h" #include int main() { + using P=armix::device::AudioSetupRecoveryPolicy; + constexpr auto wasapi=P::select(true,true,false,true); + static_assert(wasapi.reuseActivePins && !wasapi.recreateDevice && + wasapi.priorKnownOpen && !wasapi.verifyAsioPinIdentity); + constexpr auto asio=P::select(true,true,true,true); + static_assert(asio.reuseActivePins && asio.recreateDevice && + asio.priorKnownOpen && asio.verifyAsioPinIdentity); + constexpr auto closedAsio=P::select(true,false,true,true); + static_assert(!closedAsio.reuseActivePins && closedAsio.recreateDevice && + !closedAsio.priorKnownOpen && !closedAsio.verifyAsioPinIdentity); + constexpr auto closedWasapi=P::select(true,false,false,true); + static_assert(!closedWasapi.reuseActivePins && closedWasapi.recreateDevice); + constexpr auto freshBackend=P::select(false,true,true,true); + static_assert(!freshBackend.reuseActivePins && !freshBackend.recreateDevice && + freshBackend.priorKnownOpen && !freshBackend.verifyAsioPinIdentity); + constexpr auto noPinDraft=P::select(true,true,true,false); + static_assert(!noPinDraft.reuseActivePins && noPinDraft.recreateDevice && + !noPinDraft.verifyAsioPinIdentity); #if defined(_WIN32) // A headless CI runner need NOT own an ASIO interface. But the Windows // app MUST ship a functioning ASIO backend type, not just a GUI label. diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 5e2f36124..488a62cdf 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1267,6 +1267,12 @@
Reading current audio device…
The output device above is the real destination. A virtual cable does not automatically play through headphones.
+
Advanced · rate, buffer and channel pins @@ -1370,6 +1376,9 @@ rate:0,buffer:0}; } const t=types.find(x=>x.name===deviceChoice.backend); + const asio4allHint=devicePanel.querySelector("[data-audio-asio4all-hint]"); + if(asio4allHint)asio4allHint.hidden=!( + deviceChoice.backend==="ASIO"&&/asio4all/i.test(deviceChoice.capture)); fillAudioSelect("backend",types.map(x=>x.name),deviceChoice.backend); fillAudioSelect("capture",t?.inputs||[],deviceChoice.capture); fillAudioSelect("playback",t?.outputs||[],deviceChoice.playback); From 28871d969b4d4bce944f7b56c4f1ab0c328ffb97 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 07:25:56 +0700 Subject: [PATCH 139/219] test(peq): wait for requestAnimationFrame graph paint before SVG node assertions --- tests/approved_native_peq_smoke.py | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/tests/approved_native_peq_smoke.py b/tests/approved_native_peq_smoke.py index 3d163c1e9..f21a160ff 100644 --- a/tests/approved_native_peq_smoke.py +++ b/tests/approved_native_peq_smoke.py @@ -147,6 +147,11 @@ def main(): assert page.locator(".mx-peq-knob").count()==3 assert page.locator(".mx-peq-band").count()==8 assert page.locator(".mx-peq-graph svg").count()==1 + # Native EQ graph is painted by requestAnimationFrame following the + # accepted-snapshot event. The editor can be visible one frame + # before the SVG is populated; wait for the real rendered line, + # without sleeping or weakening the expected graph assertions. + page.locator(".mx-peq-zero").wait_for(state="attached") assert page.locator(".mx-peq-zero").count()==1 assert page.locator(".mx-peq-graph circle[data-eq-node]").count()==16 bbox=editor.bounding_box() From c73ffb6e2440bf504c7a37f6a870a713e33d7605 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 07:30:04 +0700 Subject: [PATCH 140/219] fix(build): verify native GUI with exact CMake-selected Python and path-level hash diagnostics --- CMakeLists.txt | 4 ++++ scripts/build_approved_native_gui.py | 20 ++++++++++++++++++- scripts/check_approved_native_gui_release.mjs | 8 +++++++- 3 files changed, 30 insertions(+), 2 deletions(-) diff --git a/CMakeLists.txt b/CMakeLists.txt index b047a4f5f..cc615bf51 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -9,6 +9,10 @@ endif() add_subdirectory("${JUCE_ROOT}" "${CMAKE_BINARY_DIR}/juce") find_package(Python3 REQUIRED COMPONENTS Interpreter) +# The independent exact-byte verifier must use the SAME Python interpreter +# selected by CMake to generate compressed favicon/PNG resources (Windows +# runners can have several Python versions with different zlib builds). +file(WRITE "${CMAKE_CURRENT_BINARY_DIR}/approved-gui-python.txt" "${Python3_EXECUTABLE}\n") set(ARMIX_BRAND_DIR "${CMAKE_CURRENT_BINARY_DIR}/brand_icons") execute_process( COMMAND "${Python3_EXECUTABLE}" "${CMAKE_CURRENT_SOURCE_DIR}/scripts/generate_brand_icons.py" diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 1a8d730f2..4212528ef 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -357,7 +357,25 @@ def verify(out: Path) -> dict: expected_out = Path(tmp) / "bundle" expected = stage(expected_out) if existing != expected: - raise ValueError("STALE OR WRONG APPROVED GUI BUNDLE: source/manifest changed") + # Diagnose the exact differing byte source. Never weaken the gate, + # and never hide a Python/zlib or asset generation mismatch behind + # an unhelpful generic manifest error. + mismatches = [] + for key in sorted(set(existing) | set(expected)): + old, new = existing.get(key), expected.get(key) + if old == new: + continue + if key == "files" and isinstance(old, list) and isinstance(new, list): + old_files = {x["path"]: x["sha256"] for x in old} + new_files = {x["path"]: x["sha256"] for x in new} + for path in sorted(old_files.keys() | new_files.keys()): + if old_files.get(path) != new_files.get(path): + mismatches.append( + f"resource={path} existing={old_files.get(path)} regenerated={new_files.get(path)}") + else: + mismatches.append(f"field={key} existing={old!r} regenerated={new!r}") + raise ValueError("STALE OR WRONG APPROVED GUI BUNDLE: " + + "; ".join(mismatches[:4])) paths = {"index.html", "ApprovedGuiResources.h", "approved-gui-manifest.json"} paths.update(p["path"] for p in expected["files"]) for path in sorted(paths): diff --git a/scripts/check_approved_native_gui_release.mjs b/scripts/check_approved_native_gui_release.mjs index 1e6398f7c..88ebef1c7 100644 --- a/scripts/check_approved_native_gui_release.mjs +++ b/scripts/check_approved_native_gui_release.mjs @@ -64,7 +64,13 @@ try { if(/juce_add_binary_data\(ARMixAssets SOURCES\s*web\//.test(cmake) || host.includes('BinaryData::consolenative_html')) block('Forbidden alternative GUI compiled in Windows executable'); - const py=process.env.PYTHON || 'python'; + // CMake's FindPython3 may pick a different interpreter than PATH's + // `python` on Windows. PNG/favicon bytes can differ across zlib versions. + // Reproduce the GUI with the exact Python that made the CMake bundle. + const interpreterNote=join(bundle,'..','approved-gui-python.txt'); + const cmakePython=existsSync(interpreterNote) + ? read(interpreterNote).toString('utf8').trim() : ''; + const py=cmakePython || process.env.PYTHON || 'python'; const result=spawnSync(py,['scripts/build_approved_native_gui.py', '--out',bundle,'--verify'],{cwd:root,encoding:'utf8',timeout:60000}); if(result.error || result.status!==0) From 9de9756c8303a081918bc9fd23195186e1e68128 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 07:33:18 +0700 Subject: [PATCH 141/219] test(gui): attest approved favicon assets alongside exact WIRE PNG bundle --- tests/pages_png_buttons_wire_reconciliation_smoke.py | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/tests/pages_png_buttons_wire_reconciliation_smoke.py b/tests/pages_png_buttons_wire_reconciliation_smoke.py index 76327b950..9640417b6 100644 --- a/tests/pages_png_buttons_wire_reconciliation_smoke.py +++ b/tests/pages_png_buttons_wire_reconciliation_smoke.py @@ -47,8 +47,15 @@ def verify_bundle(dist): assert (generated/"assets"/name).read_bytes()==(OWNER/name).read_bytes(),name canonical={f.name for f in (REFERENCE/"assets").iterdir() if f.is_file()} published={f.name for f in (generated/"assets").iterdir() if f.is_file()} - assert published==canonical|{SPRITE,"arsonmix-approved-runtime.css"},( - "asset set drift",published^canonical) + # The approved app branding now adds exactly three favicon resources to + # the compiled /preview/ folder. Keep the asset set strict and verify + # byte identity against this build's generated public root, not unrelated + # developer-local files or an older locked GUI reference. + favicons={"favicon.ico","favicon-16x16.png","favicon-32x32.png"} + expected=canonical|{SPRITE,"arsonmix-approved-runtime.css"}|favicons + assert published==expected,("asset set drift",published^expected) + for name in favicons: + assert (generated/"assets"/name).read_bytes()==(dist/name).read_bytes(),name for name in canonical-set(SPECIAL): # Compiled CSS is checked byte-for-byte by published_console above. # Uncompiled JS/SVG/font/artwork assets must remain exact source bytes. From d171b245376650c6d09011fcc59773d9fc9d094d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 08:28:01 +0700 Subject: [PATCH 142/219] fix(packaging): use exact CMake Python for icon provenance; document device-independent mixer session design --- ...VICE_INDEPENDENT_MIXER_SESSION_20261107.md | 147 ++++++++++++++++++ scripts/package_native_windows.ps1 | 4 +- scripts/resolve_approved_gui_python.ps1 | 17 ++ scripts/verify_native_windows_artifact.ps1 | 4 +- ...ative_artifact_packaging_contract_test.mjs | 15 ++ 5 files changed, 185 insertions(+), 2 deletions(-) create mode 100644 docs/ADR_DEVICE_INDEPENDENT_MIXER_SESSION_20261107.md create mode 100644 scripts/resolve_approved_gui_python.ps1 diff --git a/docs/ADR_DEVICE_INDEPENDENT_MIXER_SESSION_20261107.md b/docs/ADR_DEVICE_INDEPENDENT_MIXER_SESSION_20261107.md new file mode 100644 index 000000000..1b16f5229 --- /dev/null +++ b/docs/ADR_DEVICE_INDEPENDENT_MIXER_SESSION_20261107.md @@ -0,0 +1,147 @@ +# ADR — ArSonMix Device-Independent Mixer Session & Crash-Safe Resume +**Status: IMPLEMENTATION DESIGN / NOT YET IMPLEMENTED** +**Date:** 2026-11-07 +**Canonical integration:** PR #418, preserve ONE JUCE audio callback, native ChannelId PCM ownership, and the single assembled `/preview/` GUI. +**Driver incident:** Operator confirms WASAPI works; ASIO4ALL was reconfigured from existing WDM inputs to VB-Cable capture + Realtek playback and the host showed `Current device is not open; refresh`. Software replay is not physical qualification. + +## 0. Non-negotiable user outcomes + +1. Device selection, driver sample-rate/buffer, pin setup, and driver loss **NEVER erase mixer content**: channel IDs/order/names, channel format, faders/PAN/MUTE/SOLO, EQ and builtin effects, VST3 chains/slot identities/params/bypass/order and available saved binary states, groups/AUX/MON/MATRIX/CUE that are actually supported, sends, WIRE edges/gains, bus/master settings, routing intents, and GUI user workflow. Maintain EXACT values, not defaults. +2. Opening an Audio I/O window without committing hardware change MUST NOT mutate, discard, re-create, or reset the accepted mixer graph. +3. A different hardware device can invalidate PHYSICAL endpoint bindings only. Keep every mixer control and internal edge intact. Mark unresolved physical IN and OUT as **NEEDS REMAP**. Do not infer that "ASIO4ALL v2" on both selectors proves VB-Cable IN or Realtek OUT; require current driver port readback and identity evidence. +4. On restart, reopen the **last verified mixer document** immediately, even if no device can open; the mixer looks as previously used, but all hardware outputs remain DISARMED until a fresh verified device, routing and explicit user ARM. +5. Named user snapshots/Shows and "Latest Session" auto recovery are distinct features: users can save immutable presets and return to them, while autosave is an unobtrusive crash-safe last-known-good working state. +6. No extra callback, JS/WebAudio DSP, audio-thread disk I/O, graph rebuild on GUI navigation, optimistic ACK, automatic output routing or auto-unmute. Preserve existing `/preview/` geometry and approved icon. + +## 1. Audit findings, current source (PR #418 at design time) + +- `src/LiveAudioEngine.h::beginManualAudioSetup()` calls `dryRoutingLab_.disable()`; `finishManualAudioSetup()` invokes `startUnpatchedProductionSession()`. `LiveDryRoutingLab::startUnpatchedSession()` explicitly creates ten NONE sources, gains 0.25, neutral pans and zero sends: a real native mixer reset. +- `src/Main.cpp::showDeviceSetup()` invokes `beginManualAudioSetup()` **on opening the native JUCE settings window**, and calls `finishManualAudioSetup()` when closed; `applyCustomAudioDevice()` uses the same reset machinery. Both entrypoints must be transactionally unified. Merely closing a settings window must not replace a session. +- `LiveDryRoutingLab::prepareDevice/deviceStopped` increment a *transient* device epoch and revoke valid hardware masks. This is correct for hardware safety, but NOT evidence that the user-authored mixer document should be thrown away. +- `web/approved-native-bridge.js::refreshRealM4Inputs()` may reset presented input to None when native authoritative state is unpatched; UI must preserve document draft and display `NEEDS REMAP` without falsely claiming active PCM. +- `NativeLiveShowCapture`/`NativeDryShowRecall`/`NativeShowSchema` and `NativeShowStore` already offer useful transactional snapshot, checksum and immutable HEAD primitives. Their current fixed 10 CH + 4 AUX schema does NOT losslessly represent today's dynamic ChannelId GROUP/FX RETURN/WIRE graph. Do not repurpose this restricted format as full-session autosave or silently drop extra buses. +- `StudioBackup` is a user-directed whole-Studio export with integrity manifest. It is NOT startup autosave. +- Windows FAT run 42318730495: MSVC builds, CTest **58/58 PASS**, package fails due to a different `favicon.ico` hash during `scripts/package_native_windows.ps1` regeneration. CMake-selected Python is recorded in `build/approved-gui-python.txt`, while the packager independently invoked PATH `python`; the optional final verification script made the same mistake. Preserve SHA guard and use the exact CMake interpreter at BOTH boundaries. The generated current branding cannot be considered delivered until ZIP + embedded PE icon checks pass. + +## 2. Architecture — two lifetimes, one native authority + +```text + UI /preview/ — draft gestures and commands only + | + Native CONTROL owner + | + MixerSessionStore / SessionDocument + stable ChannelId / BusId / EdgeId / FxSlotId / revision + / | \ + Live immutable PCM DeviceBinding Persistence I/O + graph + FX leases (runtime epoch) .stage + HEAD + LKG + one JUCE callback masks / ports snapshots + autosave + \ / + DeviceApplyCoordinator (one serialized transaction) + | + ONE JUCE AudioDeviceManager +``` + +- **MixerSessionDocument (durable)**: stable logical identity + channels, buses, WIRE edges, matrix/group sends, source *intent*, FX chain references and bypass, channel controls, EQ states, master controls, UI workspace hints, named scenes. Does not embed a driver object, device epoch, callback pointers, realtime counters, screen DOM state or "output armed" permission. +- **AudioDeviceProfile (durable but independent)**: chosen backend and registered driver identity, separate endpoint identity where actually available, preferred sample rate and period, preferred physical pin roles, optional compatible hardware profile. The profile is a *preference*, not proof an output is safe or connected. +- **DeviceBinding (ephemeral)**: current JUCE device instance, verified sparse physical pin masks/labels, actual rate/period, callback generation/epoch, authorization, active mappings, failure causes and monitoring armed state. It may become unbound without modifying the mixer document. +- **PreparedRealtimeGraph (ephemeral/rebuildable)**: prepared render graph, channel buffers, plugin runtime instances/leases and PDC for current device format. Re-preparation on rate/buffer/port change is permitted, but the serialized user mixer state remains immutable and can rebuild exactly on a compatible device. +- **SessionStore** owns accepted model. All UI readbacks and effect commands derive from accepted native state. A device ACK does not declare restored routing LIVE; a later native graph generation/readback is required. Control, device and document revisions are separately monotonic; do not copy temporary device epochs into serialized IDs. + +## 3. DeviceApplyCoordinator — two-phase, idempotent, silence-safe + +**Before any mutation:** +- Gate one transaction by requestId, expected document revision, device generation and pending FX/Show work. Capture/pin an immutable **accepted MixerSessionDocument** and references to existing native VST3 leases; do not stop or erase logical routing. A device chooser opening should display current values without entering this state. +- Preflight current output state. Require explicit user review and disarm before hardware reassignment. Keep the single direct output safety fence; disarm secondary stream. Never secretly switch from ASIO to WASAPI, another speaker, or an arbitrary first enumerated port. +- Capture a non-RT complete safe checkpoint. For VST3 states that cannot be captured safely while live, retain the last verified state blob and mark it **DIRTY / SAVE PENDING**; never claim a lossless vendor snapshot. Do not block the callback for disk/JSON/plugin serialization. + +**Apply**: +```text +IDLE -> STAGE_DOCUMENT -> QUIESCE_OUTPUT -> OPEN_NEW_DEVICE + -> VERIFY_IDENTITY + PIN_ROLES + RATE/BUFFER -> PREPARE_NEW_GRAPH + -> VALIDATE_DOCUMENT + BIND_HARDWARE -> ATOMIC_GRAPH_SWAP + -> READBACK -> ACCEPTED_MUTED (or NEEDS_REMAP_MUTED) + +failure: OLD_DOCUMENT_INTACT -> attempt verified old-device restore once + -> RESTORED_MUTED or RECOVERY_REQUIRED (old document still intact) +``` + +- Hold complete logical graph and channel controls in the session model throughout the device change. For unchanged hardware port identity, compatible remapping is eligible; for swapped/disappeared/ambiguous ASIO4ALL WDM pins, preserve the routing *intent*, but mark unresolved bindings DISCONNECTED / NEEDS_REMAP and stay muted. +- If rate/block changes, call correct JUCE/VST3 preparation on control-supported threads; vendor processing tails may reset and audible interruption is unavoidable. User values, FX order and available serialized plugin state must survive. No guarantee of seamless hot-switch between clocks. +- A rejected driver open, partial readback, post-open identity mismatch or plugin prepare failure may never publish a default mixer as the accepted document. An unavailable plugin becomes a visible offline/missing placeholder with its stored state retained; it cannot cause accidental bypass of every other chain. +- Publish new graph and document binding together only when identities and routes are valid, with bounded RT-safe handoff; report route acceptance separately from device openness. No per-callback locks, allocations, logging, disk I/O or vendor GUI work. +- After success the mixer should **LOOK THE SAME**. Physical device-bound badges alone may change to NEEDS REMAP. Explicit user ARM after checking a real input and real output is still required. + +## 4. Persistence & recovery, on user's actual Studio workspace + +Use the existing `PortableWorkspace::dataRoot()` and current Studio backup conventions. Do not create a competing config root or store project truth in browser localStorage. + +**Versioned schema** `arsonmix.mixer-session.v1`, with build ID, schema version, stable document UUID, document revision, graph IDs, typed processing topology, logical routing, source intent, FX slot IDs/canonical catalog IDs, VST/plugin state SHA references, EQ parameters, snapshot metadata, UI view state and external hardware profile reference. Enforce total size, per-effect state caps, node/edge limits, unique IDs, acyclic graph and supplied plugin hash checks. Migrations must not coerce unsupported dynamic buses into 10+4 or silently discard WIRE. + +**Store layout (proposed):** +```text +Studio/Sessions// + HEAD # small atomic generation pointer + versions// + session.json # complete validated mixer document + blobs/.bin # content-addressed vendor state + manifest.json # per-file SHA, schema, length, source revision + recovery/ # bounded last-known-good / failed draft metadata +Studio/DeviceProfiles/.json # independent hardware preferences +Studio/Shows/ # existing user-named Shows untouched +``` + +Write **stage -> validate -> readback hash -> atomic commit/pointer swap**. Preserve at least two last-known-good generations, never overwrite a valid HEAD with a partial write. Include bounded orphan cleanup only off RT and only after successful commits. Support crash between any two filesystem operations and corrupt or read-only folders; load last-good and give an actionable read-only/recovery status rather than resetting to defaults. Verify portable/installed data roots use identical semantics. + +**Autosave policy:** +- Save only native **accepted** changes (not pending GUI gestures) and only when the accepted document revision advances. Debounce normal scalar changes, coalesce fader movement and persist a compact document generation; a single fader drag is one accepted gesture, not 60 writes per second. For structural edits, write a checkpoint at acceptance and avoid unrelated repeat snapshots. +- Vendor state can require different safe thread-affinity/quiescence: separate its checkpoint from high-rate fader saves. Never call arbitrary VST3 `getStateInformation` from realtime callback or while device teardown is in progress. Publish “Latest saved / Pending plugin state” truthfully. +- Manual **Save Snapshot** creates an immutable named revision; **Recall Snapshot** preflights and atomically prepares, with a one-step undo checkpoint. **Latest Session** is not a snapshot scene, and **Save Show** is not startup autosave. Preserve existing Shows/Studio Backup and introduce explicit user-level session import/export separately. +- On normal application exit, attempt a bounded final commit on the correct non-RT owner. After crash, prefer last verified fully committed generation; never trust a partial last gesture or partial plugin blob. + +**Cold startup**: +1. Verify last-good session on disk (schema, checksums, stable IDs). Render saved mixer workspace even with hardware disconnected; show clearly which device/profile is missing. +2. Discover hardware without choosing an unsafe substitute. Match exact physical port roles only with sufficient identity evidence. Unresolved physical routing gets NEEDS REMAP, all outputs DISARMED and a non-destructive device selector. +3. Prepare graph after device has been explicitly verified; publish native acceptance/ACK, then offer user-controlled ARM. Do not start loud audio from persisted "MONITOR ON" or saved meter levels. + +## 5. UI acceptance on the ONE approved /preview/ + +Keep current compact premium console; no new bulky wizard. A small existing status area displays e.g. `Latest session saved`, `Saving…`, `FX state pending`, `Output muted · verify mapping` or `3 inputs need remap`. A single **Snapshots** drop-down offers named Save, Recall, Rename/Remove and Restore Last Good. Device change does not trigger a full track list re-creation; reconcile by stable ChannelId and only update physical pin choices/status. Never render `None` over a saved but temporarily unresolved physical source *intent*. Never claim the old input is currently LIVE without driver readback. + +## 6. Provenance: approved latest icon is a release contract + +Brand reference = current approved `assets/icon/brand-source-128.png` and committed `assets/icon/arsonmix-app.ico`, `site/favicon.ico`, `site/favicon-16x16.png`, `site/favicon-32x32.png` on latest reconciled `main`. Current `CMakeLists.txt` uses `ICON_BIG/ICON_SMALL` from generated PNG; `src/Main.cpp` calls `setIcon(approvedAppIcon())` for windows; `build_pages.py` includes favicons in public preview. All are **source wiring**, not proof of installed EXE. +- Fix the exact packaging verifier interpreter mismatch without disabling the SHA test. +- Verify source hash + committed icon bytes, run consistent generation, assert EXE PE icon group rendered pixels match approved PNG at supported sizes; check native window/titlebar and WebView2 favicon after build. Validate actual artifact exe and ZIP SHA + embedded sourceCommit. Do not claim the icon is delivered while the ZIP lane is red. +- Prefer eventually shipping byte-exact pre-approved sealed icon resources across build machines (no Python/zlib-dependent compressed-byte drift); retain an independent derived-pixel verifier. + +## 7. Deterministic qualification matrix + +**Pure native session/control tests**: +- 10CH+4AUX and dynamic GROUP/FX RETURN/ChannelId/WIRE multiple edges: capture doc -> change device -> same IDs and exact fader/EQ/FX/bypass/latency/graph controls -> reconnect (including ASIO4ALL reorder). +- Device dialog open/cancel, same-device APPLY with unchanged pins, sample rate/buffer only, ASIO closed reopen, changed Realtek/VB-Cable pins, device busy/rejected, rollback success and failure. In ALL cases: original document stays complete; no auto monitor ARM. +- Disconnect/reconnect while current source identity absent, invalid sparse pin indices and ambiguous ASIO4ALL names; never silently wire channel A to device B. +- Vendor VST3 state success/failure/stale lease, editor open, missing plugin, plugin changed sample rate, save/recall mid-graph change. Exact acknowledged prior generation retained. +- Persistence fault injection: crash after stage/manifest/rename/HEAD, corrupt JSON/hash, low disk, read-only portable path, malformed graph, duplicate IDs, oversized FX blob, migration from ShowV2; no truncated/excessive memory or write in RT. + +**UI/Windows/physical gates**: +- Full Chromium captures identical MIXER/FX/ROUTE visual positions at 1366/1680/1920 and bank mode. Device-change ACK must preserve every on-screen accepted control and stable wire ID while only hardware-unsupported port states become NEEDS REMAP. +- Exact-SHA Windows MSVC + native CTest + independently verified FAT ZIP. Pin/branding PE evidence and clean reinstall/portable second-run last-session recall. +- Physical WASAPI and ASIO4ALL with VB-Cable capture and Realtek render: compare same mix/FX order before/after reconfiguration and relaunch, no phantom output to speakers, measure crackle/latency/clock drift. Software PASS != hardware PASS. + +## 8. Milestones (one meaningful integration PR, avoid naive patch stacking) + +| Phase | Product deliverable | Exit criterion | +|---|---|---| +| P0 release integrity | Fix packaging Python provenance, source/PE branding checks | Same-SHA FAT ZIP produced, independently verified, not claimed physical pass | +| P1 state ownership | Document/DeviceBinding separation; no mixer destructive mutation when opening/changing Audio Setup | All supported mixer controls preserved across ASIO/WASAPI/same-device APPLY and driver failure; native regression matrix | +| P2 persistent work | Versioned full ChannelId SessionStore, fast accepted-revision autosave, named snapshot & crash recovery | Complete dynamic graph and available FX state round-trip after cold restart, corruption rollback; no RT cost | +| P3 hardware recovery UX | Identity-safe physical port profile/remap, missing VST placeholder and explicit re-arm | VB-Cable→Realtek ASIO4ALL and WASAPI test; no silent misrouting/reset; readable diagnostics | +| P4 release qualification | Whole workflow, UI parity, exact SHA ZIP and actual hardware FAT | Repeatable soak/clock/latency/crackle evidence; staged PR review then merge main when qualified | + +**Conservative launch scope:** do not silently migrate legacy Show storage into complete SessionStore. Full session serializer must first round-trip native ChannelId state including extra buses and WIRE before making autosave the default. Do not use blind `startUnpatchedProductionSession()` as a recovery step once a user-authored document exists. + +## Handoff and safety + +- Current main at audit: `f96c09ec33da36c723aff3ae73b9b42d7db3fa7e`. Current draft integration PR #418 at audit: `9de9756c8303a081918bc9fd23195186e1e68128`. Both must be rechecked before implementation and merge. +- The architecture above is a **design**. Only the packaging interpreter fix is small implementation work in this checkpoint. No claim of implemented session retention, autosave, plugin state preservation across hardware restart, or physical ASIO4ALL PASS yet. diff --git a/scripts/package_native_windows.ps1 b/scripts/package_native_windows.ps1 index a1881b24c..f925571a0 100644 --- a/scripts/package_native_windows.ps1 +++ b/scripts/package_native_windows.ps1 @@ -61,7 +61,9 @@ if ($LASTEXITCODE -ne 0 -or $gitSha -notmatch '^[0-9a-f]{40}$') { # Refuse a valid PE/CTest artifact which embeds the WRONG browser renderer. # This is the source/asset attestation for the exact approved Pages GUI. $approvedGuiDir = Join-Path $BuildDir "approved_gui" -& python scripts/build_approved_native_gui.py --out $approvedGuiDir --verify +. (Join-Path $PSScriptRoot "resolve_approved_gui_python.ps1") +$approvedGuiPython = Resolve-ArSonMixApprovedGuiPython -BuildDir $BuildDir +& $approvedGuiPython scripts/build_approved_native_gui.py --out $approvedGuiDir --verify if ($LASTEXITCODE -ne 0) { throw "APPROVED GUI PROVENANCE MISMATCH: generated bundle differs from Pages" } $approvedGuiManifestPath = Join-Path $approvedGuiDir "approved-gui-manifest.json" $approvedGui = Get-Content -LiteralPath $approvedGuiManifestPath -Raw -Encoding UTF8 | ConvertFrom-Json diff --git a/scripts/resolve_approved_gui_python.ps1 b/scripts/resolve_approved_gui_python.ps1 new file mode 100644 index 000000000..8d3e18b5b --- /dev/null +++ b/scripts/resolve_approved_gui_python.ps1 @@ -0,0 +1,17 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Exact byte-for-byte /preview/ verifier must run under the interpreter +# selected by CMake for its generated favicon/PNG resources. A different +# Python/zlib from PATH may emit different PNG/ICO compressed bytes. +function Resolve-ArSonMixApprovedGuiPython { + param([Parameter(Mandatory=$true)][string] $BuildDir) + $note = Join-Path $BuildDir "approved-gui-python.txt" + if (-not (Test-Path -LiteralPath $note -PathType Leaf)) { + throw "CMake Python provenance missing: $note" + } + $selected = (Get-Content -LiteralPath $note -Raw -Encoding UTF8).Trim() + if ([string]::IsNullOrWhiteSpace($selected) -or + -not (Test-Path -LiteralPath $selected -PathType Leaf)) { + throw "CMake-selected Python unavailable; refusing unverified GUI regeneration" + } + return (Resolve-Path -LiteralPath $selected).Path +} diff --git a/scripts/verify_native_windows_artifact.ps1 b/scripts/verify_native_windows_artifact.ps1 index f11114569..b6871d289 100644 --- a/scripts/verify_native_windows_artifact.ps1 +++ b/scripts/verify_native_windows_artifact.ps1 @@ -98,7 +98,9 @@ if ($LASTEXITCODE -ne 0 -or $sha -ne $manifest.sourceCommit) { # Release gate must verify the EXACT GUI shown by /preview/, not a # self-consistent but WRONG legacy web/index.html or console-native renderer. $approvedGuiDir = Join-Path "build" "approved_gui" -& python scripts/build_approved_native_gui.py --out $approvedGuiDir --verify +. (Join-Path $PSScriptRoot "resolve_approved_gui_python.ps1") +$approvedGuiPython = Resolve-ArSonMixApprovedGuiPython -BuildDir "build" +& $approvedGuiPython scripts/build_approved_native_gui.py --out $approvedGuiDir --verify if ($LASTEXITCODE -ne 0) { throw "REJECT: native GUI is not built from current approved Pages" } $approvedPath = Join-Path $approvedGuiDir "approved-gui-manifest.json" $approved = Get-Content -LiteralPath $approvedPath -Raw -Encoding UTF8 | ConvertFrom-Json diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index 126c24cda..56540c1db 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -10,6 +10,7 @@ import './m3e_fat_evidence_gate.test.mjs'; const read=path=>readFileSync(path,'utf8'); const workflow=read('.github/workflows/p1-windows.yml'); const packaging=read('scripts/package_native_windows.ps1'); +const pythonProvenance=read('scripts/resolve_approved_gui_python.ps1'); const verify=read('scripts/verify_native_windows_artifact.ps1'); const nativeMain=read('src/Main.cpp'); const cmake=read('CMakeLists.txt'); @@ -17,6 +18,20 @@ const generator=read('scripts/build_approved_native_gui.py'); const adapter=read('web/approved-native-bridge.js'); const fat=read('docs/HARDWARE_FAT_GUI10_ENGINE_P012_20261027.md'); + +test('packaging and independent ZIP verifier use the exact CMake Python, never PATH python for icon recompression',()=>{ + for(const script of [packaging,verify]){ + assert.match(script,/resolve_approved_gui_python\.ps1/); + assert.match(script,/Resolve-ArSonMixApprovedGuiPython/); + assert.match(script,/& \$approvedGuiPython scripts\/build_approved_native_gui\.py --out \$approvedGuiDir --verify/); + assert.doesNotMatch(script,/& python scripts\/build_approved_native_gui\.py/); + } + assert.match(cmake,/approved-gui-python\.txt/); + assert.match(pythonProvenance,/approved-gui-python\.txt/); + assert.match(pythonProvenance,/Test-Path -LiteralPath \$selected -PathType Leaf/); + assert.match(pythonProvenance,/refusing unverified GUI regeneration/); +}); + test('native FAT picks exact JUCE GUI target, not a test executable',()=>{ assert.match(cmake,/juce_add_gui_app\(ARMixConsole/); assert.match(cmake,/PRODUCT_NAME "AR MIX Studio"/); From c2516dfec76915b8da56fb75ad1477a5c6eec4cc Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 08:50:29 +0700 Subject: [PATCH 143/219] test(release): independently attest compiled Windows PE app icon pixels and icon groups --- scripts/package_native_windows.ps1 | 4 + scripts/verify_native_windows_artifact.ps1 | 3 + scripts/verify_windows_pe_brand_icon.py | 163 ++++++++++++++++++ ...ative_artifact_packaging_contract_test.mjs | 14 ++ 4 files changed, 184 insertions(+) create mode 100644 scripts/verify_windows_pe_brand_icon.py diff --git a/scripts/package_native_windows.ps1 b/scripts/package_native_windows.ps1 index f925571a0..1e6390bdc 100644 --- a/scripts/package_native_windows.ps1 +++ b/scripts/package_native_windows.ps1 @@ -63,6 +63,10 @@ if ($LASTEXITCODE -ne 0 -or $gitSha -notmatch '^[0-9a-f]{40}$') { $approvedGuiDir = Join-Path $BuildDir "approved_gui" . (Join-Path $PSScriptRoot "resolve_approved_gui_python.ps1") $approvedGuiPython = Resolve-ArSonMixApprovedGuiPython -BuildDir $BuildDir +# Validate the ACTUAL compiled Windows taskbar/EXE icon against the approved +# committed PNG, not merely CMake resource names or an unverified .ico. +& $approvedGuiPython scripts/verify_windows_pe_brand_icon.py --exe $app --approved assets/icon/arsonmix-256.png +if ($LASTEXITCODE -ne 0) { throw "WINDOWS BRAND PE ICON MISMATCH: compiled app icon differs from approved ArSonMix" } & $approvedGuiPython scripts/build_approved_native_gui.py --out $approvedGuiDir --verify if ($LASTEXITCODE -ne 0) { throw "APPROVED GUI PROVENANCE MISMATCH: generated bundle differs from Pages" } $approvedGuiManifestPath = Join-Path $approvedGuiDir "approved-gui-manifest.json" diff --git a/scripts/verify_native_windows_artifact.ps1 b/scripts/verify_native_windows_artifact.ps1 index b6871d289..8f20d7c3b 100644 --- a/scripts/verify_native_windows_artifact.ps1 +++ b/scripts/verify_native_windows_artifact.ps1 @@ -100,6 +100,9 @@ if ($LASTEXITCODE -ne 0 -or $sha -ne $manifest.sourceCommit) { $approvedGuiDir = Join-Path "build" "approved_gui" . (Join-Path $PSScriptRoot "resolve_approved_gui_python.ps1") $approvedGuiPython = Resolve-ArSonMixApprovedGuiPython -BuildDir "build" +# Independent post-package check of the EXE that will go INSIDE the ZIP. +& $approvedGuiPython scripts/verify_windows_pe_brand_icon.py --exe $exePath --approved assets/icon/arsonmix-256.png +if ($LASTEXITCODE -ne 0) { throw "REJECT: distributed Windows PE icon does not match current approved brand" } & $approvedGuiPython scripts/build_approved_native_gui.py --out $approvedGuiDir --verify if ($LASTEXITCODE -ne 0) { throw "REJECT: native GUI is not built from current approved Pages" } $approvedPath = Join-Path $approvedGuiDir "approved-gui-manifest.json" diff --git a/scripts/verify_windows_pe_brand_icon.py b/scripts/verify_windows_pe_brand_icon.py new file mode 100644 index 000000000..a9942030b --- /dev/null +++ b/scripts/verify_windows_pe_brand_icon.py @@ -0,0 +1,163 @@ +#!/usr/bin/env python3 +"""Attest actual Windows PE RT_GROUP_ICON pixels against the approved source. + +Stdlib only: parse x64 PE resources and compare 256px icon RGBA to the +committed brand. JUCE/Windows premultiplied RGB conversions may round a +visible component by 1-2; alpha must match exactly, RGB <=3 composite units. +""" +import argparse +from pathlib import Path +import struct +import sys +from generate_brand_icons import read_png + + +def check(data: bytes, expected: Path): + def bounds(offset, size): + if offset < 0 or size < 0 or offset + size > len(data): + raise ValueError("Corrupt PE resource bounds") + def u16(offset): + bounds(offset, 2) + return struct.unpack_from(" 1024: + raise ValueError("Excessive PE resource entries") + bounds(pos+16, count*8) + result=[] + for i in range(count): + ident, offset = struct.unpack_from(" 255: + raise ValueError("Invalid resource group name") + bounds(name_offset+2, nchars*2) + ident = data[name_offset+2:name_offset+2+nchars*2].decode("utf-16le") + else: + ident &= 0x7fffffff + result.append((ident, offset)) + return result + resources={} + for resource_type, type_node in entries(0): + if resource_type not in (3, 14): + continue + if not type_node & 0x80000000: + raise ValueError("Malformed icon resource type") + parts={} + for name, lang_node in entries(type_node & 0x7fffffff): + if not lang_node & 0x80000000: + raise ValueError("Missing icon language tree") + for _, leaf in entries(lang_node & 0x7fffffff): + if leaf & 0x80000000: + raise ValueError("Nested icon data") + pos = root+(leaf & 0x7fffffff) + bounds(pos, 16) + rva, size, _, _ = struct.unpack_from(" 1024*1024: + raise ValueError("Oversized icon resource") + off=file_offset(rva, size) + parts.setdefault(name, data[off:off+size]) + resources[resource_type]=parts + images=resources.get(3,{}) + groups=resources.get(14,{}) + if not groups or not images: + raise ValueError("Windows EXE is missing RT_GROUP_ICON/RT_ICON") + size, expected_rows = read_png(expected) + if size != 256: + raise ValueError("Committed approved brand icon is not 256px") + checked=0 + required={16,32,48,256} + for name, group in groups.items(): + if len(group)<6: + raise ValueError("Truncated icon group") + reserved,kind,count=struct.unpack_from("3*255: + raise ValueError(f"Icon differs from approved brand x={pos//4} y={y}") + checked+=1 + if required-found: + raise ValueError(f"Windows icon {name} missing sizes {sorted(required-found)}") + if checked!=len(groups): + raise ValueError("Every PE icon group must match approved ArSonMix pixels") + return checked + + +def main(): + parser=argparse.ArgumentParser() + parser.add_argument("--exe",required=True,type=Path) + parser.add_argument("--approved",required=True,type=Path) + args=parser.parse_args() + try: + n=check(args.exe.read_bytes(),args.approved) + except (ValueError,OSError,struct.error,IndexError) as exc: + print("PE_BRAND_ICON_REJECTED: "+str(exc),file=sys.stderr) + return 1 + print(f"PE_BRAND_ICON_VERIFIED: {n} Windows icon groups, 16/32/48/256px, approved alpha and visible RGB") + return 0 + + +if __name__=="__main__": + sys.exit(main()) diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index 56540c1db..0e8e4392c 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -11,6 +11,7 @@ const read=path=>readFileSync(path,'utf8'); const workflow=read('.github/workflows/p1-windows.yml'); const packaging=read('scripts/package_native_windows.ps1'); const pythonProvenance=read('scripts/resolve_approved_gui_python.ps1'); +const iconVerifier=read('scripts/verify_windows_pe_brand_icon.py'); const verify=read('scripts/verify_native_windows_artifact.ps1'); const nativeMain=read('src/Main.cpp'); const cmake=read('CMakeLists.txt'); @@ -32,6 +33,19 @@ test('packaging and independent ZIP verifier use the exact CMake Python, never P assert.match(pythonProvenance,/refusing unverified GUI regeneration/); }); +test('EXE and independently ZIP-distributed PE icons must match approved source RGBA',()=>{ + for(const script of [packaging,verify]){ + assert.match(script,/& \$approvedGuiPython scripts\/verify_windows_pe_brand_icon\.py --exe/); + assert.match(script,/--approved assets\/icon\/arsonmix-256\.png/); + assert.match(script,/LASTEXITCODE -ne 0/); + } + assert.match(iconVerifier,/RT_GROUP_ICON\/RT_ICON/); + assert.match(iconVerifier,/read_png\(expected\)/); + assert.match(iconVerifier,/actual_rows=read_png/); + assert.match(iconVerifier,/old\[pos\+3\]!=actual\[pos\+3\]/); + assert.match(iconVerifier,/required=\{16,32,48,256\}/); +}); + test('native FAT picks exact JUCE GUI target, not a test executable',()=>{ assert.match(cmake,/juce_add_gui_app\(ARMixConsole/); assert.match(cmake,/PRODUCT_NAME "AR MIX Studio"/); From 3f6e9661887a737ce51d42afb06ac47e703e21f9 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 08:50:57 +0700 Subject: [PATCH 144/219] test(release): tolerate whitespace in PE pixel-verifier contract --- tests/native_artifact_packaging_contract_test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/native_artifact_packaging_contract_test.mjs b/tests/native_artifact_packaging_contract_test.mjs index 0e8e4392c..eacc94ebd 100644 --- a/tests/native_artifact_packaging_contract_test.mjs +++ b/tests/native_artifact_packaging_contract_test.mjs @@ -41,7 +41,7 @@ test('EXE and independently ZIP-distributed PE icons must match approved source } assert.match(iconVerifier,/RT_GROUP_ICON\/RT_ICON/); assert.match(iconVerifier,/read_png\(expected\)/); - assert.match(iconVerifier,/actual_rows=read_png/); + assert.match(iconVerifier,/actual_rows\s*=\s*read_png/); assert.match(iconVerifier,/old\[pos\+3\]!=actual\[pos\+3\]/); assert.match(iconVerifier,/required=\{16,32,48,256\}/); }); From 2363c38d81690d9cb14f775849d26b071545529b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 10:05:15 +0700 Subject: [PATCH 145/219] fix(audio): retain authored mixer across Audio I/O entry and fail closed on unbound devices --- CMakeLists.txt | 4 ++ ..._NONDESTRUCTIVE_DEVICE_SESSION_20261107.md | 30 +++++++++++++++ engine/device/DeviceSessionTransitionPolicy.h | 28 ++++++++++++++ src/LiveAudioEngine.h | 38 ++++++++++++++++--- src/LiveDryRoutingLab.h | 15 ++++++++ src/Main.cpp | 11 +++++- .../device_session_transition_policy_test.cpp | 37 ++++++++++++++++++ 7 files changed, 155 insertions(+), 8 deletions(-) create mode 100644 docs/P1_NONDESTRUCTIVE_DEVICE_SESSION_20261107.md create mode 100644 engine/device/DeviceSessionTransitionPolicy.h create mode 100644 tests/device_session_transition_policy_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index cc615bf51..74bd93196 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -177,6 +177,10 @@ if(BUILD_TESTING) target_link_libraries(ARMixNativeDrySendTests PRIVATE juce::juce_core juce::juce_recommended_config_flags) target_compile_features(ARMixNativeDrySendTests PRIVATE cxx_std_20) add_test(NAME LiveNativePrePostSendAndBusContract COMMAND ARMixNativeDrySendTests) + # Device reopen must not silently replace an authored ChannelId mixer. + add_executable(ARMixDeviceSessionTransitionTests tests/device_session_transition_policy_test.cpp engine/device/DeviceSessionTransitionPolicy.h) + target_compile_features(ARMixDeviceSessionTransitionTests PRIVATE cxx_std_20) + add_test(NAME NonDestructiveAudioSetupRetainsMixerDocument COMMAND ARMixDeviceSessionTransitionTests) add_executable(ARMixLiveRoutingEpochTests tests/live_port_epoch_publisher_test.cpp) target_compile_features(ARMixLiveRoutingEpochTests PRIVATE cxx_std_20) add_test(NAME P1ELivePortGenerationRevisionAndRealtimeRetirement COMMAND ARMixLiveRoutingEpochTests) diff --git a/docs/P1_NONDESTRUCTIVE_DEVICE_SESSION_20261107.md b/docs/P1_NONDESTRUCTIVE_DEVICE_SESSION_20261107.md new file mode 100644 index 000000000..fdec29220 --- /dev/null +++ b/docs/P1_NONDESTRUCTIVE_DEVICE_SESSION_20261107.md @@ -0,0 +1,30 @@ +# P1-A — Non-destructive Audio I/O session protection + +**Integration owner:** PR #418 on `integration/daw-direct-hardware-input-20261105`. **Status: partial protection, NOT full device rebind or restart resume.** + +## Causal correction + +The prior `beginManualAudioSetup()` invoked `dryRoutingLab_.disable()`, releasing the accepted M4/ChannelId publishers, FX leases, WIRE graph and live controls on **dialog open**. `finishManualAudioSetup()` then created a fresh unpatched 10CH/4AUX graph even if the operator closed the selector without changing hardware. + +The P1-A changes retain that accepted graph on setup entry, keep both outputs disarmed while device selection happens, and bypass default graph recreation when the accepted routing is still ready for the current hardware epoch. A driver change/failure preserves authored state **in process** but stops short of falsely claiming live PCM: the session remains unbound and muted until a future complete, verified rebind transaction is implemented. Other diagnostic/independent-clock paths now refuse to discard authored graph state without that transaction. This is containment, not full recovery. + +## Explicit limitations / next critical engineering work + +- The existing JUCE selector applies edits immediately; it is not a staged Cancel/Apply UX. A no-change close preserves the graph but leaves output muted for safety. Hardware changes require real identity, mask, sample-rate, buffer, FX preparation, graph publication and ACK validation. +- On an actual epoch change, the in-memory accepted logical graph and plugin lease data are **retained but not yet rebound or guaranteed to be fully visible**. Do not clear the mixer, fake a success ACK, use default endpoints, arm output, or call an M4-only Show recall to repair it. Restart does not yet restore this retained session. +- Before P1 can be marked complete, implement canonical MixerSessionDocument with durable stable IDs and complete FX state, safe DeviceApplyCoordinator, full dynamic graph rebind and GUI NEEDS REMAP projection. +- P2 crash-safe last-good generation, snapshots, plugin state blobs and restart resume remain pending. +- P3 timed VST3 catalog/cache and editor restore, P4 Inno Setup, P5 signed-update verification and installer qualification remain pending. +- Physical WASAPI/ASIO4ALL hardware FAT remains PENDING; green CTest cannot establish audible latency, sample-clock stability or sound quality. + +## Regression evidence + +The new C++ policy suite exercises all 8 verified/bound/authored combinations, asserting **createFirstSilentMixer** is legal only when no authored content exists. The policy is invoked directly by native `finishManualAudioSetup()`. A native MSVC build/CTest is required before any merge or qualification. This checkpoint does not claim full application acceptance. + +## Next milestone: real two-phase rebind + +1. Capture accepted immutable ChannelId model and original plugin/VST3 state on CONTROL (not inside callback). +2. Prepare a verified driver profile, compare physical input/output identities and explicitly mark changed ports NEEDS REMAP. +3. Rebuild graph with all authored stable IDs, buses, WIREs, original processing parameters, FX order/bypass and safe plugin state at the new sample rate/buffer. +4. Publish atomically, ensure accepted native readback and user-visible document projection. Keep output disarmed until an explicit ARM. +5. Rejected device or plugin preparation must not mutate the accepted document. Test no-change, active graph, ASIO4ALL WDM pin reorder, lost device, failed driver, rate/buffer changes, and concurrent editor/FX work. diff --git a/engine/device/DeviceSessionTransitionPolicy.h b/engine/device/DeviceSessionTransitionPolicy.h new file mode 100644 index 000000000..32ef50daa --- /dev/null +++ b/engine/device/DeviceSessionTransitionPolicy.h @@ -0,0 +1,28 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include + +namespace armix::device { + +// The mixer document is not a hardware binding. An epoch change invalidates +// PCM admission, NOT the operator's authored controls, WIREs or VST3 leases. +// All decisions happen on the JUCE message/control thread; no audio callback +// may read or mutate the retained document. +enum class DeviceSessionDecision : std::uint8_t { + rejectedDevice, + retainBoundMixer, + createFirstSilentMixer, + retainUnboundMixer +}; + +[[nodiscard]] constexpr DeviceSessionDecision decideDeviceSession( + bool verifiedDevice, bool mixerReadyForCurrentEpoch, + bool hasAuthoredMixerContent) noexcept +{ + if (!verifiedDevice) return DeviceSessionDecision::rejectedDevice; + if (mixerReadyForCurrentEpoch) return DeviceSessionDecision::retainBoundMixer; + return hasAuthoredMixerContent ? DeviceSessionDecision::retainUnboundMixer + : DeviceSessionDecision::createFirstSilentMixer; +} + +} // namespace armix::device diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index dac2eb40f..afc6300a5 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -18,6 +18,7 @@ #include "../engine/device/AsioPriorityDeviceManager.h" #include "../engine/device/AsioRegistryIdentityProbe.h" #include "../engine/device/DirectRouteFence.h" +#include "../engine/device/DeviceSessionTransitionPolicy.h" #include "../engine/device/WasapiEndpointIdentityGuard.h" #include "../engine/core/FxOrderPlan.h" #include "../engine/core/FxMoveRamp.h" @@ -370,12 +371,35 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // starts its new callback before the selector window is closed. void beginManualAudioSetup() noexcept { setOutputMuted(true); + secondaryOutput_.disarm(); directFence_.suspend(); - dryRoutingLab_.disable(); // explicit control-thread reset; not RT + // Do NOT disable the accepted ChannelId graph. Audio Setup is a + // device-binding operation, not an implicit CLEAR MIXER command. + // The JUCE selector may change the driver before its window closes. } bool finishManualAudioSetup() { if(!approveDirectRoute())return false; - return startUnpatchedProductionSession().isEmpty(); + using Decision=armix::device::DeviceSessionDecision; + switch(armix::device::decideDeviceSession( + true,dryRoutingLab_.ready(), + dryRoutingLab_.hasAuthoredMixerContent())) { + case Decision::retainBoundMixer: + return true; // no-op dialog: keep the exact FX/WIRE/PCM graph + case Decision::createFirstSilentMixer: + return startUnpatchedProductionSession().isEmpty(); + case Decision::retainUnboundMixer: + // Driver epoch changed; the old graph cannot be trusted to + // render new hardware. Keep its document/leases in memory, + // stay muted and require a verified full-graph rebind. + setOutputMuted(true); + return false; + case Decision::rejectedDevice: + return false; + } + return false; + } + bool hasRetainedUnboundMixer() const noexcept { + return dryRoutingLab_.hasAuthoredMixerContent() && !dryRoutingLab_.ready(); } // Device changes are exclusively CONTROL-THREAD transactions. @@ -411,8 +435,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String setIndependentClockEnabled (bool wanted) { - if (dryRoutingLab_.hasExplicitRoute()) - return "CLEAR PATCH and MUTE OUTPUT before changing the device clock"; + if (dryRoutingLab_.hasAuthoredMixerContent()) + return "Preserve the authored mixer first: changing the device clock requires a full non-destructive session rebind"; if (handoff_.busy()) return "Finish pending VST3 graph switch before changing audio backend"; if (wanted == independent_.active() && !(savedDirectSetup_ && !wanted)) return {}; if (wanted && savedDirectSetup_) return "Restore old device backend before another transition"; @@ -507,8 +531,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // user setup is restored on exit; temporary routes must not be persisted. juce::String setDiagnosticRoute (armix::diagnostics::Route wanted) { - if (dryRoutingLab_.hasExplicitRoute()) - return "CLEAR PATCH and MUTE OUTPUT before changing SIGNAL CHECK"; + if (dryRoutingLab_.hasAuthoredMixerContent()) + return "An authored mixer cannot enter endpoint isolation until a safe session rebind is available"; using Route = armix::diagnostics::Route; if (handoff_.busy()) return "Finish the pending FX graph transition first"; if (independent_.active()) return "Disable independent clock mode before endpoint isolation tests"; @@ -1069,6 +1093,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback juce::String startUnpatchedProductionSession() { setOutputMuted(true); secondaryOutput_.disarm(); // never carry LIVE STREAM into a new unpatched graph + if(hasRetainedUnboundMixer()) + return "Mixer session preserved, but device changed: full ChannelId graph and plugin-state rebind required (output stays muted)"; auto* device=deviceManager_.getCurrentAudioDevice(); if(!device || !directFence_.permitted() || independent_.active()) return "No verified DIRECT full-duplex device"; diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index cdd7ee459..8ce96ae20 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2208,6 +2208,21 @@ class LiveDryRoutingLab final { bool active() const noexcept {return enabled_.load(std::memory_order_acquire);} float peakLeft() const noexcept {return peakL_.load(std::memory_order_relaxed);} float peakRight() const noexcept {return peakR_.load(std::memory_order_relaxed);} + // CONTROL ONLY: hardware loss makes ready() false but does not erase + // authored values, FX identity, GROUP/FX_RETURN buses or accepted WIREs. + // Never downgrade this dynamic document to the fixed 10CH/4AUX schema. + bool hasAuthoredMixerContent() const noexcept { + if(acceptedRoute_.isObject() || nativeStructureLive_ || nativeControlDirty_) + return true; + for(const auto& lane:acceptedFxSelections_) + for(const auto& fx:lane) + if(fx.id.isNotEmpty())return true; + if(nativeAccepted_.fxOwners) + for(const auto& channel:nativeAccepted_.graph.roster.channels()) + if(nativeAccepted_.fxOwners->insertCount(channel.id)>0) + return true; + return false; + } bool ready() const noexcept { return active() && !topologyFault_.load(std::memory_order_acquire) && publishedEpoch_.load(std::memory_order_acquire)==epoch(); diff --git a/src/Main.cpp b/src/Main.cpp index 2d14c7169..77fea4986 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1293,7 +1293,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) error="Driver readback mismatch; device setting was not accepted"; if(error.isEmpty()&&!engine_.finishManualAudioSetup()) - error="Device opened but direct safe production session was rejected"; + error=engine_.hasRetainedUnboundMixer() + ? "Mixer document retained safely, but this device change needs a verified complete ChannelId / FX rebind; audio remains muted" + : "Device opened but direct safe production session was rejected"; if(error.isEmpty()) { deviceSettingsDirty_=true; directRestore_.cancel(); @@ -1339,6 +1341,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { diagnostics_.record ("SETUP", "Open audio device setup"); if (setupLaunching_) return; + // Suspend physical output but retain ALL authored mixer state while + // the real JUCE device selector is visible (including no-change close). engine_.beginManualAudioSetup(); // The native JUCE device list is cached after first construction: @@ -1374,7 +1378,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { safe->diagnostics_.record ("DIRECT_ROUTE_REJECTED", "No valid full-duplex device; audio remains gated"); - safe->emitNotice ("Choose a working capture and render device. Audio remains muted.", true); + safe->emitNotice ( + safe->engine_.hasRetainedUnboundMixer() + ? "Mixer and plugin state retained. Device binding changed; output stays muted until a verified full-session rebind." + : "Choose a working capture and render device. Audio remains muted.", true); } }); safe->audioSetupWindow_->setVisible (true); diff --git a/tests/device_session_transition_policy_test.cpp b/tests/device_session_transition_policy_test.cpp new file mode 100644 index 000000000..646b82019 --- /dev/null +++ b/tests/device_session_transition_policy_test.cpp @@ -0,0 +1,37 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#include "../engine/device/DeviceSessionTransitionPolicy.h" +#include +#include +using armix::device::DeviceSessionDecision; +using armix::device::decideDeviceSession; + +int main() +{ + // Opening and closing the dialog without a real hardware generation + // change never discards an accepted mixer, regardless of its contents. + static_assert(decideDeviceSession(true, true, true) == + DeviceSessionDecision::retainBoundMixer); + static_assert(decideDeviceSession(true, true, false) == + DeviceSessionDecision::retainBoundMixer); + // A failed open cannot create a default mixer or grant output permission. + static_assert(decideDeviceSession(false, false, true) == + DeviceSessionDecision::rejectedDevice); + static_assert(decideDeviceSession(false, false, false) == + DeviceSessionDecision::rejectedDevice); + // A new driver epoch with user-authored routing/FX is a NEEDS-REBIND + // state, never a permission to overwrite the document with 10ch defaults. + static_assert(decideDeviceSession(true, false, true) == + DeviceSessionDecision::retainUnboundMixer); + // Only a genuinely blank first-run mixer can start from the silent graph. + static_assert(decideDeviceSession(true, false, false) == + DeviceSessionDecision::createFirstSilentMixer); + for (bool verified : {false, true}) { + for (bool bound : {false, true}) { + for (bool edited : {false, true}) { + const auto decision = decideDeviceSession(verified,bound,edited); + assert(decision != DeviceSessionDecision::createFirstSilentMixer || + (verified && !bound && !edited)); + } + } + } +} From c4144f7afaff3964ff5be70655820310ab40f5b4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 10:06:43 +0700 Subject: [PATCH 146/219] test(audio): enforce non-destructive native Audio Setup contract --- tests/live_graph_contract_test.mjs | 10 ++++++++-- 1 file changed, 8 insertions(+), 2 deletions(-) diff --git a/tests/live_graph_contract_test.mjs b/tests/live_graph_contract_test.mjs index b33a201fd..1733b7e03 100644 --- a/tests/live_graph_contract_test.mjs +++ b/tests/live_graph_contract_test.mjs @@ -189,14 +189,20 @@ test('R0B B3 always-on native 10CH startup is verified, muted and unpatched',()= test('R0B B3 preserves diagnostic isolation without exposing an accepted patch',()=>{ const diagnostic=e.slice(e.indexOf('juce::String setDiagnosticRoute'), e.indexOf('armix::diagnostics::Route diagnosticRoute()')); - assert.match(diagnostic,/dryRoutingLab_\.hasExplicitRoute\(\)/); + // Endpoint isolation is allowed for the unedited silent graph, but an + // authored native WIRE/FX session must never be discarded on device change. + assert.match(diagnostic,/dryRoutingLab_\.hasAuthoredMixerContent\(\)/); assert.match(diagnostic,/dryRoutingLab_\.disable\(\)/); assert.match(diagnostic,/startUnpatchedProductionSession\(\)/); assert.match(diagnostic,/resumeVerifiedDirectRoute\(\)/); const manual=e.slice(e.indexOf('void beginManualAudioSetup()'), e.indexOf('bool independentClockActive()')); assert.match(manual,/setOutputMuted\(true\)/); - assert.match(manual,/dryRoutingLab_\.disable\(\)/); + assert.match(manual,/secondaryOutput_\.disarm\(\)/); + assert.doesNotMatch(manual,/dryRoutingLab_\.disable\(\)/); + assert.match(manual,/decideDeviceSession\(/); + assert.match(manual,/Decision::retainBoundMixer/); + assert.match(manual,/Decision::retainUnboundMixer/); assert.match(manual,/startUnpatchedProductionSession\(\)/); assert.doesNotMatch(manual,/setOutputMuted\(false\)/); }); From 9cb6d364f514083224b3434d3f6774b96612ea65 Mon Sep 17 00:00:00 2001 From: masarray Date: Sat, 7 Nov 2026 10:42:44 +0700 Subject: [PATCH 147/219] Check native test registration at its CMake source --- .../direct_restore_recovery_contract_test.mjs | 3 +-- ...independent_clock_adapter_contract_test.mjs | 4 +--- tests/live_routing_ui_contract_test.mjs | 4 +--- tests/plugin_vault_contract_test.mjs | 6 ++---- tests/portable_workspace_contract_test.mjs | 4 +--- tests/smart_audio_diagnostic_contract_test.mjs | 18 ++++++------------ tests/studio_backup_contract_test.mjs | 4 +--- 7 files changed, 13 insertions(+), 30 deletions(-) diff --git a/tests/direct_restore_recovery_contract_test.mjs b/tests/direct_restore_recovery_contract_test.mjs index 0c1d381ee..6139a50f0 100644 --- a/tests/direct_restore_recovery_contract_test.mjs +++ b/tests/direct_restore_recovery_contract_test.mjs @@ -47,8 +47,7 @@ test('restore retry is bounded and disabled on success, explicit direct and setu assert.match(main,/SMART_CLOCK_RECOVERY/); assert.match(main,/annotateRecovery \(status\)/); assert.match(main,/annotateRecovery \(state\)/); - assert.match(cmake,/BoundedDirectDeviceRecovery/); - assert.match(workflow,/ARMixRecoveryTests/); + assert.match(cmake,/add_test\(NAME BoundedDirectDeviceRecovery COMMAND ARMixRecoveryTests\)/); assert.match(workflow,/direct_restore_recovery_contract_test.mjs/); }); test('verified native FAT package preserves actual beta live-bridge provenance, not older offline-only claim',()=>{ diff --git a/tests/independent_clock_adapter_contract_test.mjs b/tests/independent_clock_adapter_contract_test.mjs index 6a0ad2248..a3075cdf3 100644 --- a/tests/independent_clock_adapter_contract_test.mjs +++ b/tests/independent_clock_adapter_contract_test.mjs @@ -34,7 +34,6 @@ test('independent source/render means two actual JUCE managers and distinct call test('P0 immutable independent stream format fence blocks silent device/period/map substitutions',()=>{ const fence=r('engine/device/IndependentStreamFormatFence.h'); const cmake=r('CMakeLists.txt'); - const workflow=r('.github/workflows/p1-windows.yml'); assert.match(fence,/class IndependentStreamFormatFence final/); assert.match(fence,/bool observeCallbackChannels/); assert.match(fence,/lifecyclePeriod/); @@ -45,8 +44,7 @@ test('P0 immutable independent stream format fence blocks silent device/period/m assert.match(device,/formatFence_\.resetStopped\(\)/); assert.match(engine,/bridgeNegotiationFault/); assert.match(host,/getProperty \("bridgeNegotiationFault", "NONE"\)/); - assert.match(cmake,/IndependentStreamNegotiatedFormatFence/); - assert.match(workflow,/ARMixIndependentFormatTests/); + assert.match(cmake,/add_test\(NAME IndependentStreamNegotiatedFormatFence COMMAND ARMixIndependentFormatTests\)/); }); test('live deployment preserves direct ASIO and bounded rollback semantics',()=>{ diff --git a/tests/live_routing_ui_contract_test.mjs b/tests/live_routing_ui_contract_test.mjs index 454b8e8e9..00f58fdf3 100644 --- a/tests/live_routing_ui_contract_test.mjs +++ b/tests/live_routing_ui_contract_test.mjs @@ -197,9 +197,7 @@ test("P1K truly keeps ten physical INPUT strips and adds four independent native assert.match(app,/auxes:draftAux\.map/); assert.match(app,/data-aux-fx/); const cmake=readFileSync(new URL("../CMakeLists.txt",import.meta.url),"utf8"); - const workflow=readFileSync(new URL("../.github/workflows/p1-windows.yml",import.meta.url),"utf8"); - assert.match(cmake,/P1KTenIndependentInputsAndFourDedicatedAuxReturns/); - assert.match(workflow,/ARMixDedicatedAuxBusTests/); + assert.match(cmake,/add_test\(NAME P1KTenIndependentInputsAndFourDedicatedAuxReturns COMMAND ARMixDedicatedAuxBusTests\)/); }); diff --git a/tests/plugin_vault_contract_test.mjs b/tests/plugin_vault_contract_test.mjs index 6a117de8a..5ff3eb680 100644 --- a/tests/plugin_vault_contract_test.mjs +++ b/tests/plugin_vault_contract_test.mjs @@ -5,7 +5,7 @@ import {readFileSync} from 'node:fs'; const read=p=>readFileSync(p,'utf8'); const vault=read('src/PluginVault.h'), catalog=read('src/PluginCatalog.h'), main=read('src/Main.cpp'), cmake=read('CMakeLists.txt'), - workflow=read('.github/workflows/p1-windows.yml'), testNative=read('tests/plugin_vault_test.cpp'); + testNative=read('tests/plugin_vault_test.cpp'); test('manual VST3 import physically copies whole plugin into the user workspace, not mere absolute source registration',()=>{ assert.match(catalog,/scan \(juce::StringArray \{ file\.getFullPathName\(\) \}, copyToVault\)/); @@ -40,9 +40,7 @@ test('no all-PC scan required for three manually selected VSTs; no third-party c assert.match(catalog,/scan \(juce::StringArray \{ file\.getFullPathName\(\) \}, copyToVault\)/); }); test('Windows CTest exercises full VST bundle resources and preserves original files/versions',()=>{ - assert.match(cmake,/ARMixVaultTests/); - assert.match(cmake,/SelectiveVst3BundleVaultImport/); - assert.match(workflow,/ARMixVaultTests/); + assert.match(cmake,/add_test\(NAME SelectiveVst3BundleVaultImport COMMAND ARMixVaultTests\)/); assert.match(testNative,/Contents\/x86_64-win\/MyVerb\.vst3/); assert.match(testNative,/Contents\/Resources\/moduleinfo\.json/); assert.match(testNative,/NEVER delete user source VST/); diff --git a/tests/portable_workspace_contract_test.mjs b/tests/portable_workspace_contract_test.mjs index c0f7fec9d..d233b274c 100644 --- a/tests/portable_workspace_contract_test.mjs +++ b/tests/portable_workspace_contract_test.mjs @@ -37,9 +37,7 @@ test('plugin catalog and native vendor ZIP persist workspace refs without changi assert.match(main,/presets_ \(settingsDirectory\(\)\.getChildFile \("presets"\), settingsDirectory\(\)\)/); }); test('real Windows-native USB move test is built in existing CTest and release includes marker',()=>{ - assert.match(cmake,/ARMixWorkspaceTests/); - assert.match(cmake,/PortableStudioUsbRelocation/); - assert.match(workflow,/ARMixWorkspaceTests/); + assert.match(cmake,/add_test\(NAME PortableStudioUsbRelocation COMMAND ARMixWorkspaceTests\)/); assert.match(workflow,/portable_workspace_contract_test\.mjs/); assert.match(packaging,/ARSONMIX_PORTABLE_WORKSPACE_V1/); assert.match(packaging,/portable_mode\.txt/); diff --git a/tests/smart_audio_diagnostic_contract_test.mjs b/tests/smart_audio_diagnostic_contract_test.mjs index 3147a8afd..7865acd51 100644 --- a/tests/smart_audio_diagnostic_contract_test.mjs +++ b/tests/smart_audio_diagnostic_contract_test.mjs @@ -13,7 +13,6 @@ const bridge=read('engine/device/AdaptiveClockBridge.h'); const policy=read('engine/device/AudioProfilePolicy.h'); const health=read('engine/core/RealtimeHealthHistogram.h'); const cmake=read('CMakeLists.txt'); -const flow=read('.github/workflows/p1-windows.yml'); test('native one-click copy uses system clipboard and includes last event markers',()=>{ assert.match(host,/if \(action == "copyDiagnosticReport"\)/); @@ -45,8 +44,7 @@ test('P0 capability report uses real independent endpoints and never auto-applie assert.match(host,/NOT_FAT_QUALIFIED_DO_NOT_AUTO_APPLY/); assert.match(host,/WASAPI shared can/); assert.match(adapter,/std::span/); - assert.match(cmake,/NativeDriverPeriodEvidence/); - assert.match(flow,/ARMixPeriodEvidenceTests/); + assert.match(cmake,/add_test\(NAME NativeDriverPeriodEvidence COMMAND ARMixPeriodEvidenceTests\)/); assert.match(policy,/unqualifiedLowLatency/); assert.match(policy,/explicitExclusiveApprovalRequired/); }); @@ -73,8 +71,7 @@ test('P0 ASIO native COM-driver registration attestation runs only on control pl assert.match(engine,/asioPinnedRegistration_\.sameDriverClass/); assert.match(engine,/asioRegisteredClassHash/); assert.match(host,/WINDOWS ASIO DRIVER REGISTRATION/); - assert.match(cmake,/AsioDriverClassRegistryAttestation/); - assert.match(flow,/ARMixAsioRegistryIdentityTests/); + assert.match(cmake,/add_test\(NAME AsioDriverClassRegistryAttestation COMMAND ARMixAsioRegistryIdentityTests\)/); }); test('P0 render callback cadence uses previous quantum and labels provenance rather than inventing XRUNs',()=>{ const cadence=read('engine/core/CallbackCadenceEvidence.h'); @@ -90,8 +87,7 @@ test('P0 render callback cadence uses previous quantum and labels provenance rat assert.match(engine,/callbackCadenceComparedIntervals/); assert.match(engine,/callbackCadenceClockRegressions/); assert.match(host,/START-to-START estimates use PREVIOUS callback frame count/); - assert.match(cmake,/P0RenderCallbackVariableQuantumCadence/); - assert.match(flow,/ARMixCadenceTests/); + assert.match(cmake,/add_test\(NAME P0RenderCallbackVariableQuantumCadence COMMAND ARMixCadenceTests\)/); assert.doesNotMatch(engine,/previousCallbackStartUs_/); }); test('telemetry distinguishes measured host budget fractions from unobservable output underrun',()=>{ @@ -111,8 +107,7 @@ test('P0 deterministic virtual clock soak is enforced in Windows CTest',()=>{ assert.match(soak,/steadyUnderflow/); assert.match(soak,/p99Budget/); assert.doesNotMatch(soak,/std::this_thread::sleep_for\s*\(|std::random_device\s*[({]/); - assert.match(cmake,/IndependentClockASRCDriftJitterSoak/); - assert.match(flow,/ARMixVirtualClockSoakTests/); + assert.match(cmake,/add_test\(NAME IndependentClockASRCDriftJitterSoak COMMAND ARMixVirtualClockSoakTests\)/); }); test('clock bridge has no callback alloc / blocking and is gated behind independent stream adapter',()=>{ assert.match(bridge,/class AdaptiveClockBridge final/); @@ -128,7 +123,7 @@ test('clock bridge has no callback alloc / blocking and is gated behind independ assert.match(cmake,/RealtimeHealthHistogram/); for (const target of ['ARMixClockBridgeTests','ARMixVirtualClockSoakTests', 'ARMixHealthTests','ARMixPolicyTests']) - assert.ok(flow.includes(target), 'Windows CI is missing ' + target); + assert.match(cmake, new RegExp('add_test\\(NAME \\w+ COMMAND '+target+'\\)')); assert.match(policy,/class AudioProfilePolicy final/); assert.match(policy,/clockSharedByHardware/); assert.match(policy,/unsupportedClockAdapter/); @@ -148,6 +143,5 @@ test('P0 capture block-head evidence is a single-pass RT heuristic, not invented assert.match(engine,/captureNonFiniteSamples/); assert.doesNotMatch(engine,/rawCapturePeak=juce::jmax\(/); assert.match(fixture,/100000/); - assert.match(cmake,/P0CaptureZeroHeadBoundaryCandidates/); - assert.match(flow,/ARMixCaptureBoundaryTests/); + assert.match(cmake,/add_test\(NAME P0CaptureZeroHeadBoundaryCandidates COMMAND ARMixCaptureBoundaryTests\)/); }); diff --git a/tests/studio_backup_contract_test.mjs b/tests/studio_backup_contract_test.mjs index ec9723983..d6988d32f 100644 --- a/tests/studio_backup_contract_test.mjs +++ b/tests/studio_backup_contract_test.mjs @@ -34,9 +34,7 @@ test('backup is non realtime and fail-closed, not a browser localStorage illusio assert.doesNotMatch(read('src/LiveAudioEngine.h'),/StudioBackup::/); }); test('Windows CI compiles and runs native corruption/USB backup tests in existing job',()=>{ - assert.match(cmake,/ARMixBackupTests/); - assert.match(cmake,/VerifiedPortableStudioBackup/); - assert.match(workflow,/ARMixBackupTests/); + assert.match(cmake,/add_test\(NAME VerifiedPortableStudioBackup COMMAND ARMixBackupTests\)/); assert.match(workflow,/studio_backup_contract_test\.mjs/); assert.match(fixture,/StudioBackup::verify/); assert.match(fixture,/INJECTED\.vst3/); From 2aac2d13d026369148fd1361323ead279a1c5c9f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:00:35 +0700 Subject: [PATCH 148/219] feat(operator): adaptive 50/50 console, floating tools and native channel presentation --- .github/workflows/ui-smoke.yml | 1 + scripts/build_approved_native_gui.py | 6 ++ scripts/build_pages.py | 2 + scripts/compose_operator_ux.py | 142 +++++++++++++++++++++++++++ src/LiveAudioEngine.h | 4 +- tests/approved_operator_ux_smoke.py | 62 ++++++++++++ web/approved-native-bridge.js | 86 ++++++++++++---- 7 files changed, 285 insertions(+), 18 deletions(-) create mode 100644 scripts/compose_operator_ux.py create mode 100644 tests/approved_operator_ux_smoke.py diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 104e9ba0d..2e6271002 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -97,6 +97,7 @@ jobs: node --check site/preview-v2/assets/gui-perf-probe.js node --check site/preview-v2/assets/mixer-native-peq.js python tests/native_peq_assembly_test.py + python tests/approved_operator_ux_smoke.py python scripts/build_ui_css.py --check python tests/gui_baseline_lock_test.py python tests/brand_icon_contract_test.py diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index 4212528ef..e44a9a227 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -103,6 +103,9 @@ def accepted_pages_html() -> str: # Native-only: the SAME original quick picker/manager owns the UI. # Only insertion leaves the demo reducer and goes to JUCE's actual VST3 # graph; never mark a browser insert as loaded. + ("function applyChannelIdentity(){\n", + "function applyChannelIdentity(){\n" + " if(window.__JUCE__?.backend&&!window.__ARMIX_NATIVE_M2__?.applyIdentity?.())return;\n"), ("function insertCatalogPlugin(id){\n", "function insertCatalogPlugin(id){\n" " if(window.__JUCE__?.backend){window.__ARMIX_NATIVE_M2__?.insertPlugin?.(id,activeFxTarget);return;}\n"), @@ -216,6 +219,9 @@ def accepted_pages_html() -> str: " return true;\n" " },\n" " make,render,findTrack,displayMeterDbfs,\n" + " openChannelIdentity,closeChannelIdentity,\n" + " get identityTrackId(){return identityTrackId;},\n" + " get identityColor(){return identityColor;},get identityIcon(){return identityIcon;},\n" " refreshStrip,syncFaderVisual,openFastPicker,openPluginBrowser,\n" " get activeFaderId(){return faderGesture?Number(faderGesture.input.closest('.strip')?.dataset.id):-1;},\n" " setNativeCatalog(rows){\n" diff --git a/scripts/build_pages.py b/scripts/build_pages.py index 2dc0b9b7e..f68b78f83 100644 --- a/scripts/build_pages.py +++ b/scripts/build_pages.py @@ -5,6 +5,7 @@ from approved_fx_rack_power import apply_authoritative_fx_power from approved_fx_rack_interaction import apply_fx_rack_interaction from compose_native_peq import apply_native_peq +from compose_operator_ux import apply_operator_ux ROOT=Path(__file__).resolve().parents[1] p=argparse.ArgumentParser() p.add_argument('--out',default='dist-pages') @@ -75,6 +76,7 @@ canonical_html=apply_authoritative_fx_power(canonical_html) canonical_html=apply_fx_rack_interaction(canonical_html) canonical_html=apply_native_peq(canonical_html) +canonical_html=apply_operator_ux(canonical_html,buttons_dest/'assets') # Stage C: compile only DEPLOYED copies, never modify locked V28 source # owners or approved PNG artwork. No new CSS/override or second renderer. canonical_html,css_compilation=optimize_assets(canonical_html,buttons_dest/'assets',runtime_bundle=True) diff --git a/scripts/compose_operator_ux.py b/scripts/compose_operator_ux.py new file mode 100644 index 000000000..198ffb609 --- /dev/null +++ b/scripts/compose_operator_ux.py @@ -0,0 +1,142 @@ +"""ArSonMix V29 operator UX composition for the ONE approved public/native console. + +The V28 historical source is byte locked. Apply this intentional, audited +product evolution once to the deployed copy BEFORE Stage C CSS compilation. +This is not an alternate renderer or an extra late stylesheet. +""" +from __future__ import annotations +from pathlib import Path +import re + +CLOSE_ICON = ('') + +OPERATOR_CSS = """ +/* V29 adaptive 50/50 console, authored for the same rail/strip/Master tokens. + At very short heights preserve minimum usable controls and scroll vertically. */ +.console-pane{overflow-y:auto!important;overflow-x:hidden!important} +.console-body{min-height:610px!important; + --v13-fader-h:max(130px,calc(50% - var(--pan-h) - var(--switch-h) - var(--footer-h)))!important; + --ux-fx-balanced-h:max(125px,calc(50% - var(--identity-h) - var(--route-h) - var(--send-h))); +} +.console-body:not(.collapsed-send):not(.collapsed-fx){min-height:680px!important} +.console-body.collapsed-route{--route-h:23px!important} +.console-body:not(.collapsed-fx) .strip .fx-section, +.console-body:not(.collapsed-fx) .section-rail>.rail-cell.fx{ + height:var(--ux-fx-balanced-h)!important;min-height:var(--ux-fx-balanced-h)!important; + max-height:var(--ux-fx-balanced-h)!important;flex:0 0 var(--ux-fx-balanced-h)!important; +} +.mixer-title{display:none!important} +.window-title{gap:12px!important;overflow:hidden!important} +.window-title .file-name{min-width:0;overflow:hidden;text-overflow:ellipsis} +.window-title .right{margin-left:auto;min-width:0;max-width:48%;overflow:hidden; + text-overflow:ellipsis;white-space:nowrap;color:#90b6c8;font-size:10px;font-weight:400} +.command-bar #densitySelect,.command-bar [for="densitySelect"],.command-bar #mode{display:none!important} +/* Every console floating editor uses one square Material close key. */ +:is(#pluginClose,#identityClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose){ + box-sizing:border-box!important;flex:0 0 29px!important;width:29px!important; + height:29px!important;min-width:29px!important;min-height:29px!important; + max-width:29px!important;max-height:29px!important;padding:0!important; + display:inline-flex!important;align-items:center!important;justify-content:center!important; + background:#253944!important;border:1px solid #57717f!important;border-radius:3px!important; + color:#d7e6eb!important;line-height:1!important;cursor:pointer!important; +} +:is(#pluginClose,#identityClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose):hover{ + background:#355161!important;color:#fff!important} +:is(#pluginClose,#identityClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose):active{ + background:#962f38!important;border-color:#e6505d!important;color:#fff!important} +:is(#pluginClose,#identityClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose) svg{ + width:20px;height:20px;display:block;pointer-events:none} +@media(max-width:1050px){ + .window-title .file-name{max-width:25vw} + .window-title .right{max-width:57%;font-size:9px} +} +@media(max-width:680px){ + .window-title .file-name{display:none!important} + .window-title .right{max-width:72%} +} +""" + +def once(source: str, before: str, after: str, label: str) -> str: + if source.count(before) != 1: + raise ValueError("Operator UX anchor drift: " + label) + return source.replace(before, after, 1) + +def apply_operator_ux(html: str, assets: Path) -> str: + """Evolve only the deployed HTML and two existing CSS owners, fail-closed.""" + html = once(html, + '
Mixer · Reference SessionOPERATOR-FIRST · SINGLE LIVE CONSOLE REFERENCE
', + '
Mixer · Reference Session10 audio · 1 bus · master
', + "compact title status") + old_title = re.compile(r'(?m)^
.*id="trackCount".*
\n') + html, count = old_title.subn("", html) + if count != 1: + raise ValueError("Operator UX old mixer status bar drift") + html = once(html, + '
Reading current audio device…
-
The output device above is the real destination. - A virtual cable does not automatically play through headphones.
-
Advanced · rate, buffer and channel pins +
-
`; devicePanel.querySelector("[data-audio-close]").onclick=()=>{ @@ -1423,8 +1471,7 @@ } const activeText=devicePanel.querySelector("[data-audio-active]"); if(activeText && !deviceBusy)activeText.textContent=deviceResult||(active.open? - "ACTIVE · "+active.backend+" · "+active.captureDevice+ - " → "+active.playbackDevice+" · "+active.rate+" Hz / "+active.buffer+" samples": + "ACTIVE · "+active.backend+" · "+active.rate+" Hz / "+active.buffer+" samples": "No verified audio device. Select a supported input and output."); devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| !!pendingDeviceMute||!deviceChoice.backend||!deviceChoice.capture|| @@ -2432,9 +2479,14 @@ if(m4ControlIsOwner()&&m4Verified())sendM4Control("pan",t,0); else intent("SET_PAN",t,{value:0}); } - else status("NATIVE: identity editor unavailable until native ACK contract"); + else if(event.target.closest?.(".footer-label,.strip-identity-top")){ + if(nativeIdFor(t) && flags.acceptedGraphConnected) + scope?.openChannelIdentity?.(t,event.target); + else status("Channel identity available after verified native admission"); + } return true; }, + applyIdentity:acceptIdentityPresentation, state:()=>controller?.state() || null }); window.__ARMIX_NATIVE_M2__ = nativeHooks; From 59832f8bf9d7750de869d8823810ebe2a0cb6051 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:01:42 +0700 Subject: [PATCH 149/219] fix(gui): match exact canonical plugin drag anchor in composed operator view --- scripts/compose_operator_ux.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/compose_operator_ux.py b/scripts/compose_operator_ux.py index 198ffb609..703597023 100644 --- a/scripts/compose_operator_ux.py +++ b/scripts/compose_operator_ux.py @@ -92,7 +92,7 @@ def apply_operator_ux(html: str, assets: Path) -> str: if count != 1: raise ValueError("Operator UX minimize event drift") html = once(html, - "const panel=plugEl('pluginBrowser'),parent=document.querySelector('.console-pane');\n const bounds=parent?.getBoundingClientRect?.();", + "const panel=plugEl('pluginBrowser'),parent=document.querySelector('.console-pane');\n const bounds=parent?.getBoundingClientRect?.();", "const panel=plugEl('pluginBrowser');\n const bounds={left:0,top:0,width:window.innerWidth,height:window.innerHeight};", "drag within entire window") targets = ("identityClose","pluginClose","fastClose", From d6c4b51649dd2faa3cbe7889941b8d375ef99d98 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:03:19 +0700 Subject: [PATCH 150/219] test(publication): verify V29 generated owners against exact single approved Pages bundle --- ...ingle_preview_publication_contract_test.py | 22 ++++++++++++++----- 1 file changed, 17 insertions(+), 5 deletions(-) diff --git a/tests/single_preview_publication_contract_test.py b/tests/single_preview_publication_contract_test.py index e6830ab19..641a5d9d3 100644 --- a/tests/single_preview_publication_contract_test.py +++ b/tests/single_preview_publication_contract_test.py @@ -1,11 +1,12 @@ """Fail closed: GitHub Pages must expose ONE approved ArSonMix GUI at /preview/.""" from pathlib import Path -import json, re, sys, hashlib +import json, re, sys, hashlib, shutil, tempfile sys.path.insert(0,str(Path(__file__).resolve().parents[1]/'scripts')) from compile_approved_css import LINK, optimize_css, compile_runtime_bundle, link_runtime_bundle, RUNTIME_CSS from approved_fx_rack_power import apply_authoritative_fx_power from approved_fx_rack_interaction import apply_fx_rack_interaction from compose_native_peq import apply_native_peq +from compose_operator_ux import apply_operator_ux ROOT=Path(__file__).resolve().parents[1] DST=Path(sys.argv[1]).resolve() if len(sys.argv)>1 else ROOT/'dist-pages' gui=DST/'preview' @@ -42,15 +43,26 @@ def require(ok,why): expected=apply_authoritative_fx_power(expected) expected=apply_fx_rack_interaction(expected) expected=apply_native_peq(expected) +# V29 edits only the generated owners, after the historical V28 source lock. +# Build the exact same two temporary pre-optimizer owners without mutating +# the source repository or the already optimized distribution. +with tempfile.TemporaryDirectory(prefix="armix-operator-contract-") as td: + owned=Path(td) + owners=("mixer-chrome-material.css","mixer-plugin-browser.css") + for name in owners: + shutil.copy2(ROOT/"site/preview-v2/assets"/name,owned/name) + expected=apply_operator_ux(expected,owned) + composed_css={name:(owned/name).read_text(encoding="utf-8") for name in owners} # Stage C: the source HTML remains byte-exact, but the 18 deployed CSS files # contain only proven cascade winners. Verify every *generated* byte and query # hash; never approve an extra stylesheet, different owner or PNG mutation. linked=[match.group(2) for match in LINK.finditer(expected)] require(len(linked)==18 and len(set(linked))==18,'approved CSS owners changed') -source_css=[(name,(ROOT / ("site/preview-buttons/assets" - if name=="mixer-control-keys.css" - else "site/preview-v2/assets") / name) - .read_text(encoding="utf-8")) for name in linked] +source_css=[(name, composed_css[name] if name in composed_css else + (ROOT / ("site/preview-buttons/assets" + if name=="mixer-control-keys.css" + else "site/preview-v2/assets") / name) + .read_text(encoding="utf-8")) for name in linked] compiled,counts=optimize_css(source_css) record=build.get('css_compilation') or {} for stat in ('sourceDeclarations','removedDeclarations', From afa444d019cc62b92df1f38538f20ea7f3e9cf17 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:06:32 +0700 Subject: [PATCH 151/219] polish(ui): unify native Parametric EQ square close SVG and pressed-red state --- site/preview-v2/assets/mixer-fx-rack.css | 7 ++++++- site/preview-v2/assets/mixer-native-peq.js | 3 ++- tests/approved_operator_ux_smoke.py | 9 +++++++++ 3 files changed, 17 insertions(+), 2 deletions(-) diff --git a/site/preview-v2/assets/mixer-fx-rack.css b/site/preview-v2/assets/mixer-fx-rack.css index ed435d3be..5852556f4 100644 --- a/site/preview-v2/assets/mixer-fx-rack.css +++ b/site/preview-v2/assets/mixer-fx-rack.css @@ -191,7 +191,12 @@ .mx-peq-brand{font-size:11px;font-weight:570;color:#e8f4f7;letter-spacing:.025em;white-space:nowrap} .mx-peq-channel{font-size:10px;color:#81bdcb;overflow:hidden;text-overflow:ellipsis;white-space:nowrap} .mx-peq-global{margin-left:auto;font-size:20px!important;width:29px;height:27px;border-radius:4px!important;color:#82d7a7!important} -.mx-peq-close{width:27px;height:27px;border-radius:4px!important;font-size:20px!important;line-height:1!important;color:#aac2cd!important} +.mx-peq .mx-peq-close{display:inline-flex;align-items:center;justify-content:center;flex:0 0 29px; + width:29px;height:29px;min-width:29px;min-height:29px;padding:0;border:1px solid #57717f; + border-radius:3px;color:#d7e6eb;background:#253944;line-height:1;box-sizing:border-box} +.mx-peq .mx-peq-close svg{width:20px;height:20px;display:block;pointer-events:none} +.mx-peq .mx-peq-close:hover{color:#fff;background:#355161} +.mx-peq .mx-peq-close:active{color:#fff;background:#962f38;border-color:#e6505d} .mx-peq-global:hover,.mx-peq-close:hover{background:#ffffff13} .mx-peq-body{display:grid;grid-template-columns:minmax(0,1fr) 143px;min-height:0;align-items:stretch;flex:0 1 auto} .mx-peq-graph{min-width:0;background:#0f202b;border-right:1px solid #29404e;overflow:hidden} diff --git a/site/preview-v2/assets/mixer-native-peq.js b/site/preview-v2/assets/mixer-native-peq.js index 179ac8a01..999a56e52 100644 --- a/site/preview-v2/assets/mixer-native-peq.js +++ b/site/preview-v2/assets/mixer-native-peq.js @@ -70,7 +70,8 @@ const root=dom("section","mx-peq");root.id="mxNativePeq";root.hidden=true;root.s root.setAttribute("aria-label","ArSonMix Parametric EQ");root.setAttribute("aria-modal","false"); const head=dom("header","mx-peq-title"),brand=dom("span","mx-peq-brand","ArSonMix / PARAMETRIC EQ"), channel=dom("span","mx-peq-channel"),power=dom("button","mx-peq-global","⏻"), - close=dom("button","mx-peq-close","×");power.type=close.type="button"; + close=dom("button","mx-peq-close");power.type=close.type="button"; +close.innerHTML='';close.setAttribute("aria-label","Close Parametric EQ"); power.title="Toggle accepted insert bypass";close.title="Close EQ"; head.append(brand,channel,power,close); const body=dom("div","mx-peq-body"),graph=dom("div","mx-peq-graph"); diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index 91c790f03..74d6a3277 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -43,6 +43,15 @@ def test_single_composed_gui_stays_faithful_and_editable(self): self.assertEqual((source/"index.html").read_text(encoding="utf-8"),html_before) self.assertEqual((source/"assets/mixer-chrome-material.css").read_bytes(),chrome_before) self.assertEqual(len(list(assets.iterdir())),2) + def test_native_peq_close_matches_mixer_floating_windows(self): + peq=(ROOT/"site/preview-v2/assets/mixer-native-peq.js").read_text(encoding="utf-8") + css=(ROOT/"site/preview-v2/assets/mixer-fx-rack.css").read_text(encoding="utf-8") + self.assertIn('close.innerHTML=',peq) + self.assertIn('M6.4,19L5,17.6L10.6,12',peq) + self.assertIn('.mx-peq .mx-peq-close:active',css) + self.assertIn('background:#962f38',css) + self.assertIn('width:29px;height:29px',css) + def test_native_hooks_and_audio_input_default(self): build=(ROOT/"scripts/build_approved_native_gui.py").read_text(encoding="utf-8") bridge=(ROOT/"web/approved-native-bridge.js").read_text(encoding="utf-8") From d4a47bf3da8dd9a32dfa18f3b5ba2bbf09f3f41f Mon Sep 17 00:00:00 2001 From: masarray Date: Sat, 7 Nov 2026 11:29:05 +0700 Subject: [PATCH 152/219] Keep accepted mixer visible when hardware binding is lost --- integration/ApprovedNativeRuntimeSnapshot.h | 82 +++++++++++++------- integration/ApprovedNativeV8Projection.h | 22 ++++-- src/LiveAudioEngine.h | 1 + src/LiveDryRoutingLab.h | 27 +++++-- src/Main.cpp | 4 +- tests/approved_native_cold_start_smoke.py | 42 +++++++++- tests/approved_native_v8_projection_test.cpp | 32 ++++++++ tests/milestone_a_single_authority.test.cjs | 2 +- web/approved-native-bridge.js | 51 +++++++++--- web/approved-native-contract.js | 19 +++-- 10 files changed, 218 insertions(+), 64 deletions(-) diff --git a/integration/ApprovedNativeRuntimeSnapshot.h b/integration/ApprovedNativeRuntimeSnapshot.h index 3aae7f8d2..544c500e7 100644 --- a/integration/ApprovedNativeRuntimeSnapshot.h +++ b/integration/ApprovedNativeRuntimeSnapshot.h @@ -188,6 +188,49 @@ inline bool publishVerifiedFirstSoundState(juce::var& snapshot, return physicalReady; } +inline void publishNativeMasterControls(juce::var& snapshot,const juce::var& live) +{ + // The physical MAIN gain/mute is + // applied by the single LiveAudioEngine host after that render. The + // generic ChannelId roster's default MAIN fader is not this physical + // gain. Publish the real host readback, or the visible master will + // snap back to 0 dB after every accepted native scalar snapshot. + double physicalMasterDb=0.; + const auto physicalMasterMute=live.getProperty("masterMute",{}); + if(nativeV8Number(live.getProperty("masterDb",{}),physicalMasterDb) && + physicalMasterDb>=-60.01 && physicalMasterDb<=10.01 && + physicalMasterMute.isBool()) { + const auto installedGraph=snapshot.getProperty("graph",{}); + const auto channels=installedGraph.getProperty("channels",{}); + if(auto* rows=channels.getArray()) + for(auto& row:*rows) + if(row.getProperty("role",{}).toString()=="MAIN") { + const auto controls=row.getProperty("controls",{}); + if(auto* obj=controls.getDynamicObject()) { + obj->setProperty("faderDb",physicalMasterDb); + obj->setProperty("mute",physicalMasterMute); + } + } + } +} + +inline bool projectRetainedNativeChannelIdGraph(juce::var& snapshot,const juce::var& live) +{ + const auto route=live.getProperty("dryRoutingLab",{}); + const auto retained=route.getProperty("retainedNativeBus",{}); + const auto pcm=route.getProperty("nativeChannelIdPcmActive",{}); + const auto device=snapshot.getProperty("device",{}); + const auto armed=device.getProperty("outputArmed",{}); + if(!retained.isObject() || !pcm.isBool() || static_cast(pcm) || + !armed.isBool() || static_cast(armed) || + !projectNativeGraph(snapshot,retained,NativeGraphProjection::retained)) + return false; + snapshot.getProperty("graph",{}).getDynamicObject() + ->setProperty("bindingState","NEEDS_REMAP"); + publishNativeMasterControls(snapshot,live); + return true; +} + inline bool projectInstalledNativeChannelIdGraph( juce::var& snapshot, const juce::var& live) { @@ -236,28 +279,7 @@ inline bool projectInstalledNativeChannelIdGraph( // comes from the verified installed ENGINE status above, not the caller. if (!projectApprovedNativeV8(snapshot,bus,true)) return false; - // ChannelId owns channel PCM, but the physical MAIN gain/mute is - // applied by the single LiveAudioEngine host after that render. The - // generic ChannelId roster's default MAIN fader is not this physical - // gain. Publish the real host readback, or the visible master will - // snap back to 0 dB after every accepted native scalar snapshot. - double physicalMasterDb=0.; - const auto physicalMasterMute=live.getProperty("masterMute",{}); - if(nativeV8Number(live.getProperty("masterDb",{}),physicalMasterDb) && - physicalMasterDb>=-60.01 && physicalMasterDb<=10.01 && - physicalMasterMute.isBool()) { - const auto installedGraph=snapshot.getProperty("graph",{}); - const auto channels=installedGraph.getProperty("channels",{}); - if(auto* rows=channels.getArray()) - for(auto& row:*rows) - if(row.getProperty("role",{}).toString()=="MAIN") { - const auto controls=row.getProperty("controls",{}); - if(auto* obj=controls.getDynamicObject()) { - obj->setProperty("faderDb",physicalMasterDb); - obj->setProperty("mute",physicalMasterMute); - } - } - } + publishNativeMasterControls(snapshot,live); // Advertise only controls provided by the currently installed and // positively admitted native callback (never inferred from a JSON shape // or the browser). Both the native and public capability are required by @@ -320,12 +342,15 @@ inline void publishAuthoritativeMixerSession(juce::var& snapshot) nativeV8Decimal(epoch) && epoch!="0" && nativeV8Decimal(graph.getProperty("revision",{})) && graphRows.isArray() && graphRows.getArray()->size()>0; + const bool channelIdRetained=!channelIdReady && + graph.getProperty("bindingState",{}).toString()=="NEEDS_REMAP"; + const bool hasChannelId=channelIdReady || channelIdRetained; const auto sources=m4.getProperty("channels",{}); const auto controls=m4.getProperty("channelControls",{}); const auto peakL=m4.getProperty("channelPeaksL",{}); const auto peakR=m4.getProperty("channelPeaksR",{}); const auto rackFlags=m4.getProperty("fxRackBypassed",{}); - const bool preparedM4=!channelIdReady && m4.isObject() && + const bool preparedM4=!hasChannelId && m4.isObject() && static_cast(m4.getProperty("active",false)) && static_cast(m4.getProperty("routeAccepted",false)) && !static_cast(m4.getProperty("nativeBusStructural",true)) && @@ -373,21 +398,22 @@ inline void publishAuthoritativeMixerSession(juce::var& snapshot) if(!validM4)rows.clear(); } auto session=std::make_unique(); - const auto authority=channelIdReady?"CHANNEL_ID":validM4?"M4":"NONE"; + const auto authority=hasChannelId?"CHANNEL_ID":validM4?"M4":"NONE"; + if(channelIdRetained)session->setProperty("bindingState","NEEDS_REMAP"); session->setProperty("authority",authority); session->setProperty("deviceEpoch",epoch); - session->setProperty("routeRevision",channelIdReady? + session->setProperty("routeRevision",hasChannelId? graph.getProperty("revision","0"):validM4? m4.getProperty("routingRevision","0"):juce::var("0")); - session->setProperty("rosterRevision",channelIdReady? + session->setProperty("rosterRevision",hasChannelId? graph.getProperty("rosterRevision","0"):juce::var("0")); - session->setProperty("channels",channelIdReady?graphRows:juce::var(rows)); + session->setProperty("channels",hasChannelId?graphRows:juce::var(rows)); session->setProperty("supportedOps",channelIdReady? caps.getProperty("supportedOps",juce::var(juce::Array{})): juce::var(juce::Array{})); // Actual physical post-mixer MAIN is not a second audio graph. auto master=std::make_unique(); - if(channelIdReady) { + if(hasChannelId) { for(const auto& ch:*graphRows.getArray()) if(ch.getProperty("role","").toString()=="MAIN") { const auto c=ch.getProperty("controls",{}); diff --git a/integration/ApprovedNativeV8Projection.h b/integration/ApprovedNativeV8Projection.h index ac7b0b98a..8319b7759 100644 --- a/integration/ApprovedNativeV8Projection.h +++ b/integration/ApprovedNativeV8Projection.h @@ -33,9 +33,11 @@ inline bool nativeV8Number(const juce::var& value,double& n) { // A structurally correct bus is NOT proof that its IDs own the installed // JUCE callback. The real PCM owner must explicitly admit the producer. // G0 must pass false and keep the accepted GUI graph unmodified. -inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, - bool installedChannelIdCallbackAdmitted) { - if(!installedChannelIdCallbackAdmitted)return false; +enum class NativeGraphProjection { installed, retained }; + +inline bool projectNativeGraph(juce::var& snapshot,const juce::var& bus, + NativeGraphProjection mode) { + const bool installed=mode==NativeGraphProjection::installed; const auto device=snapshot.getProperty("device",{}); if(!nativeV8Decimal(device.getProperty("epoch",{})))return false; const auto rawRows=bus.getProperty("channels",{}),rawEdges=bus.getProperty("edges",{}); @@ -116,7 +118,7 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, destinations.add(juce::var(dst.release())); } double left=0.,right=0.; - if(nativeV8Number(row.getProperty("peakL",{}),left) && + if(installed && nativeV8Number(row.getProperty("peakL",{}),left) && nativeV8Number(row.getProperty("peakR",{}),right) && left>=0.&&right>=0.){ auto peak=std::make_unique(); @@ -173,9 +175,10 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, g->setProperty("destinations",juce::var(destinations)); g->setProperty("edges",juce::var(wires)); if(auto* caps=graph.getProperty("capabilities",{}).getDynamicObject()){ - caps->setProperty("callbackOwnsChannelIds",true); - juce::Array ops;ops.add("APPLY_WIRE_TRANSACTION"); - const auto actual=bus.getProperty("supportedOps",{}); + caps->setProperty("callbackOwnsChannelIds",installed); + juce::Array ops; + if(installed)ops.add("APPLY_WIRE_TRANSACTION"); + const auto actual=installed?bus.getProperty("supportedOps",{}):juce::var{}; if(const auto* list=actual.getArray()) if(list->contains(juce::var("NATIVE_SET_WIRE_GAIN")))ops.add("SET_WIRE_GAIN"); caps->setProperty("supportedOps",juce::var(ops)); @@ -184,4 +187,9 @@ inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, // productionCallbackLive deliberately stays FALSE until full FAT. return true; } +inline bool projectApprovedNativeV8(juce::var& snapshot,const juce::var& bus, + bool installedChannelIdCallbackAdmitted) { + return installedChannelIdCallbackAdmitted && + projectNativeGraph(snapshot,bus,NativeGraphProjection::installed); +} } // namespace armix::console diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index afc6300a5..d2676855c 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -2254,6 +2254,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback void audioDeviceStopped() override { + setOutputMuted(true); secondaryOutput_.invalidateSource(); // explicit reconnect required after device stop masterLoudness_.prepare (0.0); // clear validity across device epoch dryRoutingLab_.deviceStopped(); diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 8ce96ae20..0d1964b50 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2012,10 +2012,11 @@ class LiveDryRoutingLab final { } // CONTROL snapshot: genuine stable ChannelIds from the SAME publisher // as physical PCM. No guessed IDs, synthetic UI routes or JS DSP. - juce::var nativeBusStatus() const { - if(!channelIdPhysicalPcmActive() || !nativeAccepted_.fxOwners)return {}; + juce::var nativeBusStatus(bool retained=false) const { + if(!nativeAccepted_.fxOwners || + (!retained && !channelIdPhysicalPcmActive()))return {}; const auto* routing=nativePublisher_.acceptedRouting( - epoch(),nativeAccepted_.pcmRevision); + nativeAccepted_.deviceEpoch,nativeAccepted_.pcmRevision); if(!routing)return {}; auto state=std::make_unique(); state->setProperty("graphRevision",juce::String( @@ -2023,12 +2024,14 @@ class LiveDryRoutingLab final { state->setProperty("rosterRevision",juce::String( std::to_string(routing->rosterRevision))); state->setProperty("structural",nativeStructureLive_); - state->setProperty("latencySamples",nativePublisher_.latencySamples(epoch(),nativeAccepted_.pcmRevision)); + if(!retained) + state->setProperty("latencySamples",nativePublisher_.latencySamples(epoch(),nativeAccepted_.pcmRevision)); juce::Array allowed; // Only expose operations backed by a real DSP lease. Dynamic // FX_RETURN insertion is not available until a native VST3 owner // can be prepared for its new ChannelId; do not advertise it. - for(const char* op: {"NATIVE_CREATE_GROUP_SELECTED", + if(!retained) + for(const char* op: {"NATIVE_CREATE_GROUP_SELECTED", "NATIVE_REMOVE_BUS","NATIVE_SET_BUS_MIX", "NATIVE_CREATE_CHANNEL","NATIVE_PATCH_CHANNEL", "NATIVE_SET_PRIMARY_OUT", @@ -2046,7 +2049,8 @@ class LiveDryRoutingLab final { juce::Array rows; // Meter taps come from the SAME realtime ChannelId renderer, in // accepted roster order. No JS guesses or second DSP render. - const bool pcmMeterValid=nativeMeterEpoch_.load(std::memory_order_acquire)==epoch(); + const bool pcmMeterValid=!retained && + nativeMeterEpoch_.load(std::memory_order_acquire)==epoch(); std::size_t meterIndex=0; for(const auto& ch:routing->channels) { auto row=std::make_unique(); @@ -2107,13 +2111,15 @@ class LiveDryRoutingLab final { for(const auto& source:nativeAccepted_.graph.request.sources) { if(source.id!=ch.id)continue; auto physical=std::make_unique(); - if(source.inputL>=0&&source.inputLsetProperty("bindingState","NEEDS_REMAP"); + if(!retained && source.inputL>=0 && + source.inputLsetProperty("portId","in:"+juce::String(pin)); } // Preserve BOTH actual physical pins on native readback, not // just the left pin. The GUI may not invent the right channel. - if(source.stereo && source.inputR>=0 && + if(!retained && source.stereo && source.inputR>=0 && source.inputRsetProperty("portIdRight","in:"+juce::String(right)); @@ -2507,6 +2513,11 @@ class LiveDryRoutingLab final { // silent so SAVE/RECALL cannot silently discard audible topology. out->setProperty("nativeBusStructural",nativeStructureLive_); if(nativePcm)out->setProperty("nativeBus",nativeBusStatus()); + else if(nativeAccepted_.deviceEpoch!=epoch() && hasAuthoredMixerContent()) { + auto retained=nativeBusStatus(true); + if(retained.isObject()) + out->setProperty("retainedNativeBus",std::move(retained)); + } // This exact original vendor Graph owner is retained by the native // accepted snapshot, NOT merely a catalog name or M4 CH1 label. // Message-thread diagnostic only; no false universal capabilities. diff --git a/src/Main.cpp b/src/Main.cpp index 77fea4986..5c515ca42 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -869,8 +869,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Actual prepared M4 epoch/revision enables the native First Sound // hardware PATCH/ARM workflow before full ChannelId admission. (void) armix::console::publishVerifiedFirstSoundState (accepted, live); - (void) armix::console::projectInstalledNativeChannelIdGraph ( - accepted, live); + if (!armix::console::projectInstalledNativeChannelIdGraph (accepted, live)) + (void) armix::console::projectRetainedNativeChannelIdGraph (accepted, live); // Sole control-thread SessionSnapshot from the installed PCM publisher. armix::console::publishAuthoritativeMixerSession(accepted); return accepted; diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index fc2c37a2b..efb7b45c3 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -53,6 +53,13 @@ def main(): state=snapshot() 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'), + ('102','FX_RETURN','Reverb Return')]: + state['graph']['channels'].insert(-1, { + 'id':ident,'role':role,'name':name,'processingFormat':'STEREO', + 'controls':{'faderDb':-5,'pan':0,'mute':False,'solo':False}, + 'inserts':[],'sends':[]}) + state['graph']['destinations'].append({'id':ident,'role':role,'name':name}) state['legacyM4']={'active':True,'routeAccepted':True,'routingRevision':'77', 'nativeBusStructural':False,'fxInstances':[[] for _ in range(14)]} emit(page,'arMixConsoleSnapshot',state) @@ -107,11 +114,44 @@ def main(): editor=page.evaluate("()=>window.__events.filter(e=>e.payload?.action==='routingFxEditor').at(-1)?.payload") assert editor and editor['channelId']==SOURCE and editor['instanceId']=='g5c-actual' assert editor['revision']=='5' and 'channel' not in editor + # A new device epoch publishes the same document without a + # callback, port assignment, meter evidence or write capability. + retained=copy.deepcopy(state) + retained['device'].update(epoch='92',outputArmed=False,sampleRate=0, + bufferFrames=0,inputEndpoints=[],outputEndpoints=[], + enabledInputs=[],enabledOutputs=[]) + retained['graph']['bindingState']='NEEDS_REMAP' + retained['graph']['capabilities'].update(callbackOwnsChannelIds=False,supportedOps=[]) + retained['graph']['channels'][0]['source']={ + 'bindingState':'NEEDS_REMAP','sourceFormat':'MONO'} + retained['telemetry']['channelMeterRmsPeak']={} + retained['legacyM4']={'active':False,'routeAccepted':False,'routingRevision':'0'} + retained['mixerSession'].update(deviceEpoch='92',bindingState='NEEDS_REMAP', + channels=copy.deepcopy(retained['graph']['channels'])) + emit(page,'arMixConsoleSnapshot',retained) + page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__.state().current?.retained') + assert page.locator('.status-bar .warning').inner_text().startswith('NEEDS REMAP') + assert page.locator('[data-native-monitor]').is_disabled() + assert page.locator('#tracks .strip').count()==4 + assert 'OUT NEEDS REMAP' in page.locator('#transport').inner_text() + page.locator('#tracks .strip[data-id="1"] .wire-node-out').click() + emit(page,'arMixConsoleSnapshot',retained) + assert page.locator('#tracks .strip[data-id="2"] .wire-gain').is_disabled() + strip=page.locator('#tracks .strip[data-id="1"]') + assert strip.locator('select[data-field="input"]').input_value()=='NEEDS REMAP' + assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' + before=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="routingFxEditor").length') + strip.locator('.fx-section [data-action="openPlugin"]').first.click() + assert page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="routingFxEditor").length')==before + assert page.evaluate('()=>window.__nativeIntents.length')==3 + # Late readback from the disconnected epoch cannot re-admit audio. + emit(page,'arMixConsoleSnapshot',state) + assert page.evaluate('()=>window.__ARMIX_NATIVE_M2__.state().current.retained') assert not errors, errors page.screenshot(path=f'native-cold-start-{width}.png') page.close() browser.close() - print('PASS G0 first drag without OUT priming; original-channel native FX insert/editor; 3 sizes (UI isolation)') + print('PASS G0 first drag without OUT priming; original-channel FX/editor; retained GROUP/FX/WIRE and disarm; 3 sizes (UI isolation)') if __name__=='__main__': diff --git a/tests/approved_native_v8_projection_test.cpp b/tests/approved_native_v8_projection_test.cpp index f6888cd8c..dced419c2 100644 --- a/tests/approved_native_v8_projection_test.cpp +++ b/tests/approved_native_v8_projection_test.cpp @@ -948,7 +948,39 @@ static void firstSoundMeasuredSignalEvidenceRegression() { assert(!static_cast(signal(live,true,true).getProperty("captureObserved",true))); } +static void retainedDocumentDoesNotAdmitPcm() { + auto snapshot=canonicalSnapshot(); + snapshot.getProperty("device",{}).getDynamicObject() + ->setProperty("outputArmed",false); + auto bus=realBusReadbackFixture(); + auto live=parse(R"JSON({ + "masterDb":-9.0,"masterMute":true, + "dryRoutingLab":{"nativeChannelIdPcmActive":false} + })JSON"); + auto* route=live.getProperty("dryRoutingLab",{}).getDynamicObject(); + route->setProperty("nativeBus",bus); + assert(!projectRetainedNativeChannelIdGraph(snapshot,live)); + route->setProperty("retainedNativeBus",bus); + assert(projectRetainedNativeChannelIdGraph(snapshot,live)); + publishAuthoritativeMixerSession(snapshot); + const auto graph=snapshot.getProperty("graph",{}); + const auto caps=graph.getProperty("capabilities",{}); + assert(graph.getProperty("bindingState",{}).toString()=="NEEDS_REMAP"); + assert(graph.getProperty("channels",{})[0].getProperty("id",{}).toString()=="9007199254740993"); + assert(graph.getProperty("edges",{})[0].getProperty("edgeId",{}).toString()=="9223372036854775808"); + assert(!static_cast(caps.getProperty("callbackOwnsChannelIds",true))); + assert(caps.getProperty("supportedOps",{}).getArray()->isEmpty()); + assert(snapshot.getProperty("telemetry",{}).getProperty("channelMeterRmsPeak",{}) + .getDynamicObject()->getProperties().size()==0); + const auto session=snapshot.getProperty("mixerSession",{}); + assert(session.getProperty("bindingState",{}).toString()=="NEEDS_REMAP"); + assert(static_cast(session.getProperty("main",{}).getProperty("db",0.0))==-9.0); + route->setProperty("nativeChannelIdPcmActive",true); + assert(!projectRetainedNativeChannelIdGraph(snapshot,live)); +} + int main() { + retainedDocumentDoesNotAdmitPcm(); auto snap=canonicalSnapshot(); auto bus=realBusReadbackFixture(); // Merely having matching native-shaped JSON cannot enable fake LIVE. diff --git a/tests/milestone_a_single_authority.test.cjs b/tests/milestone_a_single_authority.test.cjs index d078e757a..08bb77170 100644 --- a/tests/milestone_a_single_authority.test.cjs +++ b/tests/milestone_a_single_authority.test.cjs @@ -8,7 +8,7 @@ test("only installed callback determines GUI channel control authority",()=>{ const producer=read("integration/ApprovedNativeRuntimeSnapshot.h"); const host=read("src/Main.cpp"),adapter=read("web/approved-native-bridge.js"); assert.match(host,/publishAuthoritativeMixerSession\(accepted\)/); - assert.match(producer,/const auto authority=channelIdReady\?"CHANNEL_ID":validM4\?"M4":"NONE"/); + assert.match(producer,/const auto authority=hasChannelId\?"CHANNEL_ID":validM4\?"M4":"NONE"/); assert.match(producer,/row->setProperty\("id","m4:"/); assert.match(adapter,/if\(session\.authority==="M4" && m4Verified\(\)\)/); assert.match(adapter,/const nativeAdmitted=session\.authority==="CHANNEL_ID"/); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 488a62cdf..7d7b371cf 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -132,7 +132,7 @@ return result.ok; }; function projection(native) { - if (!native?.admitted || !Array.isArray(native.graph.edges) || + if ((!native?.admitted && !native?.retained) || !Array.isArray(native.graph.edges) || !scope?.make || !scope?.render || !scope?.wireGraph || !scope?.installGraph || !scope?.allocateWireId) return false; const accepted = native.graph; @@ -168,8 +168,9 @@ if(ch.role==="INPUT"){ const src=ch.source||{},l=/^in:(\d+)$/.exec(src.portId||""), r=/^in:(\d+)$/.exec(src.portIdRight||""); - t.input=l?inputLabelFor({mode:src.sourceFormat==="STEREO"?"STEREO":"MONO", - left:Number(l[1]),right:r?Number(r[1]):-1}):"None"; + t.input=native.retained && src.bindingState==="NEEDS_REMAP"? + NEEDS_REMAP:l?inputLabelFor({mode:src.sourceFormat==="STEREO"?"STEREO":"MONO", + left:Number(l[1]),right:r?Number(r[1]):-1}):"None"; } const out=accepted.channels.find(dest=>dest.id===ch.primaryOutId); // Identity-safe labels also handle duplicate names and reserved labels. @@ -342,7 +343,8 @@ if(ui===undefined)continue; for(const input of document.querySelectorAll?.('.wire-gain[data-wire-id="'+ui+'"]')||[]){ const fixed=edge.primaryOutput===true; - if(input.disabled!==fixed)input.disabled=fixed; + const disabled=fixed || next.retained; + if(input.disabled!==disabled)input.disabled=disabled; const title="Primary OUT is unity gain · use the destination fader"; if(fixed&&input.title!==title)input.title=title; } @@ -408,6 +410,7 @@ Number.isInteger(p.port) && hardware.device.enabledInputs.includes(p.port)):[]; // BUS is verified engine state, not an available hardware input choice. const INTERNAL_BUS="Internal BUS (read-only)"; + const NEEDS_REMAP="NEEDS REMAP"; const monoLabel=p=>"Mono · "+p.label+" [IN "+(p.port+1)+"]"; const stereoLabel=(a,b)=>"Stereo · IN "+(a.port+1)+" + "+(b.port+1); const inputChoicesFor=()=>{ @@ -1147,12 +1150,13 @@ monitorButton.disabled=!d?.outputArmed && !deviceReady(); monitorButton.dataset.armed=String(!!d?.outputArmed); } - if(scope?.master && deviceOpen && - scope.master.output!==playback){ - scope.master.output=playback; - if(!next?.admitted)scope.render?.(); + const mainOutput=next?.retained?NEEDS_REMAP:deviceOpen?playback:null; + if(scope?.master && mainOutput && scope.master.output!==mainOutput){ + scope.master.output=mainOutput; + if(!next?.admitted && !next?.retained)scope.render?.(); } - const transport=!deviceOpen?"Audio device not ready": + const transport=next?.retained?"MONITOR OFF · OUT NEEDS REMAP": + !deviceOpen?"Audio device not ready": (d.outputArmed?"MONITOR ON":"MONITOR OFF")+" · OUT "+playback+ (virtualOut?" · VIRTUAL / NO SPEAKERS":""); if(label && label.textContent!==transport)label.textContent=transport; @@ -1162,7 +1166,8 @@ // initiates native source publication; only its correlated ACK may // request a safe first MONITOR. If the driver exposes no physical IN, // guide the operator to the existing Audio I/O panel instead. - const warningText=!deviceOpen?"NO VERIFIED AUDIO DEVICE": + const warningText=next?.retained?"NEEDS REMAP · MIXER RETAINED · OUTPUT MUTED": + !deviceOpen?"NO VERIFIED AUDIO DEVICE": d.outputArmed?(next.admitted?"NATIVE PCM · HARDWARE FAT PENDING": "MAIN MONITOR ON · PCM ADMISSION NOT VERIFIED"): !d.enabledInputs?.length?"NO CAPTURE INPUT · OPEN AUDIO I/O": @@ -1669,6 +1674,21 @@ // snapshot even if the GUI signature is otherwise identical. window.queueMicrotask(dispatchNativeSource); } + if (next.retained && !nativeAdmitted) { + flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; + pendingNativeSources.clear();pendingSourceQueue.clear(); + activeNativeSource=null;nativeUiSourcePending=null; + pendingOutputPatch=null;pendingNativeFxPower=null;pendingBusCreate=null; + pendingFxInsert=null;startupWire=null;activeWireAttempt=null; + pendingWireGains.clear();pendingNativeControl.clear();liveFaderVisualTargets.clear(); + const signature="retained|"+next.identity; + if(lastPaintedSignature!==signature && projectNativeGraphWithoutFocusLoss(next)) + lastPaintedSignature=signature; + stopDemo(); + paintNativeMeters(next); + status("NEEDS REMAP · mixer retained · output muted"); + return; + } if (!nativeAdmitted) { flags.productionCallbackLive=false;flags.acceptedGraphConnected=false; lastPaintedSignature="";lastNativeTopologySignature=""; @@ -2007,6 +2027,7 @@ enabled:connected, inputChoices(t) { if(t?.kind!=="audio")return ["None"]; + if(controller?.state()?.current?.retained)return [t.input||"None"]; const choices=inputChoicesFor().map(x=>x.label); // The native BUS lane is selectable only for display: never invent a // hardware pin or promote the internal BUS to a writable physical IN. @@ -2015,7 +2036,8 @@ }, outputChoices(t) { if(t?.kind==="master") - return [String(hardware?.device?.playbackDevice||t.output||"Choose audio output")]; + return [hardware?.retained?NEEDS_REMAP: + String(hardware?.device?.playbackDevice||t.output||"Choose audio output")]; if(t?.kind!=="master"){ // M4 accepts MAIN or source-only. Bus routing is via native WIRE, // never pretend the demo's other destinations have native PCM. @@ -2034,6 +2056,13 @@ if (!field)return false; const t=scope?.findTrack?.(el) || null; if (!t)return true; + if(controller?.state()?.current?.retained){ + if(field==="output" && t.kind==="master" && event.type==="change") + openNativeAudioIO(); + if(field==="level" || field==="pan" || field==="input" || field==="output") + el.value=String(t[field]); + return true; + } if(field==="wireGain"){ const edge=scope?.wireEdges?.find(e=>e.id===Number(el.dataset.wireId)&&e.destId===t.id); if(!edge||!requestWireGain({sourceId:edge.sourceId,edgeId:edge.id,levelDb:Number(el.value)})) diff --git a/web/approved-native-contract.js b/web/approved-native-contract.js index 06275f94c..1da1ea8d0 100644 --- a/web/approved-native-contract.js +++ b/web/approved-native-contract.js @@ -79,11 +79,9 @@ // FAT. Never equate an installed PCM graph with a release-ready product. // Conversely, callbackOwnsChannelIds is ONLY advertised by the real // installed callback; the legacy M4/Pages demo must remain unadmitted. - const admitted = caps.callbackOwnsChannelIds === true && + const hasAcceptedGraph = cmp(d.epoch,"0") > 0 && cmp(g.revision,"0") > 0 && - d.sampleRate > 0 && d.bufferFrames > 0 && - d.enabledOutputs.length > 0 && d.outputEndpoints.length > 0 && - Array.isArray(g.edges) && g.channels.length > 0 && mainCount === 1 && + cmp(g.rosterRevision,"0") > 0 && Array.isArray(g.edges) && g.channels.length > 0 && mainCount === 1 && typeof g.mainChannelId === "string" && g.channels.some(ch => ch.id === g.mainChannelId && ch.role === "MAIN") && g.channels.every(ch => fields(ch,["controls","inserts","sends"]) && @@ -92,11 +90,20 @@ Number.isFinite(ch.controls.pan) && isBool(ch.controls.mute) && isBool(ch.controls.solo) && Array.isArray(ch.inserts) && Array.isArray(ch.sends)); + const retained = g.bindingState === "NEEDS_REMAP"; + if (retained && (!hasAcceptedGraph || caps.callbackOwnsChannelIds || + caps.supportedOps.length !== 0 || d.outputArmed || + raw.mixerSession?.authority !== "CHANNEL_ID" || + raw.mixerSession?.bindingState !== "NEEDS_REMAP" || + raw.mixerSession?.deviceEpoch !== d.epoch)) return null; + const admitted = caps.callbackOwnsChannelIds === true && hasAcceptedGraph && + d.sampleRate > 0 && d.bufferFrames > 0 && + d.enabledOutputs.length > 0 && d.outputEndpoints.length > 0; // A producer may stage PCM without claiming full release/UAT. A producer // must NEVER claim product LIVE without an admitted PCM graph. if (raw.productionCallbackLive && !admitted) return null; if (caps.callbackOwnsChannelIds && !admitted) return null; - return { raw, device:d, graph:g, telemetry:t, admitted, + return { raw, device:d, graph:g, telemetry:t, admitted, retained, productLive:admitted && raw.productionCallbackLive, identity: d.epoch + ":" + g.revision + ":" + g.rosterRevision }; } @@ -284,7 +291,7 @@ cmp(next.graph.rosterRevision,current.graph.rosterRevision) < 0))) { lastError="OLD_NATIVE_REVISION";notify();return false; } - if (pending && epochCompare !== 0) { + if (pending && (epochCompare !== 0 || next.retained)) { pending=null;lastError="STALE_DEVICE"; } } From 21963843bd382e20d2599801bfd5b6504a2d9f18 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:47:30 +0700 Subject: [PATCH 153/219] test(ux): real Chromium 5-viewport FAT for adaptive native console and floating tools --- .github/workflows/ui-smoke.yml | 26 ++++ tests/approved_operator_ux_chromium_fat.py | 149 +++++++++++++++++++++ 2 files changed, 175 insertions(+) create mode 100644 tests/approved_operator_ux_chromium_fat.py diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 2e6271002..e8daff9ad 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -115,6 +115,32 @@ jobs: - name: Block incomplete product release only when preparing product review if: ${{ github.event_name == 'pull_request' && !github.event.pull_request.draft && startsWith(github.head_ref, 'integration/product-') }} run: node scripts/check_console_puzzle.mjs --release + operator-ux-fat: + name: Operator UX real Chromium / native-assembled GUI (5 viewports) + needs: quick + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107' }} + runs-on: ubuntu-latest + timeout-minutes: 15 + steps: + - uses: actions/checkout@v4 + - uses: actions/setup-python@v5 + with: + python-version: "3.12" + - name: Install Chromium for UX FAT + run: | + python -m pip install playwright + python -m playwright install --with-deps chromium + - name: Measure actual layout, close keys, floating move and small-screen scaling + run: python tests/approved_operator_ux_chromium_fat.py + - name: Retain rendered evidence across viewport sizes + if: ${{ always() }} + uses: actions/upload-artifact@v4 + with: + name: ArSonMix-Operator-UX-5-viewports-${{ github.run_id }} + path: operator-ux-*.png + if-no-files-found: ignore + retention-days: 7 + frontend: name: Full Chromium /preview/ visual and interaction qualification # Draft edits are cheap; ChatGPT milestone comments dispatch this full suite. diff --git a/tests/approved_operator_ux_chromium_fat.py b/tests/approved_operator_ux_chromium_fat.py new file mode 100644 index 000000000..08fc1d6da --- /dev/null +++ b/tests/approved_operator_ux_chromium_fat.py @@ -0,0 +1,149 @@ +"""Product UX FAT (real Chromium) for the SINGLE assembled /preview/ and native WebView HTML. + +Checks rendering in CSS-pixel viewports corresponding to 100/125/150% Windows +display scaling. DeviceScaleFactor alone does not reduce usable CSS height, +so each smaller viewport is explicitly tested. Never emulates DSP/hardware. +""" +import importlib.util +import json +from pathlib import Path +import tempfile +from playwright.sync_api import sync_playwright + +ROOT=Path(__file__).resolve().parents[1] +CASES=((1680,900,1),(1366,768,1),(1255,700,1.25), + (1024,576,1.25),(900,540,1.5)) + +def metrics(page): + return page.evaluate("""() => { + const get=selector=>document.querySelector(selector)?.getBoundingClientRect(); + const root=get('.console-body'), strip=document.querySelector('#tracks .strip'); + const item=cls=>strip?.querySelector('.'+cls)?.getBoundingClientRect(); + const top=item('route-section'), fx=item('fx-section'), + wire=item('send-section'), pan=item('pan-section'), + switches=item('switch-section'), fader=item('fader-section'), + footer=item('bottom-section'); + if(!root||!top||!fx||!wire||!pan||!fader||!footer)return null; + return {viewport:innerHeight, root:root.height, viewportWidth:innerWidth, + route:top.height,fx:fx.height,wire:wire.height,pan:pan.height, + switches:switches.height,fader:fader.height,footer:footer.height, + upper:pan.top-root.top,lower:footer.bottom-pan.top, + gap:footer.bottom-root.bottom, + overflow:document.querySelector('.console-pane').scrollHeight- + document.querySelector('.console-pane').clientHeight, + density:document.querySelector('.console-body').dataset.density, + title:get('.window-title').height, + hasLiveBar:!!document.querySelector('.mixer-title'), + status:document.querySelector('#trackCount')?.textContent, + pluginStyle:document.querySelector('#pluginBrowser')?.getAttribute('style') + }; + }""") + +def assert_key(page, selector): + button=page.locator(selector) + box=button.bounding_box() + assert box and abs(box['width']-box['height'])<=1,(selector,box) + assert button.locator('svg path').count()==1,selector + assert button.locator('svg path').get_attribute('d').startswith('M6.4,19'),selector + # A pressed close must have a visually red background before release. + box=button.bounding_box() + page.mouse.move(box['x']+box['width']/2,box['y']+box['height']/2) + page.mouse.down() + color=button.evaluate("e=>getComputedStyle(e).backgroundColor") + assert color.startswith("rgb(") and (lambda a:a[0]>a[1]*1.3 and a[0]>a[2]*1.2)( + list(map(int,color[4:-1].split(',')[:3]))),(selector,color) + page.mouse.up() + +def inspect_page(page, width, height, scale, label): + page.goto((Path(label)).as_uri()) + page.wait_for_selector('#tracks .strip[data-id="1"]') + page.evaluate("document.fonts.ready") + assert page.locator('.mixer-title').count()==0,"redundant LIVE MIXER bar" + assert page.locator('.window-title #trackCount').count()==1 + assert page.locator('.window-title').inner_text().find("OPERATOR-FIRST")<0 + assert page.locator('#densitySelect').is_hidden() + assert page.locator('#pluginMinimize').count()==0 + m=metrics(page) + print("UX_BASE",width,height,scale,json.dumps(m,sort_keys=True),flush=True) + assert m and m['density']=='comfort' + assert m['root']>=min(540,height-90),(width,height,m) + assert m['fader']>=120 and m['fx']>=100,(width,height,m) + # All controls must fit in their strip without moving the nameplate below + # the console; short screens scroll the content, not truncate it. + assert abs(m['gap'])<=3,(width,height,m) + assert m['overflow']>=-3 + assert m['upper']>0 and m['lower']>0 + # Expand all components and verify coherent 50:50 allocation. + for area in ('route','fx','send'): + if page.locator('.console-body').evaluate("(e,a)=>e.classList.contains('collapsed-'+a)",area): + page.locator(f'.section-rail [data-section="{area}"]').click() + m=metrics(page) + print("UX_EXPANDED",width,height,scale,json.dumps(m,sort_keys=True),flush=True) + assert m['route']>=20 and m['fx']>=100 and m['wire']>=20,(width,height,m) + assert m['upper']>0 and m['lower']>0 + assert abs(m['gap'])<=3,(width,height,m) + assert 0.31<=m['lower']/(m['upper']+m['lower'])<=0.69,(width,height,m) + # Fold the FX; sections/fader must preserve mechanical labels and avoid + # a second panel/overflow, even when all three upper parts are collapsed. + for area in ('fx','route','send'): + page.locator(f'.section-rail [data-section="{area}"]').click() + m=metrics(page) + print("UX_COLLAPSED",width,height,scale,json.dumps(m,sort_keys=True),flush=True) + assert m['fader']>=120 and m['footer']>=32,(width,height,m) + assert abs(m['gap'])<=3,(width,height,m) + + # Genuine draggable Plugin Manager with no minimize, correct Close state. + page.locator('#pluginsButton').click() + win=page.locator('#pluginBrowser') + assert win.is_visible() + assert win.evaluate("e=>getComputedStyle(e).position")=="fixed" + original=win.bounding_box() + handle=page.locator('#pluginDragHandle') + hb=handle.bounding_box() + page.mouse.move(hb['x']+40,hb['y']+13) + page.mouse.down() + page.mouse.move(max(30,min(width-150,hb['x']-110)),max(70,min(height-80,hb['y']+75)),steps=6) + page.mouse.up() + moved=win.bounding_box() + assert moved and original and abs(moved['x']-original['x'])+abs(moved['y']-original['y'])>12,( + "plugin drag inert",width,height,original,moved) + assert moved['x']>=-2 and moved['y']>=-2 and moved['x']+moved['width']<=width+4,( + "plugin escaped viewport",width,height,moved) + assert_key(page,'#pluginClose') + assert win.is_hidden() + # Identity window and the other modeless tool share the exact square key. + page.locator('#tracks .strip[data-id="1"] .strip-identity-top').dblclick() + assert page.locator('#channelIdentity').is_visible() + assert_key(page,'#identityClose') + assert page.locator('#channelIdentity').is_hidden() + # All other close keys use the SAME SVG and dimensions; hidden popups + # cannot be pointer-tested here, but the CSS/DOM invariants are checked. + for id in ('fastClose','wireConfigClose','wireWsClose','routeChoiceClose'): + el=page.locator('#'+id) + assert el.locator('svg path').count()==1,id + assert el.evaluate("e=>getComputedStyle(e).width")=="29px",id + page.screenshot(path=str(ROOT / f'operator-ux-{width}x{height}-{scale}.png'), + full_page=True) + return m + +def main(): + import sys + sys.path.insert(0,str(ROOT/'scripts')) + import build_approved_native_gui as build + with tempfile.TemporaryDirectory(prefix="arsonmix-ux-fat-") as td, sync_playwright() as p: + staged=Path(td)/'native' + build.stage(staged) + browser=p.chromium.launch(headless=True) + try: + for width,height,scale in CASES: + page=browser.new_page(viewport={'width':width,'height':height}, + device_scale_factor=scale) + errors=[] + page.on('pageerror',lambda err:errors.append(str(err))) + inspect_page(page,width,height,scale,staged/'index.html') + assert not errors,(width,height,errors) + page.close() + finally:browser.close() + print('PASS operator UX: actual native-assembled Chromium layout/interaction across display scales') + +if __name__=='__main__':main() From 9489dc3567e44a86d8cce0bee96f23cf7488a941 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:49:49 +0700 Subject: [PATCH 154/219] fix(ux): make plugin Close pressed-red in its actual CSS owner; record visual FAT diagnostics --- scripts/compose_operator_ux.py | 5 +++++ tests/approved_operator_ux_chromium_fat.py | 8 ++++++-- tests/approved_operator_ux_smoke.py | 2 ++ 3 files changed, 13 insertions(+), 2 deletions(-) diff --git a/scripts/compose_operator_ux.py b/scripts/compose_operator_ux.py index 703597023..2f8a23344 100644 --- a/scripts/compose_operator_ux.py +++ b/scripts/compose_operator_ux.py @@ -136,6 +136,11 @@ def apply_operator_ux(html: str, assets: Path) -> str: if count != 1: raise ValueError("Operator UX obsolete minimized CSS drift") chrome_path.write_text(chrome.rstrip()+"\n"+OPERATOR_CSS+"\n",encoding="utf-8") + # Same plugin-browser CSS owner: pressed state outranks the legacy + # .plugin-close transparent background after Stage C compilation. + plugin += ("\n#pluginBrowser #pluginClose:active{" + "background:#962f38!important;background-color:#962f38!important;" + "border-color:#e6505d!important;color:#fff!important}\n") plugin_path.write_text(plugin,encoding="utf-8") if html.count('id="trackCount"')!=1 or 'id="pluginMinimize"' in html: raise ValueError("Operator UX DOM invariants rejected") diff --git a/tests/approved_operator_ux_chromium_fat.py b/tests/approved_operator_ux_chromium_fat.py index 08fc1d6da..1ed402334 100644 --- a/tests/approved_operator_ux_chromium_fat.py +++ b/tests/approved_operator_ux_chromium_fat.py @@ -50,8 +50,11 @@ def assert_key(page, selector): page.mouse.move(box['x']+box['width']/2,box['y']+box['height']/2) page.mouse.down() color=button.evaluate("e=>getComputedStyle(e).backgroundColor") - assert color.startswith("rgb(") and (lambda a:a[0]>a[1]*1.3 and a[0]>a[2]*1.2)( - list(map(int,color[4:-1].split(',')[:3]))),(selector,color) + active=button.evaluate("e=>e.matches(':active')") + print("UX_CLOSE_PRESSED",selector,"active",active,"color",color,flush=True) + rgb=[int(float(x.strip())) for x in color.replace("rgba(","").replace("rgb(","").split(")")[0].split(",")[:3]] + assert active and rgb[0]>=110 and rgb[0]>rgb[1]*1.3 and rgb[0]>rgb[2]*1.2,( + selector,active,color) page.mouse.up() def inspect_page(page, width, height, scale, label): @@ -109,6 +112,7 @@ def inspect_page(page, width, height, scale, label): "plugin drag inert",width,height,original,moved) assert moved['x']>=-2 and moved['y']>=-2 and moved['x']+moved['width']<=width+4,( "plugin escaped viewport",width,height,moved) + page.screenshot(path=str(ROOT/f'operator-ux-drag-{width}x{height}-{scale}.png')) assert_key(page,'#pluginClose') assert win.is_hidden() # Identity window and the other modeless tool share the exact square key. diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index 74d6a3277..e35940022 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -39,6 +39,8 @@ def test_single_composed_gui_stays_faithful_and_editable(self): self.assertNotIn(".plugin-browser.minimized",plugin) self.assertIn("calc(100vw - 28px)",plugin) self.assertIn("calc(100dvh - 90px)",plugin) + self.assertIn("#pluginBrowser #pluginClose:active",plugin) + self.assertIn("background:#962f38!important",plugin) # No extra CSS file, one canonical assembler, source history untouched. self.assertEqual((source/"index.html").read_text(encoding="utf-8"),html_before) self.assertEqual((source/"assets/mixer-chrome-material.css").read_bytes(),chrome_before) From a4225a0ff0d8cf7b70d04b0361fc48c26d360453 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:52:31 +0700 Subject: [PATCH 155/219] ci(fat): certify operator UX exact SHA in Windows MSVC, realtime CTest and audited FAT ZIP --- .github/workflows/p1-windows.yml | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 37e13c6e5..0366d5b8e 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -127,9 +127,10 @@ jobs: windows-build: name: Windows MSVC / realtime CTest needs: quick - # Draft commits never reserve expensive Windows runners. Non-draft PR - # synchronizations re-test latest HEAD. Main push and manual always run. - if: ${{ github.event_name != 'pull_request' }} + # One explicitly scoped UX milestone qualifies real Windows CTest and + # independently audited FAT ZIP. Other PRs stay on cheap contracts; + # main push/manual retain the existing qualification workflow. + if: ${{ github.event_name != 'pull_request' || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} runs-on: windows-2022 timeout-minutes: 50 steps: @@ -222,19 +223,19 @@ jobs: - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} shell: pwsh run: | & ./scripts/package_native_windows.ps1 -BuildDir build -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Stage ONLY legally approved and host-qualified Factory VST3 bundles - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} shell: pwsh run: | python scripts/factoryfx_release_bundle.py stage --lock config/factoryfx-approved-releases.json --output dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Independently verify release ZIP and embedded GUI/engine before upload - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} shell: pwsh run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist @@ -242,7 +243,7 @@ jobs: # Optional manual FAT only: never churn experimental ZIPs per commit. # The unqualified artifact is NOT a stable release or physical audio proof. - uses: actions/upload-artifact@v4 - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} with: name: ArSonMix-Windows-FAT-UNQUALIFIED-${{ github.run_id }} path: dist/ From e616c43e968cb635f297e80a608b1d155c3ad3eb Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 11:54:54 +0700 Subject: [PATCH 156/219] test(audio): enforce saved-ASIO callback order with stereo-first JUCE startup --- tests/independent_clock_adapter_contract_test.mjs | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/tests/independent_clock_adapter_contract_test.mjs b/tests/independent_clock_adapter_contract_test.mjs index a3075cdf3..8d113a649 100644 --- a/tests/independent_clock_adapter_contract_test.mjs +++ b/tests/independent_clock_adapter_contract_test.mjs @@ -141,7 +141,8 @@ test('ASIO is the preferred first-run live backend only for one same-driver dupl test('saved ASIO startup failure keeps the host callback registered for manual AUDIO SETUP recovery',()=>{ const registration=engine.indexOf('deviceManager_.addAudioCallback (this);'); - const initialise=engine.indexOf('auto error = deviceManager_.initialise (1, 2, savedSettings, !savedRoute);'); + // Product default requests stereo IN 1+2; saved explicit masks remain authoritative. + const initialise=engine.indexOf('auto error = deviceManager_.initialise (2, 2, savedSettings, !savedRoute);'); assert.ok(registration>=0 && registration Date: Sat, 7 Nov 2026 11:57:05 +0700 Subject: [PATCH 157/219] Restore accepted mixer on verified WASAPI reconnect --- engine/core/DynamicChannelFxLeaseBank.h | 17 +++++ engine/core/RealtimeRoutePublisher.h | 19 +++++ src/LiveAudioEngine.h | 85 +++++++++++++++++++++-- src/LiveDryRoutingLab.h | 69 +++++++++++++++++- src/Main.cpp | 25 +++++-- tests/approved_native_cold_start_smoke.py | 12 ++++ tests/live_channel_fx_graph_test.cpp | 9 +++ tests/live_port_epoch_publisher_test.cpp | 14 ++++ web/approved-native-bridge.js | 35 ++++++---- 9 files changed, 256 insertions(+), 29 deletions(-) diff --git a/engine/core/DynamicChannelFxLeaseBank.h b/engine/core/DynamicChannelFxLeaseBank.h index 292e708c2..6547882fa 100644 --- a/engine/core/DynamicChannelFxLeaseBank.h +++ b/engine/core/DynamicChannelFxLeaseBank.h @@ -262,6 +262,22 @@ class DynamicChannelFxLeaseBank final { DynamicChannelFxLeaseBank& destination) { if(!epoch || epoch!=prior.epoch_ || revision<=prior.revision_)return Fault::invalidEpoch; + return reusePreparedOwners(epoch,revision,prior,destination); + } + + // Caller has independently verified identical negotiated audio format. + static Fault rebindSameFormat(std::uint64_t epoch,std::uint64_t revision, + const DynamicChannelFxLeaseBank& prior, + DynamicChannelFxLeaseBank& destination) { + if(epoch<=prior.epoch_ || revision<=prior.revision_) + return Fault::invalidEpoch; + return reusePreparedOwners(epoch,revision,prior,destination); + } + +private: + static Fault reusePreparedOwners(std::uint64_t epoch,std::uint64_t revision, + const DynamicChannelFxLeaseBank& prior, + DynamicChannelFxLeaseBank& destination) { std::vector retained; retained.reserve(prior.rows_.size()); for(const auto& row:prior.rows_) { @@ -275,6 +291,7 @@ class DynamicChannelFxLeaseBank final { return prepare(epoch,revision,retained,destination,prior.external_); } +public: // Processing MONO/STEREO is a DSP lane property, not a device pin change. // Rebind the vendor lease's matching format atomically with the PCM // topology; otherwise a later insert would see stale format metadata. diff --git a/engine/core/RealtimeRoutePublisher.h b/engine/core/RealtimeRoutePublisher.h index 5c2452392..1adb0d670 100644 --- a/engine/core/RealtimeRoutePublisher.h +++ b/engine/core/RealtimeRoutePublisher.h @@ -95,6 +95,25 @@ class RealtimeRoutePublisher final { return Result::applied; } + // CONTROL only, after proving identical hardware layout and format. + // Keep the prepared compatibility plan and its revision. Run the paired + // publication while no reader can observe or acquire this snapshot. + template + bool rebindQuiescent(std::uint64_t from,std::uint64_t to, + Commit&& commit) noexcept { + static_assert(noexcept(commit())); + if(!owned_ || active_.load(std::memory_order_seq_cst)!=owned_.get() || + owned_->deviceEpoch!=from || !from || to<=from)return false; + std::uint32_t idle=0; + if(!activity_.compare_exchange_strong(idle,writerFlag, + std::memory_order_seq_cst)) + return false; + const bool accepted=commit(); + if(accepted)owned_->deviceEpoch=to; + activity_.store(0,std::memory_order_seq_cst); + return accepted; + } + // Immediately gate the last route to silence. Do NOT delete a graph // while the audio callback could own a ReadLease to its snapshot. void unpublish() noexcept { diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index d2676855c..f620c9285 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -388,11 +388,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback case Decision::createFirstSilentMixer: return startUnpatchedProductionSession().isEmpty(); case Decision::retainUnboundMixer: - // Driver epoch changed; the old graph cannot be trusted to - // render new hardware. Keep its document/leases in memory, - // stay muted and require a verified full-graph rebind. - setOutputMuted(true); - return false; + return rebindRetainedWasapiSession(); case Decision::rejectedDevice: return false; } @@ -1098,10 +1094,15 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback auto* device=deviceManager_.getCurrentAudioDevice(); if(!device || !directFence_.permitted() || independent_.active()) return "No verified DIRECT full-duplex device"; - return dryRoutingLab_.startUnpatchedSession( + const auto epoch=dryRoutingLab_.epoch(); + auto profile=inspectWasapiBinding(); + const auto error=dryRoutingLab_.startUnpatchedSession( directFence_.permitted(),independent_.active(),graphOwned_->count, formats_,device->getCurrentSampleRate(), juce::jmax(32,device->getCurrentBufferSizeSamples())); + if(error.isEmpty() && dryRoutingLab_.epoch()==epoch) + acceptedWasapiBinding_=std::move(profile); + return error; } // Historical STOP command retained as a safe CLEAR PATCH alias. @@ -1780,6 +1781,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return dryRoutingLab_.setNativeBusMix(epoch,revision,id,gain,pan); } bool dryRoutingLabActive() const noexcept {return dryRoutingLab_.active();} + bool hasBoundMixerRoute() const noexcept {return dryRoutingLab_.hasExplicitRoute();} void pollDryRoutingLab() noexcept {dryRoutingLab_.poll();} juce::var status() @@ -2019,6 +2021,76 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } private: + struct WasapiBinding { + armix::device::EndpointIdentityPolicy::Selection endpoints; + juce::String backend; + juce::BigInteger inputs,outputs; + juce::StringArray inputLabels,outputLabels; + double rate=0.0; + int frames=0; + std::uint64_t epoch=0; + + bool sameHardware(const WasapiBinding& other) const { + return backend==other.backend && + armix::device::EndpointIdentityPolicy::sameIdentity(endpoints,other.endpoints) && + inputs==other.inputs && outputs==other.outputs && + inputLabels==other.inputLabels && outputLabels==other.outputLabels && + rate==other.rate && frames==other.frames; + } + }; + + std::optional inspectWasapiBinding() { + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device || !device->isOpen() || independent_.active() || + !directFence_.permitted() || !device->getTypeName().startsWith("Windows Audio")) + return {}; + const auto epoch=dryRoutingLab_.epoch(); + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + const auto endpoints=armix::device::WasapiEndpointIdentityGuard::resolve( + setup.inputDeviceName,setup.outputDeviceName); + if(!endpoints.ok())return {}; + const auto inputs=device->getActiveInputChannels(); + const auto outputs=device->getActiveOutputChannels(); + const auto rate=device->getCurrentSampleRate(); + const auto frames=device->getCurrentBufferSizeSamples(); + if(inputs!=setup.inputChannels || outputs!=setup.outputChannels || + inputs.isZero() || outputs.countNumberOfSetBits()<2 || + !std::isfinite(rate) || rate<8000.0 || rate!=setup.sampleRate || + frames<16 || frames!=setup.bufferSize)return {}; + const auto inLabels=device->getInputChannelNames(); + const auto outLabels=device->getOutputChannelNames(); + const auto uniqueActiveLabels=[](const juce::BigInteger& mask,const juce::StringArray& labels) { + juce::StringArray seen; + for(int pin=mask.findNextSetBit(0);pin>=0;pin=mask.findNextSetBit(pin+1)) { + if(pin>=labels.size() || labels[pin].isEmpty() || seen.contains(labels[pin])) + return false; + seen.add(labels[pin]); + } + return true; + }; + if(!uniqueActiveLabels(inputs,inLabels) || !uniqueActiveLabels(outputs,outLabels) || + dryRoutingLab_.epoch()!=epoch || !directFence_.permitted())return {}; + return WasapiBinding{endpoints.selection,device->getTypeName(),inputs,outputs, + inLabels,outLabels,rate,frames,epoch}; + } + + bool rebindRetainedWasapiSession() { + if(!acceptedWasapiBinding_ || !allOutputsDisarmed() || !attached_ || + routeReconfiguring_.load(std::memory_order_acquire) || handoff_.busy() || + fxMovePhase_.load(std::memory_order_acquire)!=0 || + diagnosticRoute_.load(std::memory_order_acquire)!=armix::diagnostics::Route::normal) + return false; + try { + auto current=inspectWasapiBinding(); + if(!current || !acceptedWasapiBinding_->sameHardware(*current) || + !dryRoutingLab_.rebindVerifiedDevice(acceptedWasapiBinding_->epoch,current->epoch)) + return false; + acceptedWasapiBinding_=std::move(current); + return true; + } catch(...) {return false;} + } + bool approveDirectRoute ( const armix::device::AsioRegistrationPolicy::Identity* expectedAsio = nullptr) { @@ -2088,6 +2160,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback static constexpr int maxFrames = 8192; armix::device::AsioPriorityDeviceManager deviceManager_; armix::device::DirectRouteFence directFence_; + std::optional acceptedWasapiBinding_; // CONTROL only // Control-thread only; retain full class identity for exact comparison, // publish correlation HASH only. Never read registry in audio callback. armix::device::AsioRegistrationPolicy::Identity asioPinnedRegistration_; diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 0d1964b50..dbcd5b5b0 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -65,10 +65,19 @@ class LiveDryRoutingLab final { bool mute=false, solo=false, mono=false; }; + // Device callbacks only invalidate admission. CONTROL can later rebind + // the previously active graph after independent hardware verification. + void invalidateDeviceAdmission() noexcept { + const auto previous=channelIdPcmEpoch_.exchange(0,std::memory_order_acq_rel); + const auto generation=epoch(); + if(publishedEpoch_.load(std::memory_order_acquire)==generation) + rebindableNativeEpoch_.store(previous,std::memory_order_release); + } + // JUCE calls aboutToStart after configuring the input/output device. // One device session gets a new epoch; stored route cannot survive it. void prepareDevice (juce::AudioIODevice* device) noexcept { - channelIdPcmEpoch_.store(0,std::memory_order_release); + invalidateDeviceAdmission(); const auto generation=deviceEpoch_.fetch_add(1,std::memory_order_acq_rel)+1; userPatched_.store(false,std::memory_order_release); registryValid_.store(false,std::memory_order_release); @@ -98,7 +107,7 @@ class LiveDryRoutingLab final { registryValid_.store(true,std::memory_order_release); } void deviceStopped() noexcept { - channelIdPcmEpoch_.store(0,std::memory_order_release); + invalidateDeviceAdmission(); // A stale lab cannot silently resume legacy CH1 on device hotplug. userPatched_.store(false,std::memory_order_release); deviceEpoch_.fetch_add(1,std::memory_order_acq_rel); @@ -2229,6 +2238,61 @@ class LiveDryRoutingLab final { return true; return false; } + // CONTROL only. The verified profile proves identical port ordinals, + // rate and block size. Recompile the accepted ChannelId roster to reset + // DSP scratch/PDC, but preserve vendor instances and every document ID. + bool rebindVerifiedDevice(std::uint64_t priorEpoch,std::uint64_t newEpoch) { + using namespace armix::mixer; + if(!priorEpoch || newEpoch<=priorEpoch || newEpoch!=epoch() || + publishedEpoch_.load(std::memory_order_acquire)!=priorEpoch || + !active() || !acceptedRoute_.isObject() || + !registryValid_.load(std::memory_order_acquire) || + topologyFault_.load(std::memory_order_acquire))return false; + const bool native=rebindableNativeEpoch_.load(std::memory_order_acquire)==priorEpoch; + if(!native && (nativeStructureLive_ || nativeControlDirty_ || + nativeAccepted_.deviceEpoch==priorEpoch))return false; + std::shared_ptr owner; + DynamicNativeSessionPublisher::FxPlan fx; + const auto revision=nativeAccepted_.pcmRevision; + if(native) { + if(!nativeAccepted_.matches(nativePublisher_,priorEpoch,revision)) + return false; + owner=std::make_shared(); + if(DynamicChannelFxLeaseBank::rebindSameFormat( + newEpoch,revision+1,*nativeAccepted_.fxOwners,*owner)!= + DynamicChannelFxLeaseBank::Fault::none)return false; + fx.owner=owner;fx.context=owner.get(); + fx.deviceEpoch=newEpoch;fx.graphRevision=revision+1; + fx.render=+[](void* ctx,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(ctx))(id,l,r,n); + }; + fx.latency=+[](void* ctx,ChannelId id) noexcept { + return static_cast(ctx)->latencySamples(id); + }; + } + const bool applied=publisher_.rebindQuiescent(priorEpoch,newEpoch,[&]() noexcept { + if(newEpoch!=epoch())return false; + if(!native)return true; + try { + return nativePublisher_.commit( + nativeAccepted_.graph.roster,nativeAccepted_.graph.request, + revision,newEpoch,epoch(),true,std::move(fx)).ok(); + } catch(...) {return false;} + }); + if(!applied)return false; + if(native) { + nativeAccepted_.deviceEpoch=newEpoch; + nativeAccepted_.pcmRevision=revision+1; + nativeAccepted_.fxOwners=std::move(owner); + // The retained compatibility plan is only the physical contract. + // A later native fault must not silently fall back to its DSP. + nativeControlDirty_=true; + channelIdPcmEpoch_.store(newEpoch,std::memory_order_release); + } + publishedEpoch_.store(newEpoch,std::memory_order_release); + userPatched_.store(true,std::memory_order_release); + return newEpoch==epoch() && ready(); + } bool ready() const noexcept { return active() && !topologyFault_.load(std::memory_order_acquire) && publishedEpoch_.load(std::memory_order_acquire)==epoch(); @@ -2678,6 +2742,7 @@ class LiveDryRoutingLab final { std::atomic topologyFault_{false}; std::atomic deviceEpoch_{0}; std::atomic publishedEpoch_{0}; + std::atomic rebindableNativeEpoch_{0}; std::atomic callbackInputCount_{-1}; std::atomic callbackOutputCount_{-1}; std::atomic enabled_{false}; diff --git a/src/Main.cpp b/src/Main.cpp index 5c515ca42..87491dd45 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1137,6 +1137,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ack->setProperty("error",error); ack->setProperty("active",currentDeviceSnapshot()); ack->setProperty("outputMuted",engine_.isOutputMuted()); + ack->setProperty("mixerBound",engine_.hasBoundMixerRoute()); if(browser_.loaded) browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); }; @@ -1292,16 +1293,24 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::abs(opened->getCurrentSampleRate()-actual.sampleRate)>1.0|| opened->getCurrentBufferSizeSamples()!=actual.bufferSize)) error="Driver readback mismatch; device setting was not accepted"; - if(error.isEmpty()&&!engine_.finishManualAudioSetup()) - error=engine_.hasRetainedUnboundMixer() - ? "Mixer document retained safely, but this device change needs a verified complete ChannelId / FX rebind; audio remains muted" - : "Device opened but direct safe production session was rejected"; + if(error.isEmpty()&&!engine_.finishManualAudioSetup()) { + if(engine_.directRouteAuthorized()&&engine_.hasRetainedUnboundMixer()) { + const juce::String needsRemap="Device verified. Mixer retained and muted; its previous hardware mapping could not be verified"; + diagnostics_.record("CUSTOM_AUDIO_NEEDS_REMAP",needsRemap); + send(false,"NEEDS_REMAP",needsRemap); + emitApprovedNativeSnapshot(); + return; + } + error="Device opened but direct safe production session was rejected"; + } if(error.isEmpty()) { deviceSettingsDirty_=true; directRestore_.cancel(); diagnostics_.record("CUSTOM_AUDIO_APPLY_OK", typeName+" | "+juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); - return send(true,"ACCEPTED_MUTED",{}); + send(true,"ACCEPTED_MUTED",{}); + emitApprovedNativeSnapshot(); + return; } // A changed ASIO layout cannot be 'restored' by replaying indices // that now refer to different WDM pins. Keep the fresh device MUTED, @@ -1325,6 +1334,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr checked.outputDeviceName==before.outputDeviceName&& checked.inputChannels==before.inputChannels&& checked.outputChannels==before.outputChannels&& + checked.sampleRate==before.sampleRate&& + checked.bufferSize==before.bufferSize&& manager.getCurrentAudioDevice()!=nullptr&& manager.getCurrentAudioDevice()->isOpen()&& (previousType!="ASIO"|| @@ -1335,6 +1346,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (verified?"RESTORED":"RECOVERY_REQUIRED")+" | "+ juce::String(static_cast(monotonicMilliseconds()-start))+" ms"); send(false,verified?"RESTORED_MUTED":"RECOVERY_REQUIRED",error); + emitApprovedNativeSnapshot(); } void showDeviceSetup() @@ -1382,6 +1394,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr safe->engine_.hasRetainedUnboundMixer() ? "Mixer and plugin state retained. Device binding changed; output stays muted until a verified full-session rebind." : "Choose a working capture and render device. Audio remains muted.", true); + safe->emitApprovedNativeSnapshot(); } }); safe->audioSetupWindow_->setVisible (true); @@ -3452,7 +3465,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // DeviceManager signals even when a temporary capture-only / // output-only route is selected. Never persist that test route. if (!engine_.hasTemporaryDiagnosticDevice() && !engine_.independentClockActive() && - engine_.directRouteAuthorized() && + engine_.directRouteAuthorized() && !engine_.hasRetainedUnboundMixer() && (audioSetupWindow_ == nullptr || !audioSetupWindow_->isVisible()) && engine_.devices().getCurrentAudioDevice() != nullptr) if (auto xml = engine_.devices().createStateXml()) diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index efb7b45c3..bee2dff11 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -147,6 +147,18 @@ def main(): # Late readback from the disconnected epoch cannot re-admit audio. emit(page,'arMixConsoleSnapshot',state) assert page.evaluate('()=>window.__ARMIX_NATIVE_M2__.state().current.retained') + rebound=copy.deepcopy(state) + rebound['device'].update(epoch='93',outputArmed=False) + rebound['graph']['revision']='6' + rebound['mixerSession'].update(deviceEpoch='93',routeRevision='6') + monitor_events=page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length') + emit(page,'arMixConsoleSnapshot',rebound) + 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')=='false' + assert page.locator('#tracks .strip').count()==4 + assert strip.locator('.fx-section [data-action="openPlugin"]').first.inner_text()=='Latency VST' + assert page.evaluate('()=>window.__events.filter(e=>e.payload?.action==="monitor").length')==monitor_events assert not errors, errors page.screenshot(path=f'native-cold-start-{width}.png') page.close() diff --git a/tests/live_channel_fx_graph_test.cpp b/tests/live_channel_fx_graph_test.cpp index 60a76f11a..f14648434 100644 --- a/tests/live_channel_fx_graph_test.cpp +++ b/tests/live_channel_fx_graph_test.cpp @@ -1889,6 +1889,15 @@ static void verifyChannelIdGroupPreservesHostedFx() { assert(heapCalls.load(std::memory_order_relaxed)==heapBefore); assert(GainFx::living==pluginCount&&fallbackCalls==0); assert(!live.setLiveMix(epoch,2,voice,0.f,0.f)); + Bank rebound; + assert(Bank::rebindSameFormat(epoch,4,*nextBank,rebound)==Bank::Fault::invalidEpoch); + assert(nextBank->setRackBypass(epoch,3,voice,true)); + assert(Bank::rebindSameFormat(epoch+1,4,*nextBank,rebound)==Bank::Fault::none); + assert(rebound.ownerForControl(voice,0)->get()==nextBank->ownerForControl(voice,0)->get()); + assert(rebound.rackBypassed(voice)); + assert(!rebound.setInsertBypass(epoch,4,voice,0,token,true)); + assert(rebound.setInsertBypass(epoch+1,4,voice,0,token,true)); + assert(GainFx::living==pluginCount); live.unpublish();live.pollRetirement(); } diff --git a/tests/live_port_epoch_publisher_test.cpp b/tests/live_port_epoch_publisher_test.cpp index cdd09ecd3..a74ec5a91 100644 --- a/tests/live_port_epoch_publisher_test.cpp +++ b/tests/live_port_epoch_publisher_test.cpp @@ -79,6 +79,20 @@ int main() { assert(SpyGraph::alive==1); assert(p.publish(makeGraph(8,1,201),0,8)==Publisher::Result::applied); { auto v=p.acquire();assert(v.get(8)->prepared->value==201); } + { + auto live=p.acquire(); + assert(!p.rebindQuiescent(8,9,[]() noexcept {return true;})); + assert(live.get(8) && !live.get(9)); + } + assert(!p.rebindQuiescent(8,9,[]() noexcept {return false;})); + assert(p.controlPrepared(8,1) && !p.controlPrepared(9,1)); + const auto* retained=p.controlPrepared(8,1); + assert(p.rebindQuiescent(8,9,[&]() noexcept { + auto blocked=p.acquire(); + return !blocked.get(8) && !blocked.get(9); + })); + assert(p.controlPrepared(9,1)==retained && !p.controlPrepared(8,1)); + assert(p.lastRevision()==1); p.unpublish(); assert(p.pollRetirement()); assert(SpyGraph::alive==0); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 7d7b371cf..30a1cbe4c 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1133,6 +1133,16 @@ mixerSession()?.authority==="NONE") && legacy()?.active===true && safeNativeCounter(legacy()?.routingRevision)!==null)); + function syncMonitorButton(d) { + const monitorButton=document.querySelector?.("[data-native-monitor]"); + if(monitorButton){ + monitorButton.textContent=d?.outputArmed?"MONITOR OFF":"MONITOR ON"; + monitorButton.title=d?.outputArmed? + "Mute actual MAIN output immediately":"Listen through verified MAIN hardware output"; + monitorButton.disabled=!d?.outputArmed && !deviceReady(); + monitorButton.dataset.armed=String(!!d?.outputArmed); + } + } function updateHardwarePanel(next) { hardware=next || null; refreshRealM4Inputs(next); @@ -1142,14 +1152,7 @@ const label=document.getElementById("transport"); const playback=String(d?.playbackDevice||"unknown output"); const virtualOut=/VB-Audio Virtual Cable|CABLE Input/i.test(playback); - const monitorButton=document.querySelector?.("[data-native-monitor]"); - if(monitorButton){ - monitorButton.textContent=d?.outputArmed?"MONITOR OFF":"MONITOR ON"; - monitorButton.title=d?.outputArmed? - "Mute actual MAIN output immediately":"Listen through verified MAIN hardware output"; - monitorButton.disabled=!d?.outputArmed && !deviceReady(); - monitorButton.dataset.armed=String(!!d?.outputArmed); - } + syncMonitorButton(d); const mainOutput=next?.retained?NEEDS_REMAP:deviceOpen?playback:null; if(scope?.master && mainOutput && scope.master.output!==mainOutput){ scope.master.output=mainOutput; @@ -1471,16 +1474,17 @@ Array.isArray(ack.active.enabledOutputs) && ack.active.enabledOutputs.length>=2; deviceResult=accepted? - "Audio device ready · choose an IN on any channel": - "Device rejected · "+(ack.error||"native hardware readback failed"); + (ack.mixerBound?"Mixer ready · MONITOR OFF":"Audio device ready · choose an IN on any channel"): + ack.state==="NEEDS_REMAP"? + "NEEDS REMAP · "+ack.error: + "Device rejected · "+(ack.error||"native hardware readback failed"); deviceChoice=null; if(accepted){ devicePanel.hidden=true; - status("AUDIO ACTIVE · "+ack.active.backend+" · "+ - ack.active.rate+" Hz / "+ack.active.buffer+ - " samples · MONITOR muted until a real IN is selected"); - nativeToast("Audio device connected · "+ack.active.backend+ - " · "+ack.active.rate+" Hz · choose channel IN"); + status("DEVICE READY · "+ack.active.backend+" · "+ + ack.active.rate+" Hz / "+ack.active.buffer+" samples · MONITOR OFF"); + nativeToast(ack.mixerBound?"Mixer ready · MONITOR OFF": + "Audio device connected · "+ack.active.backend+" · "+ack.active.rate+" Hz · choose channel IN"); controller?.subscribe(); }else renderDevicePanel(); }); @@ -1718,6 +1722,7 @@ return; } flags.productionCallbackLive=next.productLive;flags.acceptedGraphConnected=true; + syncMonitorButton(next.device); lastPaintedSignature=signature;stopDemo();paintNativeMeters(next); if(pendingFxInsert?.authority==="CHANNEL_ID"){ const p=pendingFxInsert; From 71c1c6e71a3ce2eb2eeb7477d88459cb3a7f1307 Mon Sep 17 00:00:00 2001 From: masarray Date: Sat, 7 Nov 2026 12:02:11 +0700 Subject: [PATCH 158/219] Wait for the rendered EQ control before testing gestures --- tests/approved_native_peq_smoke.py | 22 +++++++++++----------- 1 file changed, 11 insertions(+), 11 deletions(-) diff --git a/tests/approved_native_peq_smoke.py b/tests/approved_native_peq_smoke.py index f21a160ff..9b9cdbde2 100644 --- a/tests/approved_native_peq_smoke.py +++ b/tests/approved_native_peq_smoke.py @@ -32,21 +32,19 @@ def node_pixel(page,index): bounding_box on a transparent SVG circle (Chromium may return None). Mouse events below remain real browser pointer interactions. """ - selector=f'.mx-peq-graph circle[data-eq-node="{index}"]' - page.locator(selector).last.wait_for(state="attached") - position=page.locator(selector).last.evaluate("""el=>{ - const svg=el.ownerSVGElement,matrix=svg?.getScreenCTM(); + selector=f'.mx-peq-graph circle[data-eq-node="{index}"][role="slider"]' + # The graph replaces its SVG children on rAF. Resolve the current + # node and measure it in the same browser turn, then require a real hit. + position=page.wait_for_function("""selector=>{ + const el=document.querySelector(selector); + const svg=el?.ownerSVGElement,matrix=svg?.getScreenCTM(); if(!matrix)return null; const point=svg.createSVGPoint(); point.x=Number(el.getAttribute('cx')); point.y=Number(el.getAttribute('cy')); - const screen=point.matrixTransform(matrix); - const target=document.elementFromPoint(screen.x,screen.y); - return {x:screen.x,y:screen.y, - hit:target?.getAttribute('data-eq-node')===el.getAttribute('data-eq-node')}; - }""") - assert position and position["x"]>0 and position["y"]>0,position - assert position["hit"],"EQ node not actually pointer-targetable: "+str(position) + const {x,y}=point.matrixTransform(matrix); + return x>0 && y>0 && document.elementFromPoint(x,y)===el ? {x,y} : null; + }""",arg=selector).json_value() return position["x"],position["y"] @@ -170,6 +168,7 @@ def main(): # The three power clicks leave band 4 selected. Explicitly # select bell 2 before checking its independent gain edit. page.locator(".mx-peq-band").nth(2).locator(".mx-peq-select").click() + page.wait_for_function("()=>document.querySelectorAll('.mx-peq-band')[2].classList.contains('active')") gain=page.locator('.mx-peq-knob[data-kind="gainDb"] .mx-peq-value') gain.fill("5.5");gain.press("Tab") flush_edits(page,state,values,handled) @@ -182,6 +181,7 @@ def main(): band.locator(".mx-peq-band-power").click() flush_edits(page,state,values,handled) if gain_value is not None: + band.locator('.mx-peq-band-power[aria-pressed="true"]').wait_for() knob=page.locator('.mx-peq-knob[data-kind="gainDb"] .mx-peq-value') knob.fill(str(gain_value));knob.press("Tab") flush_edits(page,state,values,handled) From 3aa77dcef8d23b3a46f9691806b3784cb3195f2f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 12:07:52 +0700 Subject: [PATCH 159/219] test(ux): prove native ChannelId alias persistence in Chromium; retire one-off Windows FAT CI --- .github/workflows/p1-windows.yml | 15 ++-- .github/workflows/ui-smoke.yml | 8 +- ...roved_operator_ux_native_identity_smoke.py | 81 +++++++++++++++++++ 3 files changed, 95 insertions(+), 9 deletions(-) create mode 100644 tests/approved_operator_ux_native_identity_smoke.py diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 0366d5b8e..37e13c6e5 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -127,10 +127,9 @@ jobs: windows-build: name: Windows MSVC / realtime CTest needs: quick - # One explicitly scoped UX milestone qualifies real Windows CTest and - # independently audited FAT ZIP. Other PRs stay on cheap contracts; - # main push/manual retain the existing qualification workflow. - if: ${{ github.event_name != 'pull_request' || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} + # Draft commits never reserve expensive Windows runners. Non-draft PR + # synchronizations re-test latest HEAD. Main push and manual always run. + if: ${{ github.event_name != 'pull_request' }} runs-on: windows-2022 timeout-minutes: 50 steps: @@ -223,19 +222,19 @@ jobs: - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT - if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} shell: pwsh run: | & ./scripts/package_native_windows.ps1 -BuildDir build -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Stage ONLY legally approved and host-qualified Factory VST3 bundles - if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} shell: pwsh run: | python scripts/factoryfx_release_bundle.py stage --lock config/factoryfx-approved-releases.json --output dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Independently verify release ZIP and embedded GUI/engine before upload - if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} shell: pwsh run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist @@ -243,7 +242,7 @@ jobs: # Optional manual FAT only: never churn experimental ZIPs per commit. # The unqualified artifact is NOT a stable release or physical audio proof. - uses: actions/upload-artifact@v4 - if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107') }} + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} with: name: ArSonMix-Windows-FAT-UNQUALIFIED-${{ github.run_id }} path: dist/ diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index e8daff9ad..f652b9407 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -131,7 +131,9 @@ jobs: python -m pip install playwright python -m playwright install --with-deps chromium - name: Measure actual layout, close keys, floating move and small-screen scaling - run: python tests/approved_operator_ux_chromium_fat.py + run: | + python tests/approved_operator_ux_chromium_fat.py + python tests/approved_operator_ux_native_identity_smoke.py - name: Retain rendered evidence across viewport sizes if: ${{ always() }} uses: actions/upload-artifact@v4 @@ -203,6 +205,10 @@ jobs: run: python tests/approved_native_meter_dirty_stage_b_smoke.py - name: Verify Stage C shipped CSS versus original-source computed and screenshot parity run: python tests/approved_stage_c_css_visual_parity_smoke.py + - name: V29 operator WebView: five geometry sizes, floating controls, and native channel identity + run: | + python tests/approved_operator_ux_chromium_fat.py + python tests/approved_operator_ux_native_identity_smoke.py - name: Check real mobile /preview/ touch toolbar, popup and stray chevrons run: python tests/approved_preview_mobile_navigation_smoke.py - name: FX rack master bypass preserves each insert state (real Chromium) diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py new file mode 100644 index 000000000..2547969c4 --- /dev/null +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -0,0 +1,81 @@ +"""Native channel identity end-to-end: Chromium + emulated JUCE metadata only. + +Source of truth for PCM/WIRE is the admitted ChannelId graph. A user-facing +alias must not create any synthetic graph intents, survive snapshot readback +and WebView reload, or rename the immutable native ChannelId. +""" +from pathlib import Path +import tempfile +import sys +import copy +from playwright.sync_api import sync_playwright +from approved_native_wire_gain_smoke import snapshot, emit, SOURCE, RECEIVER + +ROOT=Path(__file__).resolve().parents[1] +sys.path.insert(0,str(ROOT/'scripts')) +import build_approved_native_gui as bundle + +def main(): + with tempfile.TemporaryDirectory(prefix="armix-native-alias-") as temp, sync_playwright() as p: + out=Path(temp)/"native" + bundle.stage(out) + browser=p.chromium.launch(headless=True) + context=browser.new_context(viewport={"width":1366,"height":768}) + errors=[] + def open_page(): + page=context.new_page() + page.on('pageerror',lambda e:errors.append(str(e))) + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + window.__JUCE__={backend:{ + emitEvent(name,payload){if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") + page.goto((out/'index.html').as_uri()) + page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + return page + state=snapshot() + page=open_page() + emit(page,"arMixConsoleSnapshot",state) + page.wait_for_selector('#tracks .strip[data-id="1"]') + page.locator('#tracks .strip[data-id="1"] .strip-identity-top').dblclick() + editor=page.locator('#channelIdentity') + assert editor.is_visible(),"native bridge still blocks identity window" + page.locator('#identityName').fill("Studio Vox") + color="#c32974" + page.locator(f'#identityColors [data-identity-color="{color}"]').click() + icon="🎹" + page.locator(f'#identityIcons [data-identity-icon="{icon}"]').click() + page.locator('#identitySave').click() + assert editor.is_hidden() + assert page.locator('#tracks .strip[data-id="1"]').inner_text().find("Studio Vox")>=0 + alias=page.evaluate("()=>JSON.parse(localStorage.getItem('arsonmix.native.channel-presentation.v1'))") + assert alias["channels"][SOURCE]["name"]=="Studio Vox",alias + assert alias["channels"][SOURCE]["color"]==color + assert alias["channels"][SOURCE]["icon"]==icon + assert page.evaluate("()=>window.__nativeIntents.length")==0,\ + "display-only edit emitted an unauthorized PCM/route intent" + # No native server alias or ChannelId mutation: same authoritative + # snapshot retains its original name and exact ID. + assert state['graph']['channels'][0]['id']==SOURCE + assert state['graph']['channels'][0]['name']=='CH03' + emit(page,"arMixConsoleSnapshot",state) + assert "Studio Vox" in page.locator('#tracks .strip[data-id="1"]').inner_text() + assert page.evaluate("()=>window.__nativeIntents.length")==0 + # New WebView document, same browser profile: alias survives. + page.close() + page=open_page() + emit(page,"arMixConsoleSnapshot",state) + page.wait_for_selector('#tracks .strip[data-id="1"]') + assert "Studio Vox" in page.locator('#tracks .strip[data-id="1"]').inner_text() + page.locator('#tracks .strip[data-id="2"] .strip-identity-top').dblclick() + page.locator('#identityName').fill('Studio Vox') + page.locator('#identitySave').click() + assert page.locator('#channelIdentity').is_visible(),\ + "duplicate visible channel names should not silently collide" + page.locator('#identityClose').click() + assert page.evaluate("()=>window.__nativeIntents.length")==0 + assert not errors,errors + page.close() + context.close();browser.close() + print("PASS native identity: real edit name/icon/color; exact ChannelId; readback/reload; duplicate reject; no PCM graph intents") + +if __name__=="__main__":main() From a98ed99f2f987fa0b1dc1c713dbc9cb978401e09 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 12:09:10 +0700 Subject: [PATCH 160/219] ci: quote operator regression job label safely for GitHub Actions YAML --- .github/workflows/ui-smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index f652b9407..6d2ff22f7 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -205,7 +205,7 @@ jobs: run: python tests/approved_native_meter_dirty_stage_b_smoke.py - name: Verify Stage C shipped CSS versus original-source computed and screenshot parity run: python tests/approved_stage_c_css_visual_parity_smoke.py - - name: V29 operator WebView: five geometry sizes, floating controls, and native channel identity + - name: V29 operator WebView - five geometry sizes, floating controls, and native channel identity run: | python tests/approved_operator_ux_chromium_fat.py python tests/approved_operator_ux_native_identity_smoke.py From d92068304beef46444b0348994be7f75e622b242 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 12:52:42 +0700 Subject: [PATCH 161/219] fix(native UX): reconcile first-show WebView2 bounds and deterministic half-height mixer; no demo-only active controls --- .github/workflows/p1-windows.yml | 10 ++-- .github/workflows/ui-smoke.yml | 2 +- scripts/compose_operator_ux.py | 46 ++++++++++++++++ src/Main.cpp | 43 ++++++++++++++- tests/approved_operator_ux_chromium_fat.py | 16 +++++- ...roved_operator_ux_native_identity_smoke.py | 13 ++++- tests/approved_operator_ux_smoke.py | 9 ++++ web/approved-native-bridge.js | 52 ++++++++++++++++++- 8 files changed, 179 insertions(+), 12 deletions(-) diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 37e13c6e5..4fbcfeac4 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -129,7 +129,7 @@ jobs: needs: quick # Draft commits never reserve expensive Windows runners. Non-draft PR # synchronizations re-test latest HEAD. Main push and manual always run. - if: ${{ github.event_name != 'pull_request' }} + if: ${{ github.event_name != 'pull_request' || (github.event_name == 'pull_request' && github.head_ref == 'fix/native-first-paint-ux-20261107') }} runs-on: windows-2022 timeout-minutes: 50 steps: @@ -222,19 +222,19 @@ jobs: - name: Test realtime control primitives run: ctest --test-dir build -C Release --output-on-failure - name: Package verified JUCE GUI for hardware FAT - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/native-first-paint-ux-20261107') }} shell: pwsh run: | & ./scripts/package_native_windows.ps1 -BuildDir build -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Stage ONLY legally approved and host-qualified Factory VST3 bundles - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/native-first-paint-ux-20261107') }} shell: pwsh run: | python scripts/factoryfx_release_bundle.py stage --lock config/factoryfx-approved-releases.json --output dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } - name: Independently verify release ZIP and embedded GUI/engine before upload - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/native-first-paint-ux-20261107') }} shell: pwsh run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist @@ -242,7 +242,7 @@ jobs: # Optional manual FAT only: never churn experimental ZIPs per commit. # The unqualified artifact is NOT a stable release or physical audio proof. - uses: actions/upload-artifact@v4 - if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + if: ${{ (github.event_name == 'workflow_dispatch' && inputs.package_fat == true) || (github.event_name == 'pull_request' && github.head_ref == 'fix/native-first-paint-ux-20261107') }} with: name: ArSonMix-Windows-FAT-UNQUALIFIED-${{ github.run_id }} path: dist/ diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 6d2ff22f7..7e284e8c9 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -118,7 +118,7 @@ jobs: operator-ux-fat: name: Operator UX real Chromium / native-assembled GUI (5 viewports) needs: quick - if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107' }} + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/native-first-paint-ux-20261107' }} runs-on: ubuntu-latest timeout-minutes: 15 steps: diff --git a/scripts/compose_operator_ux.py b/scripts/compose_operator_ux.py index 2f8a23344..5d31af68f 100644 --- a/scripts/compose_operator_ux.py +++ b/scripts/compose_operator_ux.py @@ -13,6 +13,51 @@ '' '') +SPLIT_BOOTSTRAP = """ +// One console layout authority. CSS percent flex tracks were resolving against +// differing ancestors during WebView2 first show, causing 48:52 and clipped +// faders. Measure the real console once at boot and on actual size/fold changes. +// No timer, PCM access, animation loop, or per-meter layout work. +(function installConsoleSplit(){ + const root=document.querySelector('.console-body'); + if(!root || root.__armixBalancedSplitInstalled)return; + root.__armixBalancedSplitInstalled=true; + let scheduled=false,previous=''; + function update(){ + scheduled=false; + const rail=root.querySelector('.section-rail'); + if(!rail)return; + const h=root.getBoundingClientRect().height; + if(!(h>0))return; + const height=selector=>rail.querySelector(selector)?.getBoundingClientRect().height||0; + const pan=height('.rail-cell.pan'), + switches=height('.rail-cell.switch'), + footer=height('.rail-cell.footer'), + identity=height('.rail-cell.identity'), + route=height('.rail-cell.route'), + send=height('.rail-cell.send'); + // Panels remain equal halves when upper racks are expanded. If all upper + // modules fold, the existing flex fader may use the deliberately freed bay. + const half=Math.round(h/2); + const fader=Math.max(130,Math.round(half-pan-switches-footer)); + const fx=Math.max(125,Math.round(half-identity-route-send)); + const signature=fader+':'+fx; + if(signature===previous)return; + previous=signature; + root.style.setProperty('--v13-fader-h',fader+'px','important'); + root.style.setProperty('--ux-fx-balanced-h',fx+'px','important'); + } + function queue(){ + if(scheduled)return; + scheduled=true;requestAnimationFrame(update); + } + update(); // before first paint, not after operator starts using the mixer + if(window.ResizeObserver)new ResizeObserver(queue).observe(root); + new MutationObserver(queue).observe(root,{attributes:true,attributeFilter:['class']}); + window.addEventListener('resize',queue,{passive:true}); +})(); +""" + OPERATOR_CSS = """ /* V29 adaptive 50/50 console, authored for the same rail/strip/Master tokens. At very short heights preserve minimum usable controls and scroll vertically. */ @@ -142,6 +187,7 @@ def apply_operator_ux(html: str, assets: Path) -> str: "background:#962f38!important;background-color:#962f38!important;" "border-color:#e6505d!important;color:#fff!important}\n") plugin_path.write_text(plugin,encoding="utf-8") + html = once(html, "restorePluginPreferences();init();", "restorePluginPreferences();init();\n"+SPLIT_BOOTSTRAP, "startup geometry bootstrap") if html.count('id="trackCount"')!=1 or 'id="pluginMinimize"' in html: raise ValueError("Operator UX DOM invariants rejected") return html diff --git a/src/Main.cpp b/src/Main.cpp index 87491dd45..31aaf65c9 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -205,10 +205,30 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr onStartupStage_ (std::move (onStartupStage)), browser_ (webViewOptions() .withNativeIntegrationEnabled() - .withEventListener ("arMixGuiReady", [this] (juce::var) + .withEventListener ("arMixGuiReady", [this] (juce::var ready) { browser_.loaded = true; guiReadyTick_ = juce::Time::getMillisecondCounter(); + // WebView2 may finish its first navigation while this + // DocumentWindow is still hidden behind the splash. On + // 125%/150% DPI its child controller can keep that *old* + // bounds even though JUCE has already resized the content. + // Reapply actual browser bounds on the message thread, + // once after the native peer is visible: NO audio work. + const int cssWidth = static_cast (ready.getProperty ("viewportWidth", 0)); + const int cssHeight = static_cast (ready.getProperty ("viewportHeight", 0)); + if ((cssWidth > 0 && std::abs (cssWidth - browser_.getWidth()) > 2) || + (cssHeight > 0 && std::abs (cssHeight - browser_.getHeight()) > 2)) + diagnostics_.record ("WEBVIEW2_INITIAL_BOUNDS", + juce::String (cssWidth) + "x" + juce::String (cssHeight) + + " host=" + juce::String (browser_.getWidth()) + "x" + + juce::String (browser_.getHeight())); + juce::MessageManager::callAsync ( + [safe = juce::Component::SafePointer (this)] + { + if (safe && safe->browser_.isShowing()) + safe->browser_.resized(); + }); browser_.repaint(); if (onStartupStage_) onStartupStage_ (1); }) @@ -241,7 +261,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr setResizable (true, true); setResizeLimits (1100, 650, 3840, 2160); setContentNonOwned (&browser_, false); - centreWithSize (1650, 930); + // A fixed 1650x930 initial HWND exceeds the *logical* Windows work + // area on high-DPI laptops. Clamp BEFORE WebView2 first navigation, + // instead of letting Windows resize the outer peer without matching + // the child compositor during its hidden first-frame startup. + const auto* display = juce::Desktop::getInstance().getDisplays().getPrimaryDisplay(); + const auto available = display != nullptr + ? display->userArea : juce::Rectangle (0, 0, 1650, 930); + centreWithSize (juce::jlimit (1100, 1650, available.getWidth() - 24), + juce::jlimit (650, 930, available.getHeight() - 24)); // Keep native main window hidden during its expensive initial WebView2 // construction. The opaque always-on-top splash owns first paint. // After one control tick, reveal the PEER behind splash if WebView2 @@ -259,6 +287,16 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Startup must not spend seconds enumerating third-party VST3 modules. } + // Rebind the embedded WebView2 controller whenever its JUCE content + // window is resized. This catches the hidden-peer/show path, DPI moves + // and normal operator window drags without a per-frame polling timer. + void resized() override + { + juce::DocumentWindow::resized(); + if (getContentComponent() == &browser_ && browser_.isShowing()) + browser_.resized(); + } + ~ConsoleWindow() override { stopTimer(); @@ -3358,6 +3396,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { webViewPeerWarmed_ = true; setVisible (true); + browser_.resized(); // first visible HWND, not its pre-splash size toBack(); } // Existing message-thread 12 Hz timer: no extra worker or DSP work. diff --git a/tests/approved_operator_ux_chromium_fat.py b/tests/approved_operator_ux_chromium_fat.py index 1ed402334..8d9204a44 100644 --- a/tests/approved_operator_ux_chromium_fat.py +++ b/tests/approved_operator_ux_chromium_fat.py @@ -57,6 +57,16 @@ def assert_key(page, selector): selector,active,color) page.mouse.up() +def wait_balanced(page): + page.wait_for_function("""() => { + const root=document.querySelector('.console-body'),strip=document.querySelector('#tracks .strip'); + const pan=strip?.querySelector('.pan-section'),footer=strip?.querySelector('.bottom-section'); + if(!root||!pan||!footer)return false; + const r=root.getBoundingClientRect(),p=pan.getBoundingClientRect(), + f=footer.getBoundingClientRect(); + return Math.abs((p.top-r.top)-(f.bottom-p.top))<=2; + }""",timeout=4000) + def inspect_page(page, width, height, scale, label): page.goto((Path(label)).as_uri()) page.wait_for_selector('#tracks .strip[data-id="1"]') @@ -66,6 +76,8 @@ def inspect_page(page, width, height, scale, label): assert page.locator('.window-title').inner_text().find("OPERATOR-FIRST")<0 assert page.locator('#densitySelect').is_hidden() assert page.locator('#pluginMinimize').count()==0 + assert page.evaluate("()=>document.querySelector('.console-body').__armixBalancedSplitInstalled") + wait_balanced(page) m=metrics(page) print("UX_BASE",width,height,scale,json.dumps(m,sort_keys=True),flush=True) assert m and m['density']=='comfort' @@ -76,16 +88,18 @@ def inspect_page(page, width, height, scale, label): assert abs(m['gap'])<=3,(width,height,m) assert m['overflow']>=-3 assert m['upper']>0 and m['lower']>0 + assert abs(m['upper']-m['lower'])<=2,(width,height,m) # Expand all components and verify coherent 50:50 allocation. for area in ('route','fx','send'): if page.locator('.console-body').evaluate("(e,a)=>e.classList.contains('collapsed-'+a)",area): page.locator(f'.section-rail [data-section="{area}"]').click() + wait_balanced(page) m=metrics(page) print("UX_EXPANDED",width,height,scale,json.dumps(m,sort_keys=True),flush=True) assert m['route']>=20 and m['fx']>=100 and m['wire']>=20,(width,height,m) assert m['upper']>0 and m['lower']>0 assert abs(m['gap'])<=3,(width,height,m) - assert 0.31<=m['lower']/(m['upper']+m['lower'])<=0.69,(width,height,m) + assert abs(m['upper']-m['lower'])<=2,(width,height,m) # Fold the FX; sections/fader must preserve mechanical labels and avoid # a second panel/overflow, even when all three upper parts are collapsed. for area in ('fx','route','send'): diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py index 2547969c4..5a0199604 100644 --- a/tests/approved_operator_ux_native_identity_smoke.py +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -25,15 +25,24 @@ def main(): def open_page(): page=context.new_page() page.on('pageerror',lambda e:errors.append(str(e))) - page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[]; + page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[];window.__nativeEvents=[]; window.__JUCE__={backend:{ - emitEvent(name,payload){if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + emitEvent(name,payload){window.__nativeEvents.push({name,payload});if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") page.goto((out/'index.html').as_uri()) page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') return page state=snapshot() page=open_page() + ready=page.evaluate("()=>window.__nativeEvents.find(e=>e.name==='arMixGuiReady')?.payload") + assert ready and ready['viewportWidth']==1366 and ready['viewportHeight']==768 + # Never show demo-only controls as clickable on a physical host. + for id in ('saveScene','recallScene','copy','paste','group','ungroup','preview','clearCue','reset'): + element=page.locator('#'+id) + assert element.is_hidden() and element.is_disabled(),id + assert page.locator('[data-native-monitor]').count()==1 + assert page.locator('#pluginsButton').is_visible() + assert page.locator('#wireNavigatorToggle').is_visible() emit(page,"arMixConsoleSnapshot",state) page.wait_for_selector('#tracks .strip[data-id="1"]') page.locator('#tracks .strip[data-id="1"] .strip-identity-top').dblclick() diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index e35940022..42a59c79a 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -32,6 +32,10 @@ def test_single_composed_gui_stays_faithful_and_editable(self): self.assertIn('id="densitySelect" class="density-select" hidden',compiled) self.assertEqual(compiled.count(CLOSE_ICON),6) self.assertIn("V29 adaptive 50/50 console",chrome) + self.assertIn("installConsoleSplit",compiled) + self.assertIn("ResizeObserver",compiled) + self.assertIn("MutationObserver",compiled) + self.assertIn("--ux-fx-balanced-h',fx+'px'",compiled) self.assertIn("--ux-fx-balanced-h",chrome) self.assertIn("calc(50%",chrome) self.assertIn(".console-body.collapsed-route{--route-h:23px",chrome) @@ -67,6 +71,11 @@ def test_native_hooks_and_audio_input_default(self): self.assertIn("active.enabledInputs",bridge) self.assertIn("data-audio-asio4all-hint",bridge) self.assertIn("armix-floating-close",bridge) + self.assertIn("viewportWidth:Math.round(window.innerWidth)",bridge) + self.assertIn("presentNativeOnlyTools()",bridge) + main=(ROOT/"src/Main.cpp").read_text(encoding="utf-8") + self.assertIn("browser_.resized(); // first visible HWND",main) + self.assertIn("available.getWidth() - 24",main) self.assertNotIn("A virtual cable does not automatically play through headphones",bridge) if __name__=="__main__": diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index d23e9f8d9..25771d4bf 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2570,14 +2570,64 @@ // Native fader is committed exactly once INSIDE the original GUI's // finishFaderPointer via build_approved_native_gui.py hook. A later // window.pointerup listener would run after that handler clears the gesture. + + // Pages' reference-only controls must not masquerade as working native + // operations. Keep REAL audio/FX/WIRE/device controls fully interactive; + // until full device-independent Show is implemented, hide unsafe demo + // shortcuts instead of silently intercepting and leaving broken buttons. + const nativeReferenceOnly=Object.freeze({ + sceneSelect:"Native full-session Show is not yet available", + saveScene:"Native full-session Show is not yet available", + recallScene:"Native full-session Show is not yet available", + sceneSafe:"Show safe requires native session snapshots", + group:"Native channel grouping not yet admitted", + ungroup:"Native channel grouping not yet admitted", + copy:"Native channel copy not yet admitted", + paste:"Native channel paste not yet admitted", + clearCue:"PFL requires dedicated physical monitoring", + preview:"Demo meters never run inside the native audio host", + reset:"Demo reset must not erase a live mixer", + addTrack:"Native channel creation requires graph admission", + addFx:"Use a verified FX insert slot on an admitted channel" + }); + function presentNativeOnlyTools(){ + for(const [id,reason] of Object.entries(nativeReferenceOnly)){ + const el=document.getElementById(id); + if(!el)continue; + el.disabled=true; + el.title=reason; + el.dataset.nativeUnavailable=reason; + // Do not advertise an interactive click target that native cannot + // fulfill. Internal IDs survive for the approved Pages DOM contract. + el.style.setProperty("display","none","important"); + el.setAttribute("aria-hidden","true"); + } + const select=document.getElementById("sceneSelect"); + const label=document.querySelector('label[for="sceneSelect"]'); + if(select&&label)label.style.setProperty("display","none","important"); + // Keyboard shortcuts in Pages call the demo reducer directly, bypassing + // the click capture guard below. Suppress that route only in JUCE native. + document.addEventListener("keydown",event=>{ + if(!(event.ctrlKey||event.metaKey))return; + if(event.target?.closest?.('input,textarea,select,[contenteditable="true"]'))return; + if(["c","v","g"].includes(event.key.toLowerCase())){ + event.preventDefault();event.stopImmediatePropagation(); + nativeToast("Native channel copy/group requires accepted mixer session support"); + } + },true); + } const ready=()=>{ + presentNativeOnlyTools(); installFirstSoundMenu(); scope?.setNativeCatalog?.([]); // no synthetic/demo VST3 in Windows host updateHardwarePanel(null); stopDemo(); status("NATIVE: subscribed · waiting for true device and accepted ChannelId graph"); backend.emitEvent("arMixGuiReady",{ - gui:"APPROVED_PAGES_PREVIEW_BUTTONS",visualReady:true,audioReady:false + gui:"APPROVED_PAGES_PREVIEW_BUTTONS",visualReady:true,audioReady:false, + viewportWidth:Math.round(window.innerWidth), + viewportHeight:Math.round(window.innerHeight), + devicePixelRatio:window.devicePixelRatio }); controller.subscribe(); }; From 196f6aa0e8e93df9dd668563f9a00b287873a759 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 12:54:14 +0700 Subject: [PATCH 162/219] fix(native): keep first-show order and support minimal JS DOM test harness while retaining hard functional gating --- src/Main.cpp | 2 +- web/approved-native-bridge.js | 8 ++++---- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 31aaf65c9..0233c995e 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -3396,8 +3396,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr { webViewPeerWarmed_ = true; setVisible (true); - browser_.resized(); // first visible HWND, not its pre-splash size toBack(); + browser_.resized(); // first visible HWND, not its pre-splash size } // Existing message-thread 12 Hz timer: no extra worker or DSP work. // Never allow a hidden broken GUI to continue unattended audio. diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 25771d4bf..00e581aa5 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2596,15 +2596,15 @@ if(!el)continue; el.disabled=true; el.title=reason; - el.dataset.nativeUnavailable=reason; + if(el.dataset)el.dataset.nativeUnavailable=reason; // Do not advertise an interactive click target that native cannot // fulfill. Internal IDs survive for the approved Pages DOM contract. - el.style.setProperty("display","none","important"); - el.setAttribute("aria-hidden","true"); + el.style?.setProperty?.("display","none","important"); + el.setAttribute?.("aria-hidden","true"); } const select=document.getElementById("sceneSelect"); const label=document.querySelector('label[for="sceneSelect"]'); - if(select&&label)label.style.setProperty("display","none","important"); + if(select&&label)label.style?.setProperty?.("display","none","important"); // Keyboard shortcuts in Pages call the demo reducer directly, bypassing // the click capture guard below. Suppress that route only in JUCE native. document.addEventListener("keydown",event=>{ From bf77bbce495f3b5ef164fde93c5fbc1f67dde7df Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 12:55:32 +0700 Subject: [PATCH 163/219] fix(css): bootstrap balanced layout before init while preserving reversible native Pages source anchor --- scripts/compose_operator_ux.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/scripts/compose_operator_ux.py b/scripts/compose_operator_ux.py index 5d31af68f..9d91dbe58 100644 --- a/scripts/compose_operator_ux.py +++ b/scripts/compose_operator_ux.py @@ -187,7 +187,7 @@ def apply_operator_ux(html: str, assets: Path) -> str: "background:#962f38!important;background-color:#962f38!important;" "border-color:#e6505d!important;color:#fff!important}\n") plugin_path.write_text(plugin,encoding="utf-8") - html = once(html, "restorePluginPreferences();init();", "restorePluginPreferences();init();\n"+SPLIT_BOOTSTRAP, "startup geometry bootstrap") + html = once(html, "restorePluginPreferences();init();", SPLIT_BOOTSTRAP+"\nrestorePluginPreferences();init();", "startup geometry bootstrap") if html.count('id="trackCount"')!=1 or 'id="pluginMinimize"' in html: raise ValueError("Operator UX DOM invariants rejected") return html From ecd149e599bd5cdc8419967e324ea2ae7d608d84 Mon Sep 17 00:00:00 2001 From: masarray Date: Sat, 7 Nov 2026 12:57:50 +0700 Subject: [PATCH 164/219] Preserve mixer across WASAPI format changes and confirmed pin remap --- engine/device/DeviceSessionTransitionPolicy.h | 13 +++++ src/LiveAudioEngine.h | 57 +++++++++++++++---- src/LiveDryRoutingLab.h | 40 +++++++++++-- src/Main.cpp | 27 ++++++++- tests/approved_native_cold_start_smoke.py | 31 ++++++++++ .../device_session_transition_policy_test.cpp | 8 +++ web/approved-native-bridge.js | 30 ++++++++-- 7 files changed, 183 insertions(+), 23 deletions(-) diff --git a/engine/device/DeviceSessionTransitionPolicy.h b/engine/device/DeviceSessionTransitionPolicy.h index 32ef50daa..5eab14f16 100644 --- a/engine/device/DeviceSessionTransitionPolicy.h +++ b/engine/device/DeviceSessionTransitionPolicy.h @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once +#include #include namespace armix::device { @@ -25,4 +26,16 @@ enum class DeviceSessionDecision : std::uint8_t { : DeviceSessionDecision::createFirstSilentMixer; } +// Retained processors stay on their prepared rate. A changed buffer is +// safe when every callback chunk fits both the old graph and the new device. +[[nodiscard]] constexpr int retainedMixerQuantum( + int preparedFrames,int currentFrames,int maximumFrames, + bool rateChanged,bool hasPreparedEffects) noexcept +{ + if(preparedFrames<=0 || currentFrames<=0 || + preparedFrames>maximumFrames || currentFrames>maximumFrames || + (rateChanged && hasPreparedEffects))return 0; + return std::min(preparedFrames,currentFrames); +} + } // namespace armix::device diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index aa5cdfaf7..b6265d758 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -372,6 +372,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback // Suppress any live output while selecting/changing a device, even if JUCE // starts its new callback before the selector window is closed. void beginManualAudioSetup() noexcept { + offeredWasapiBinding_.reset(); setOutputMuted(true); secondaryOutput_.disarm(); directFence_.suspend(); @@ -396,6 +397,27 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback } return false; } + // Explicit operator consent can bind matching numbered pins on another + // uniquely identified WASAPI endpoint pair. It never authorizes output. + bool stageRetainedWasapiPortMapping() { + offeredWasapiBinding_.reset(); + if(!hasRetainedUnboundMixer() || !acceptedWasapiBinding_)return false; + try { + auto current=inspectWasapiBinding(); + if(!current || !acceptedWasapiBinding_->samePinLayout(*current) || + acceptedWasapiBinding_->sameEndpoints(*current) || + acceptedWasapiBinding_->rate!=current->rate) + return false; + offeredWasapiBinding_=std::move(current); + return true; + } catch(...) {return false;} + } + bool confirmRetainedWasapiPortMapping() { + auto offered=std::move(offeredWasapiBinding_); + offeredWasapiBinding_.reset(); + return offered && hasRetainedUnboundMixer() && directFence_.permitted() && + rebindRetainedWasapiSession(&*offered); + } bool hasRetainedUnboundMixer() const noexcept { return dryRoutingLab_.hasAuthoredMixerContent() && !dryRoutingLab_.ready(); } @@ -2032,12 +2054,12 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback int frames=0; std::uint64_t epoch=0; - bool sameHardware(const WasapiBinding& other) const { - return backend==other.backend && - armix::device::EndpointIdentityPolicy::sameIdentity(endpoints,other.endpoints) && - inputs==other.inputs && outputs==other.outputs && - inputLabels==other.inputLabels && outputLabels==other.outputLabels && - rate==other.rate && frames==other.frames; + bool samePinLayout(const WasapiBinding& other) const { + return backend==other.backend && inputs==other.inputs && outputs==other.outputs && + inputLabels==other.inputLabels && outputLabels==other.outputLabels; + } + bool sameEndpoints(const WasapiBinding& other) const noexcept { + return armix::device::EndpointIdentityPolicy::sameIdentity(endpoints,other.endpoints); } }; @@ -2059,7 +2081,8 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback if(inputs!=setup.inputChannels || outputs!=setup.outputChannels || inputs.isZero() || outputs.countNumberOfSetBits()<2 || !std::isfinite(rate) || rate<8000.0 || rate!=setup.sampleRate || - frames<16 || frames!=setup.bufferSize)return {}; + frames<16 || frames>LiveDryRoutingLab::Block::hardFrameLimit || + frames!=setup.bufferSize)return {}; const auto inLabels=device->getInputChannelNames(); const auto outLabels=device->getOutputChannelNames(); const auto uniqueActiveLabels=[](const juce::BigInteger& mask,const juce::StringArray& labels) { @@ -2077,7 +2100,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback inLabels,outLabels,rate,frames,epoch}; } - bool rebindRetainedWasapiSession() { + bool rebindRetainedWasapiSession(const WasapiBinding* offered=nullptr) { if(!acceptedWasapiBinding_ || !allOutputsDisarmed() || !attached_ || routeReconfiguring_.load(std::memory_order_acquire) || handoff_.busy() || fxMovePhase_.load(std::memory_order_acquire)!=0 || @@ -2085,8 +2108,21 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return false; try { auto current=inspectWasapiBinding(); - if(!current || !acceptedWasapiBinding_->sameHardware(*current) || - !dryRoutingLab_.rebindVerifiedDevice(acceptedWasapiBinding_->epoch,current->epoch)) + if(!current || !acceptedWasapiBinding_->samePinLayout(*current)) + return false; + if(offered) { + if(offered->epoch!=current->epoch || offered->rate!=current->rate || + offered->frames!=current->frames || !offered->sameEndpoints(*current) || + !offered->samePinLayout(*current)) + return false; + } else if(!acceptedWasapiBinding_->sameEndpoints(*current))return false; + const bool rateChanged=acceptedWasapiBinding_->rate!=current->rate; + // The external CH1/Orbit rack is prepared by the device callback + // rather than the retained ChannelId lease bank. Keep the same + // policy for it as for other authored effects. + if((rateChanged && graphOwned_->count>0) || + !dryRoutingLab_.rebindVerifiedDevice(acceptedWasapiBinding_->epoch, + current->epoch,current->frames,rateChanged)) return false; acceptedWasapiBinding_=std::move(current); return true; @@ -2163,6 +2199,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::device::AsioPriorityDeviceManager deviceManager_; armix::device::DirectRouteFence directFence_; std::optional acceptedWasapiBinding_; // CONTROL only + std::optional offeredWasapiBinding_; // one explicit remap // Control-thread only; retain full class identity for exact comparison, // publish correlation HASH only. Never read registry in audio callback. armix::device::AsioRegistrationPolicy::Identity asioPinnedRegistration_; diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index dbcd5b5b0..3f1f97af9 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -4,6 +4,7 @@ #include "../engine/core/MasterOutputMonoPolicy.h" #include "../engine/core/LiveChannelFxGraph.h" #include "../engine/core/DynamicChannelFxLeaseBank.h" +#include "../engine/device/DeviceSessionTransitionPolicy.h" #include "../engine/core/NativeFxRackTransaction.h" #include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "VstBusLayout.h" @@ -453,6 +454,7 @@ class LiveDryRoutingLab final { channelIdPcmEpoch_.store(previousPcmEpoch,std::memory_order_release); switch(result) { case Publisher::Result::applied: + reboundQuantum_.store(Block::hardFrameLimit,std::memory_order_release); publishedEpoch_.store(currentEpoch,std::memory_order_release); enabled_.store(true,std::memory_order_release); sendCount_.store(sends.count,std::memory_order_relaxed); @@ -2238,10 +2240,11 @@ class LiveDryRoutingLab final { return true; return false; } - // CONTROL only. The verified profile proves identical port ordinals, - // rate and block size. Recompile the accepted ChannelId roster to reset - // DSP scratch/PDC, but preserve vendor instances and every document ID. - bool rebindVerifiedDevice(std::uint64_t priorEpoch,std::uint64_t newEpoch) { + // CONTROL only. The verified profile proves identical port ordinals. + // Rebuild DSP scratch/PDC while retaining the accepted document and + // compatible processors. Never re-use a processor at a different rate. + bool rebindVerifiedDevice(std::uint64_t priorEpoch,std::uint64_t newEpoch, + int deviceFrames,bool rateChanged) { using namespace armix::mixer; if(!priorEpoch || newEpoch<=priorEpoch || newEpoch!=epoch() || publishedEpoch_.load(std::memory_order_acquire)!=priorEpoch || @@ -2251,6 +2254,28 @@ class LiveDryRoutingLab final { const bool native=rebindableNativeEpoch_.load(std::memory_order_acquire)==priorEpoch; if(!native && (nativeStructureLive_ || nativeControlDirty_ || nativeAccepted_.deviceEpoch==priorEpoch))return false; + const auto* compatibility=publisher_.controlPrepared(priorEpoch,revision()); + if(!compatibility)return false; + int preparedFrames=std::min(compatibility->maxFramesPerPlugin(), + reboundQuantum_.load(std::memory_order_acquire)); + if(native)preparedFrames=std::min(preparedFrames,nativeAccepted_.graph.request.maxFrames); + bool hasEffects=false; + if(rateChanged) { + // Also check the compatibility plan. It can still hold legacy + // owners which a later M4 operation might otherwise reuse. + for(int lane=0;laneinsertsOn(lane)>0; + if(native && nativeAccepted_.fxOwners) { + hasEffects=hasEffects || nativeAccepted_.fxOwners->externalChannel().value!=0; + for(const auto& row:nativeAccepted_.graph.roster.channels()) { + if(hasEffects)break; + hasEffects=nativeAccepted_.fxOwners->insertCount(row.id)>0; + } + } + } + const int quantum=armix::device::retainedMixerQuantum( + preparedFrames,deviceFrames,Block::hardFrameLimit,rateChanged,hasEffects); + if(quantum==0)return false; std::shared_ptr owner; DynamicNativeSessionPublisher::FxPlan fx; const auto revision=nativeAccepted_.pcmRevision; @@ -2289,6 +2314,7 @@ class LiveDryRoutingLab final { nativeControlDirty_=true; channelIdPcmEpoch_.store(newEpoch,std::memory_order_release); } + reboundQuantum_.store(quantum,std::memory_order_release); publishedEpoch_.store(newEpoch,std::memory_order_release); userPatched_.store(true,std::memory_order_release); return newEpoch==epoch() && ready(); @@ -2377,6 +2403,9 @@ class LiveDryRoutingLab final { silence();return true; } const auto generation=epoch(); + // Sample the cap before leasing. A fresh plan may raise the cap + // after publishing, while an older callback still holds its lease. + const int reboundQuantum=reboundQuantum_.load(std::memory_order_acquire); auto lease=publisher_.acquire(); const auto* snapshot=lease.get(generation); if(!snapshot||!snapshot->prepared || @@ -2438,7 +2467,7 @@ class LiveDryRoutingLab final { // Large/variable JUCE quantum is chunked using stack pointer views; // no heap allocation or new processing object inside callback. std::array shifted{}; - const int max=snapshot->prepared->maxFramesPerPlugin(); + const int max=std::min(snapshot->prepared->maxFramesPerPlugin(),reboundQuantum); if(max<=0) { topologyFault_.store(true,std::memory_order_release); silence();return true; @@ -2743,6 +2772,7 @@ class LiveDryRoutingLab final { std::atomic deviceEpoch_{0}; std::atomic publishedEpoch_{0}; std::atomic rebindableNativeEpoch_{0}; + std::atomic reboundQuantum_{Block::hardFrameLimit}; std::atomic callbackInputCount_{-1}; std::atomic callbackOutputCount_{-1}; std::atomic enabled_{false}; diff --git a/src/Main.cpp b/src/Main.cpp index 87491dd45..6fb1f2190 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -1128,7 +1128,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // thread. A vendor driver may block; never pretend JS async fixes it. const auto id=args.getProperty("requestId",{}).toString().substring(0,64); const auto oldGeneration=engine_.status().getProperty("deviceGeneration",0); - auto send=[&](bool ok,const juce::String& state,const juce::String& error) + auto send=[&](bool ok,const juce::String& state,const juce::String& error, + bool canReusePins=false) { auto ack=std::make_unique(); ack->setProperty("requestId",id); @@ -1138,6 +1139,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr ack->setProperty("active",currentDeviceSnapshot()); ack->setProperty("outputMuted",engine_.isOutputMuted()); ack->setProperty("mixerBound",engine_.hasBoundMixerRoute()); + ack->setProperty("canReusePins",canReusePins); if(browser_.loaded) browser_.emitEventIfBrowserIsVisible("arMixAudioDeviceApplyAck",juce::var(ack.release())); }; @@ -1191,6 +1193,25 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr &&before.outputDeviceName==playback; auto* previousDevice=manager.getCurrentAudioDevice(); const bool previousWasOpen=previousDevice!=nullptr&&previousDevice->isOpen(); + const auto confirm=config.getProperty("confirmRetainedPinMapping",false); + if(!confirm.isBool()) + return send(false,"REJECTED","Invalid retained mixer mapping confirmation"); + if(static_cast(confirm)) { + // The first Apply must open and verify the selected device. + // Confirmation binds only that exact, still-open generation; + // draft rate, buffer and pin changes use the normal Apply path. + if(!sameEndpoint || !previousWasOpen || rate!=before.sampleRate || + block!=before.bufferSize || + !engine_.confirmRetainedWasapiPortMapping()) + return send(false,"NEEDS_REMAP", + "Cannot reuse mixer pins. Endpoint, pin layout or FX format is incompatible."); + deviceSettingsDirty_=true; + directRestore_.cancel(); + diagnostics_.record("CUSTOM_AUDIO_REMAP_ACCEPTED",typeName); + send(true,"ACCEPTED_MUTED",{}); + emitApprovedNativeSnapshot(); + return; + } const auto originalInputNames=previousWasOpen ?previousDevice->getInputChannelNames():juce::StringArray{}; const auto originalOutputNames=previousWasOpen @@ -1295,9 +1316,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr error="Driver readback mismatch; device setting was not accepted"; if(error.isEmpty()&&!engine_.finishManualAudioSetup()) { if(engine_.directRouteAuthorized()&&engine_.hasRetainedUnboundMixer()) { - const juce::String needsRemap="Device verified. Mixer retained and muted; its previous hardware mapping could not be verified"; + const juce::String needsRemap="Device opened. Mixer retained and muted; its port mapping or FX processing format needs review"; diagnostics_.record("CUSTOM_AUDIO_NEEDS_REMAP",needsRemap); - send(false,"NEEDS_REMAP",needsRemap); + send(false,"NEEDS_REMAP",needsRemap,engine_.stageRetainedWasapiPortMapping()); emitApprovedNativeSnapshot(); return; } diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index bee2dff11..c16dfcffd 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -147,6 +147,37 @@ def main(): # Late readback from the disconnected epoch cannot re-admit audio. emit(page,'arMixConsoleSnapshot',state) assert page.evaluate('()=>window.__ARMIX_NATIVE_M2__.state().current.retained') + # A new WASAPI pair is inspected before exposing a separate, + # explicit confirmation for the retained numbered pin mapping. + 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, + 'inputNames':['Input 1'],'outputNames':['Output 1','Output 2'], + 'enabledInputs':[0],'enabledOutputs':[0,1],'rates':[48000],'buffers':[256]} + emit(page,'arMixAudioDeviceInventory',{'active':active,'types':[ + {'name':backend,'inputs':['New Capture'],'outputs':['New Playback'],'separate':True}]}) + remap=page.locator('[data-audio-remap]') + assert remap.is_hidden() + page.locator('[data-audio-apply]').click() + read_apply='()=>window.__events.filter(e=>e.payload?.action==="audioDeviceApply").at(-1).payload' + opened=page.evaluate(read_apply) + assert 'confirmRetainedPinMapping' not in opened['config'] + emit(page,'arMixAudioDeviceApplyAck',{'requestId':'old','state':'NEEDS_REMAP', + 'active':active,'canReusePins':True}) + assert remap.is_hidden() + emit(page,'arMixAudioDeviceApplyAck',{'requestId':opened['requestId'],'state':'NEEDS_REMAP', + 'active':active,'canReusePins':True}) + remap.click() + binding=page.evaluate(read_apply) + assert binding['config']['confirmRetainedPinMapping'] is True + assert binding['expectedDeviceGeneration']==12 + assert binding['config']['captureDevice']=='New Capture' + assert binding['config']['playbackDevice']=='New Playback' + assert binding['config']['sampleRate']==48000 and binding['config']['bufferSize']==256 + emit(page,'arMixAudioDeviceApplyAck',{'requestId':binding['requestId'],'ok':True, + 'state':'ACCEPTED_MUTED','active':active,'mixerBound':True}) + assert page.locator('.armix-audio-shade').is_hidden() rebound=copy.deepcopy(state) rebound['device'].update(epoch='93',outputArmed=False) rebound['graph']['revision']='6' diff --git a/tests/device_session_transition_policy_test.cpp b/tests/device_session_transition_policy_test.cpp index 646b82019..2c28e9a69 100644 --- a/tests/device_session_transition_policy_test.cpp +++ b/tests/device_session_transition_policy_test.cpp @@ -7,6 +7,14 @@ using armix::device::decideDeviceSession; int main() { + using armix::device::retainedMixerQuantum; + static_assert(retainedMixerQuantum(256,1024,8192,false,true)==256); + static_assert(retainedMixerQuantum(256,64,8192,false,true)==64); + static_assert(retainedMixerQuantum(64,512,8192,false,true)==64); + static_assert(retainedMixerQuantum(256,512,8192,true,false)==256); + static_assert(retainedMixerQuantum(256,512,8192,true,true)==0); + static_assert(retainedMixerQuantum(256,8193,8192,false,false)==0); + static_assert(retainedMixerQuantum(0,512,8192,false,false)==0); // Opening and closing the dialog without a real hardware generation // change never discards an accepted mixer, regardless of its contents. static_assert(decideDeviceSession(true, true, true) == diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index d23e9f8d9..82c1911b7 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1266,7 +1266,8 @@ // 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,pendingDeviceMute=null,deviceChoice=null,deviceResult=""; + deviceRequest=0,pendingDeviceMute=null,deviceChoice=null,deviceResult="", + offeredPinRemap=null; let toastTimer=0; function nativeToast(message){ let element=document.getElementById("armixNativeToast"); @@ -1337,6 +1338,7 @@
+
`; devicePanel.querySelector("[data-audio-close]").onclick=()=>{ devicePanel.hidden=true; @@ -1346,6 +1348,7 @@ }); devicePanel.addEventListener("change",e=>{ if(!deviceChoice)return; + offeredPinRemap=null; deviceResult=""; const pinSide=e.target.dataset.audioPin; if(pinSide==="input"||pinSide==="output"){ @@ -1399,11 +1402,17 @@ },8000); }else sendDeviceApply(); }; + devicePanel.querySelector("[data-audio-remap]").onclick=()=>{ + if(!deviceBusy && !pendingDeviceMute && offeredPinRemap!==null && + !hardware?.device?.outputArmed) + sendDeviceApply(true); + }; document.body.appendChild(devicePanel); } devicePanel.hidden=false; const active=devicePanel.querySelector("[data-audio-active]"); deviceResult=""; + offeredPinRemap=null; if(active)active.textContent="Reading verified audio devices…"; backend.emitEvent("arMixAction",{action:"audioDeviceInventory"}); } @@ -1484,12 +1493,17 @@ devicePanel.querySelector("[data-audio-apply]").disabled=deviceBusy|| !!pendingDeviceMute||!deviceChoice.backend||!deviceChoice.capture|| !deviceChoice.playback; + const remap=devicePanel.querySelector("[data-audio-remap]"); + remap.hidden=!same || offeredPinRemap!==active.deviceGeneration; + remap.disabled=deviceBusy || !!pendingDeviceMute; + remap.title="Reuse existing input and output pin numbers on the selected device. MONITOR stays off."; } - function sendDeviceApply(){ + function sendDeviceApply(confirmRetainedPinMapping=false){ if(!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; deviceBusy=true; const requestId="approved-io-"+(++deviceRequest); devicePanel.dataset.pendingRequest=requestId; @@ -1498,10 +1512,12 @@ backend.emitEvent("arMixAction",{action:"audioDeviceApply", requestId,expectedDeviceGeneration:Number(a.deviceGeneration), config:{backend:c.backend,captureDevice:c.capture, - playbackDevice:c.playback,sampleRate:same?c.rate:0, - bufferSize:same?c.buffer:0, + 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:[]}}); + enabledOutputs:same?c.outputPins:[], + ...(confirmRetainedPinMapping?{confirmRetainedPinMapping:true}:{})}}); } if(connected){ backend.addEventListener("arMixAudioDeviceInventory",inventory=>{ @@ -1514,6 +1530,10 @@ if(!devicePanel||ack?.requestId!==devicePanel.dataset.pendingRequest)return; deviceBusy=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&&ack.state==="ACCEPTED_MUTED" && ack.active?.open===true && ack.active?.authorized===true && Array.isArray(ack.active.enabledInputs) && From f9bb6d047166b5de1170ccd617c49ad1faaa19c7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 12:59:32 +0700 Subject: [PATCH 165/219] release(windows): add installable per-user RC with real install/uninstall FAT verification Generate separate Inno Setup artifact from the independently SHA-verified native GUI and reviewed FactoryFX without touching portable ZIP. Validate installed PE identity, provenance, no portable storage mode and AppData Studio survival. Candidate remains unsigned and physical-FAT unqualified. --- .github/workflows/p1-windows.yml | 31 ++++++++- installer/ArSonMix.iss | 38 +++++++++++ scripts/build_verify_windows_installer.ps1 | 76 ++++++++++++++++++++++ tests/windows_installer_contract_test.mjs | 23 +++++++ 4 files changed, 167 insertions(+), 1 deletion(-) create mode 100644 installer/ArSonMix.iss create mode 100644 scripts/build_verify_windows_installer.ps1 create mode 100644 tests/windows_installer_contract_test.mjs diff --git a/.github/workflows/p1-windows.yml b/.github/workflows/p1-windows.yml index 37e13c6e5..0c8aa9410 100644 --- a/.github/workflows/p1-windows.yml +++ b/.github/workflows/p1-windows.yml @@ -26,6 +26,9 @@ on: - 'web/monitor.js' - 'tests/*.cpp' - 'scripts/package_native_windows.ps1' + - 'scripts/build_verify_windows_installer.ps1' + - 'installer/**' + - 'tests/windows_installer_contract_test.mjs' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/console_v6_fat_gate.mjs' @@ -64,6 +67,9 @@ on: - 'web/monitor.js' - 'tests/*.cpp' - 'scripts/package_native_windows.ps1' + - 'scripts/build_verify_windows_installer.ps1' + - 'installer/**' + - 'tests/windows_installer_contract_test.mjs' - 'scripts/verify_native_windows_artifact.ps1' - 'scripts/collect_hardware_fat_windows.ps1' - 'scripts/console_v6_fat_gate.mjs' @@ -121,7 +127,7 @@ jobs: node scripts/check_console_puzzle.mjs node --check web/approved-native-bridge.js node --check web/approved-native-contract.js - node --test tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract_test.mjs tests/live_graph_contract_test.mjs + node --test tests/workstream_coordination_contract.test.mjs tests/ci_workflow_efficiency_test.mjs tests/chat_ci_dispatch_contract.test.mjs tests/approved_native_m2_contract.test.cjs tests/native_artifact_packaging_contract_test.mjs tests/windows_installer_contract_test.mjs tests/live_graph_contract_test.mjs python -m unittest discover -s tests -p approved_native_gui_bundle_test.py -v python -m unittest discover -s scripts/tests -p test_factoryfx_release_bundle.py -v windows-build: @@ -197,6 +203,7 @@ jobs: 'tests/independent_clock_adapter_contract_test.mjs' 'tests/direct_restore_recovery_contract_test.mjs' 'tests/native_artifact_packaging_contract_test.mjs' + 'tests/windows_installer_contract_test.mjs' 'tests/portable_workspace_contract_test.mjs' 'tests/plugin_vault_contract_test.mjs' 'tests/plugin_ui_contract_test.mjs' @@ -239,6 +246,28 @@ jobs: run: | & ./scripts/verify_native_windows_artifact.ps1 -OutputDir dist if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - name: Install Inno Setup 6 compiler if missing + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + shell: pwsh + run: | + if (-not (Get-Command ISCC.exe -ErrorAction SilentlyContinue) -and + -not (Test-Path -LiteralPath 'C:\Program Files (x86)\Inno Setup 6\ISCC.exe')) { + choco install innosetup --yes --no-progress --limit-output + if ($LASTEXITCODE -ne 0) { throw 'Inno Setup compiler installation failed' } + } + - name: Compile and validate per-user Windows RC installer from exact FAT PE + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + shell: pwsh + run: | + & ./scripts/build_verify_windows_installer.ps1 -OutputDir dist -InstallerOutput installer-output + if ($LASTEXITCODE -ne 0) { exit $LASTEXITCODE } + - uses: actions/upload-artifact@v4 + if: ${{ github.event_name == 'workflow_dispatch' && inputs.package_fat == true }} + with: + name: ArSonMix-Windows-Installer-UNQUALIFIED-${{ github.run_id }} + path: installer-output/ + if-no-files-found: error + retention-days: 14 # Optional manual FAT only: never churn experimental ZIPs per commit. # The unqualified artifact is NOT a stable release or physical audio proof. - uses: actions/upload-artifact@v4 diff --git a/installer/ArSonMix.iss b/installer/ArSonMix.iss new file mode 100644 index 000000000..ed7999f29 --- /dev/null +++ b/installer/ArSonMix.iss @@ -0,0 +1,38 @@ +; ArSonMix x64 RC from exact independently verified FAT app, no new DSP or GUI. +#ifndef SourceRoot + #error "Supply /DSourceRoot with SHA-verified staging directory" +#endif +#ifndef OutputRoot + #error "Supply /DOutputRoot with destination directory" +#endif +[Setup] +AppId=ArSonMix.LiveStudio +AppName=ArSonMix +AppVersion=0.1.0-rc.1 +AppVerName=ArSonMix RC (hardware FAT pending) +AppPublisher=ArSonMix +AppPublisherURL=https://masarray.github.io/arsonmix/ +DefaultDirName={localappdata}\Programs\ArSonMix +PrivilegesRequired=lowest +DisableProgramGroupPage=yes +ArchitecturesAllowed=x64compatible +ArchitecturesInstallIn64BitMode=x64compatible +MinVersion=10.0.17763 +WizardStyle=modern +OutputDir={#OutputRoot} +OutputBaseFilename=ArSonMix-Windows-x64-Setup-UNQUALIFIED +SetupIconFile={#SourceRoot}\arsonmix-app.ico +UninstallDisplayIcon={app}\ArSonMix.exe +Compression=lzma2 +SolidCompression=yes +CloseApplications=no +RestartApplications=no +[Files] +Source: "{#SourceRoot}\verified-gui.exe"; DestDir: "{app}"; DestName: "ArSonMix.exe"; Flags: ignoreversion +Source: "{#SourceRoot}\BUILD_PROVENANCE.json"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#SourceRoot}\README.md"; DestDir: "{app}"; Flags: ignoreversion +Source: "{#SourceRoot}\FactoryFX\*"; DestDir: "{app}\FactoryFX"; Flags: ignoreversion recursesubdirs createallsubdirs skipifsourcedoesntexist +[Icons] +Name: "{autoprograms}\ArSonMix"; Filename: "{app}\ArSonMix.exe"; WorkingDir: "{app}" +; No Run or UninstallDelete: do not auto-activate live audio or erase +; AppData Studio. Do not install portable_mode.txt. diff --git a/scripts/build_verify_windows_installer.ps1 b/scripts/build_verify_windows_installer.ps1 new file mode 100644 index 000000000..6cfab9f11 --- /dev/null +++ b/scripts/build_verify_windows_installer.ps1 @@ -0,0 +1,76 @@ +# SPDX-License-Identifier: AGPL-3.0-only +# Independent FAT-only GUI installer build AND real per-user install/uninstall. +param([string]$OutputDir="dist",[string]$InstallerOutput="installer-output") +Set-StrictMode -Version Latest +$ErrorActionPreference="Stop" +$dist=(Resolve-Path -LiteralPath $OutputDir).Path +$sha=(& git rev-parse HEAD).Trim() +$manifest=Get-Content -LiteralPath (Join-Path $dist "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json +$exe=Join-Path $dist "ArSonMix-GUI10CH-P012-Windows-x64.exe" +$appHash=(Get-FileHash -LiteralPath $exe -Algorithm SHA256).Hash.ToLowerInvariant() +if($LASTEXITCODE -ne 0 -or $manifest.sourceCommit -ne $sha -or + $manifest.exeSha256 -ne $appHash -or $manifest.fatStatus -ne "EXPERIMENTAL_NOT_HARDWARE_QUALIFIED" -or + (Get-Item -LiteralPath $exe).Length -ne $manifest.guiExeBytes -or + (Test-Path -LiteralPath (Join-Path $dist "Studio"))) { + throw "Installer requires the exact already verified and hardware-unqualified FAT PE" +} +$which=Get-Command ISCC.exe -ErrorAction SilentlyContinue +$iscc=if($which){$which.Source}else{"C:\Program Files (x86)\Inno Setup 6\ISCC.exe"} +if(-not (Test-Path -LiteralPath $iscc -PathType Leaf)){throw "Inno Setup 6 compiler missing"} +$root=(Resolve-Path .).Path +$out=Join-Path $root $InstallerOutput +New-Item -ItemType Directory -Force -Path $out | Out-Null +$stage=Join-Path $env:RUNNER_TEMP ("arsonmix-install-stage-"+[guid]::NewGuid().ToString("N")) +$install=Join-Path $env:RUNNER_TEMP ("arsonmix-install-test-"+[guid]::NewGuid().ToString("N")) +$studio=Join-Path $env:APPDATA "AR-MIX-Studio" +New-Item -ItemType Directory -Force -Path $studio | Out-Null +$sentinel=Join-Path $studio ("installer-test-"+[guid]::NewGuid().ToString("N")+".keep") +"persistent-private-data" | Set-Content -LiteralPath $sentinel +try { + New-Item -ItemType Directory -Force -Path $stage | Out-Null + Copy-Item -LiteralPath $exe -Destination (Join-Path $stage "verified-gui.exe") + foreach($item in @("BUILD_PROVENANCE.json","README.md")){ + Copy-Item -LiteralPath (Join-Path $dist $item) -Destination (Join-Path $stage $item) + } + Copy-Item -LiteralPath "assets/icon/arsonmix-app.ico" -Destination (Join-Path $stage "arsonmix-app.ico") + $factory=Join-Path $dist "FactoryFX" + if(Test-Path -LiteralPath $factory -PathType Container){ + Copy-Item -LiteralPath $factory -Destination (Join-Path $stage "FactoryFX") -Recurse + } + & $iscc "/Qp" "/DSourceRoot=$stage" "/DOutputRoot=$out" "installer/ArSonMix.iss" + $setup=Join-Path $out "ArSonMix-Windows-x64-Setup-UNQUALIFIED.exe" + if($LASTEXITCODE -ne 0 -or -not (Test-Path -LiteralPath $setup -PathType Leaf) -or + (Get-Item -LiteralPath $setup).Length -lt 2MB){throw "ISCC failed to build installer RC"} + $start=Start-Process -FilePath $setup -ArgumentList @( + "/VERYSILENT","/SUPPRESSMSGBOXES","/NORESTART","/CURRENTUSER","/DIR=$install" + ) -Wait -PassThru + if($start.ExitCode -ne 0){throw "Actual Windows installation failed"} + $installedExe=Join-Path $install "ArSonMix.exe" + if(-not (Test-Path -LiteralPath $installedExe -PathType Leaf) -or + (Get-FileHash -LiteralPath $installedExe -Algorithm SHA256).Hash.ToLowerInvariant() -ne $appHash -or + (Test-Path -LiteralPath (Join-Path $install "portable_mode.txt"))){ + throw "Installed EXE hash or storage mode differs from source" + } + $installedManifest=Get-Content -LiteralPath (Join-Path $install "BUILD_PROVENANCE.json") -Raw -Encoding UTF8 | ConvertFrom-Json + if($installedManifest.sourceCommit -ne $sha){throw "Wrong installed provenance"} + $uninstall=Join-Path $install "unins000.exe" + if(-not (Test-Path -LiteralPath $uninstall -PathType Leaf)){throw "Uninstaller missing"} + $stop=Start-Process -FilePath $uninstall -ArgumentList @( + "/VERYSILENT","/SUPPRESSMSGBOXES","/NORESTART" + ) -Wait -PassThru + if($stop.ExitCode -ne 0 -or -not (Test-Path -LiteralPath $sentinel)){ + throw "Uninstaller failed or erased user Studio data" + } + [ordered]@{ + sourceCommit=$sha;guiSha256=$appHash + installerSha256=(Get-FileHash -LiteralPath $setup -Algorithm SHA256).Hash.ToLowerInvariant() + certification="UNSIGNED_HARDWARE_FAT_PENDING";mode="PER_USER_NO_AUTOARM" + } | ConvertTo-Json | Set-Content -LiteralPath (Join-Path $out "INSTALLER_PROVENANCE.json") -Encoding UTF8 + Write-Host "INSTALLER_RC_VERIFIED: SHA-matched PE, install/uninstall, private Studio intact" + Write-Host "PHYSICAL_FAT_PENDING" +} +finally { + if(Test-Path -LiteralPath $sentinel){Remove-Item -LiteralPath $sentinel -Force} + if(Test-Path -LiteralPath $stage){Remove-Item -LiteralPath $stage -Recurse -Force} + if(Test-Path -LiteralPath $install){Remove-Item -LiteralPath $install -Recurse -Force -ErrorAction SilentlyContinue} +} diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs new file mode 100644 index 000000000..862312224 --- /dev/null +++ b/tests/windows_installer_contract_test.mjs @@ -0,0 +1,23 @@ +import test from 'node:test'; +import assert from 'node:assert/strict'; +import {readFileSync} from 'node:fs'; +const read=p=>readFileSync(p,'utf8'); +const iss=read('installer/ArSonMix.iss'); +const ps=read('scripts/build_verify_windows_installer.ps1'); +const ci=read('.github/workflows/p1-windows.yml'); +test('Inno RC is per-user, 64-bit, no automatic activation or Studio deletion',()=>{ + for(const item of ['PrivilegesRequired=lowest','DefaultDirName={localappdata}', + 'ArchitecturesAllowed=x64compatible','CloseApplications=no','RestartApplications=no', + 'UNQUALIFIED','verified-gui.exe','BUILD_PROVENANCE.json']) assert.ok(iss.includes(item),item); + assert.doesNotMatch(iss,/^\[(Run|UninstallDelete)\]/m); + assert.doesNotMatch(iss,/^Source:.*portable_mode\.txt/m); +}); +test('installer only derives from verified FAT PE and tests uninstall safely',()=>{ + for(const item of ['manifest.sourceCommit','manifest.exeSha256','manifest.fatStatus', + 'assets/icon/arsonmix-app.ico','FactoryFX','Start-Process -FilePath $setup', + 'Start-Process -FilePath $uninstall','Test-Path -LiteralPath $sentinel', + 'PHYSICAL_FAT_PENDING','INSTALLER_PROVENANCE.json'])assert.ok(ps.includes(item),item); + assert.ok(ci.indexOf('scripts/verify_native_windows_artifact.ps1')< + ci.indexOf('scripts/build_verify_windows_installer.ps1')); + assert.match(ci,/ArSonMix-Windows-Installer-UNQUALIFIED/); +}); From 803e1d9618777894ca5a56c8011fb7b8a34c4d34 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 13:00:15 +0700 Subject: [PATCH 166/219] test(installer): check release verification job order, not workflow path-filter text --- tests/windows_installer_contract_test.mjs | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/tests/windows_installer_contract_test.mjs b/tests/windows_installer_contract_test.mjs index 862312224..cefe9ee4b 100644 --- a/tests/windows_installer_contract_test.mjs +++ b/tests/windows_installer_contract_test.mjs @@ -17,7 +17,8 @@ test('installer only derives from verified FAT PE and tests uninstall safely',() 'assets/icon/arsonmix-app.ico','FactoryFX','Start-Process -FilePath $setup', 'Start-Process -FilePath $uninstall','Test-Path -LiteralPath $sentinel', 'PHYSICAL_FAT_PENDING','INSTALLER_PROVENANCE.json'])assert.ok(ps.includes(item),item); - assert.ok(ci.indexOf('scripts/verify_native_windows_artifact.ps1')< - ci.indexOf('scripts/build_verify_windows_installer.ps1')); + const verifyStep=ci.indexOf(' - name: Independently verify release ZIP and embedded GUI/engine before upload'); + const installerStep=ci.indexOf(' - name: Compile and validate per-user Windows RC installer from exact FAT PE'); + assert.ok(verifyStep>=0 && installerStep>verifyStep); assert.match(ci,/ArSonMix-Windows-Installer-UNQUALIFIED/); }); From d2e9c82c18960a4dcc4b444afe6e7009610086df Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 13:01:17 +0700 Subject: [PATCH 167/219] test(ci): preserve deliberate FAT-only seven-step portable and installer gates --- tests/ci_workflow_efficiency_test.mjs | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/ci_workflow_efficiency_test.mjs b/tests/ci_workflow_efficiency_test.mjs index 161eec8e1..51227772d 100644 --- a/tests/ci_workflow_efficiency_test.mjs +++ b/tests/ci_workflow_efficiency_test.mjs @@ -163,7 +163,7 @@ test('Windows realtime CTest is explicit for PR milestones; packaging requires d assert.match(native,/^ windows-build:[\s\S]*?needs: quick\n/m); assert.match(native,/github\.event_name != 'pull_request'/); const fatOnly = [...native.matchAll(/^ if: .*inputs\.package_fat == true.*$/gm)].length; - assert.equal(fatOnly,4,'Packaging, FactoryFX stage, ZIP verify and upload require manual FAT'); + assert.equal(fatOnly,7,'Portable FAT and Inno installer build/verify/upload all require deliberate manual opt-in'); assert.match(native,/FAT_EXACT_PR_HEAD_CHECKOUT/); assert.match(native,/ctest --test-dir build -C Release --output-on-failure/); assert.ok(native.indexOf('scripts/verify_native_windows_artifact.ps1 -OutputDir dist') < From 2e1561939756b068ebfd2c6b8c5beff4b6f1543c Mon Sep 17 00:00:00 2001 From: masarray Date: Sat, 7 Nov 2026 13:04:37 +0700 Subject: [PATCH 168/219] Compare CSS optimizer against the composed operator layout --- tests/approved_css_original_bundle_fixture.py | 21 +++++++++++++++++- ...roved_css_stage_c_computed_parity_smoke.py | 22 +++---------------- ...pproved_stage_c_css_visual_parity_smoke.py | 13 ++--------- 3 files changed, 25 insertions(+), 31 deletions(-) diff --git a/tests/approved_css_original_bundle_fixture.py b/tests/approved_css_original_bundle_fixture.py index 2162f2a99..82385d9d8 100644 --- a/tests/approved_css_original_bundle_fixture.py +++ b/tests/approved_css_original_bundle_fixture.py @@ -2,13 +2,19 @@ Do not recreate another GUI. HTML+JS+PNG are copied from compiled /preview/, and only the ONE generated runtime stylesheet link is exchanged for the -18 original source owner links before testing the original owner CSS files. +18 original owner links. Restore the sheets after operator UX composition +and before the CSS optimizer, so both sides have the same presentation. """ from pathlib import Path import re +import shutil +import sys ROOT = Path(__file__).resolve().parents[1] SOURCE = ROOT / "site/preview-v2/index.html" +sys.path.insert(0, str(ROOT / "scripts")) +from compile_approved_css import LINK +from compose_operator_ux import apply_operator_ux ORIGINAL_LINK = re.compile( r'' ) @@ -26,3 +32,16 @@ def reconstructed_original_css_html(shipped_html: str) -> str: if len(ORIGINAL_LINK.findall(shipped_html)) != 1: raise ValueError("Unexpected extra runtime CSS stack") return RUNTIME_LINK.sub("\n".join(original), shipped_html, count=1) + +def restore_original_css_bundle(bundle: Path) -> None: + index = bundle / "index.html" + assets = bundle / "assets" + original_html = reconstructed_original_css_html(index.read_text(encoding="utf-8")) + source_html = SOURCE.read_text(encoding="utf-8") + for _, name, _, _ in LINK.findall(source_html): + owner = "preview-buttons" if name == "mixer-control-keys.css" else "preview-v2" + shutil.copyfile(ROOT / "site" / owner / "assets" / name, assets / name) + # The shipped DOM already contains the same composition. Reapply it + # only to reconstruct the CSS owner bytes, using its original HTML input. + apply_operator_ux(source_html, assets) + index.write_text(original_html, encoding="utf-8") diff --git a/tests/approved_css_stage_c_computed_parity_smoke.py b/tests/approved_css_stage_c_computed_parity_smoke.py index 26f967a7d..8768a2d19 100644 --- a/tests/approved_css_stage_c_computed_parity_smoke.py +++ b/tests/approved_css_stage_c_computed_parity_smoke.py @@ -9,21 +9,11 @@ import shutil import tempfile from playwright.async_api import async_playwright -from approved_css_original_bundle_fixture import reconstructed_original_css_html +from approved_css_original_bundle_fixture import restore_original_css_bundle ROOT = Path(__file__).resolve().parents[1] PRODUCTION = ROOT / "dist-pages" / "preview" -SHEETS = ( - "mixer-console-foundation.css", "mixer-channel-grid.css", - "mixer-section-controls.css", "mixer-section-layout.css", - "mixer-hardware-artwork.css", "mixer-v3-layout-contract.css", - "mixer-chrome-material.css", "mixer-control-keys.css", - "mixer-fx-rack.css", "mixer-plugin-browser.css", - "mixer-pan-controls.css", "mixer-fader-assembly.css", - "mixer-meter-display.css", "mixer-utility-controls.css", - "inter-embedded.css", "mixer-wire-dots.css", - "mixer-wire-out-align-v48.css", "mixer-contextual-buttons.css", -) + PROPERTIES = ( "display", "position", "visibility", "opacity", "width", "height", "min-width", "min-height", "max-width", "max-height", "top", "left", @@ -103,13 +93,7 @@ async def main(): with tempfile.TemporaryDirectory(prefix="armix-css-c-baseline-") as tmp: before = Path(tmp) / "approved-original-css" shutil.copytree(PRODUCTION, before) - original_html=reconstructed_original_css_html((before/'index.html').read_text(encoding='utf-8')) - (before/'index.html').write_text(original_html,encoding='utf-8') - for name in SHEETS: - source = (ROOT / ("site/preview-buttons/assets" - if name == "mixer-control-keys.css" - else "site/preview-v2/assets") / name) - shutil.copy2(source, before / "assets" / name) + restore_original_css_bundle(before) async with async_playwright() as playwright: browser = await playwright.chromium.launch(headless=True) try: diff --git a/tests/approved_stage_c_css_visual_parity_smoke.py b/tests/approved_stage_c_css_visual_parity_smoke.py index b19696e21..51adf1b86 100644 --- a/tests/approved_stage_c_css_visual_parity_smoke.py +++ b/tests/approved_stage_c_css_visual_parity_smoke.py @@ -7,12 +7,11 @@ import asyncio import hashlib from pathlib import Path -import re import shutil import tempfile from playwright.async_api import async_playwright -from approved_css_original_bundle_fixture import reconstructed_original_css_html +from approved_css_original_bundle_fixture import restore_original_css_bundle ROOT=Path(__file__).resolve().parents[1] COMPILED=ROOT/"dist-pages/preview" @@ -74,15 +73,7 @@ async def main(): with tempfile.TemporaryDirectory(prefix="armix-stage-c-original-") as tmp: baseline=Path(tmp)/"preview" shutil.copytree(COMPILED,baseline) - original_html=reconstructed_original_css_html((baseline/'index.html').read_text(encoding='utf-8')) - (baseline/'index.html').write_text(original_html,encoding='utf-8') - cssnames=[p.name for p in (COMPILED/"assets").glob("*.css")] - for name in cssnames: - source=(ROOT/("site/preview-buttons/assets" - if name=="mixer-control-keys.css" - else "site/preview-v2/assets")/name) - if source.is_file(): - shutil.copyfile(source,baseline/"assets"/name) + restore_original_css_bundle(baseline) async with async_playwright() as playwright: browser=await playwright.chromium.launch(headless=True) try: From 089062fd0a5e1775159b8105ff2622727c054b8e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 13:27:28 +0700 Subject: [PATCH 169/219] test(wire): qualify actual V29 comfort/fold/refocus states instead of hidden legacy density selector Preserve nine Chromium viewport/state WIRE audits, canonical MAIN EdgeId, focused remap, fold/unfold, pointer routing, scene SAFE and Undo coverage. This corrects the obsolete tester, not the production GUI or native PCM. --- .../pages_wire_first_canonical_main_smoke.py | 34 ++++++++++++------- 1 file changed, 22 insertions(+), 12 deletions(-) diff --git a/tests/pages_wire_first_canonical_main_smoke.py b/tests/pages_wire_first_canonical_main_smoke.py index a74dc92a3..b2012166f 100644 --- a/tests/pages_wire_first_canonical_main_smoke.py +++ b/tests/pages_wire_first_canonical_main_smoke.py @@ -85,20 +85,27 @@ def drag_to(point,escape=False): def audit_visual_matrix(browser): - """Nine real Chromium renders: viewport, density, focus, collapse, plug.""" + """Nine real Chromium renders: viewport, actual operator focus/fold states and plug.""" for width,height in ((1366,768),(1680,900),(1920,1080)): - for density in ("comfort","standard","compact"): + for presentation in ("default","folded","refocused"): page=browser.new_page(viewport={"width":width,"height":height}, reduced_motion="reduce") errors=[] page.on("pageerror",lambda exc: errors.append(str(exc))) page.goto(PAGE.as_uri()) - page.locator("#densitySelect").select_option(density) body=page.locator(".console-body") - # Narrow/Compact intentionally locks the WIRE bay folded to keep - # 23px physical geometry. It has graph-bound compact contacts, - # not a full cable overlay; the rail refuses expansion by design. - if density=="compact": + # V29 has ONE operator comfort view. The original density select + # remains as a hidden, inert compatibility ID, not a public tool. + # Audit meaningful operator fold and focus states instead of + # selecting an invisible legacy dropdown and timing out. + assert page.locator("#densitySelect").is_hidden() + assert body.get_attribute("data-density")=="comfort" + if presentation=="folded": + if "collapsed-send" not in (body.get_attribute("class") or ""): + page.locator('.section-rail [data-section="send"]').click() + assert "collapsed-send" in (body.get_attribute("class") or "") + # Folded visual sockets may disappear; canonical MAIN EdgeId + # and other channels' connections must not be discarded. assert "collapsed-send" in (body.get_attribute("class") or "") initial=edge(page,1,"out") assert initial, "folded view must retain the canonical MAIN graph edge" @@ -111,8 +118,8 @@ def audit_visual_matrix(browser): assert page.locator('#tracks .strip[data-id="1"] .wire-fold-summary .has-out').count()==0 assert page.locator(".wire-main-fragment").count()==0 page.screenshot(path=str(ROOT/ - f"pages-wire-main-{width}x{height}-{density}.png")) - assert not errors,(width,height,density,errors) + f"pages-wire-main-{width}x{height}-{presentation}.png")) + assert not errors,(width,height,presentation,errors) page.close() continue if "collapsed-send" in (body.get_attribute("class") or ""): @@ -121,6 +128,9 @@ def audit_visual_matrix(browser): assert initial,"quiet MAIN must retain the real graph edge" assert page.locator('.wire-main-fragment').count()==0 assert page.locator('#tracks .strip[data-id="1"] .wire-node-out').get_attribute('data-wire-main-edge')==initial + if presentation=="refocused": + page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() + assert edge(page,2,"out"), "refocus must preserve the other MAIN EdgeId" page.locator('#tracks .strip[data-id="5"] .strip-identity-top').click() focused=edge(page,5,"out") assert page.locator('#master .wire-node-in').get_attribute('data-wire-main-edge')==focused @@ -131,8 +141,8 @@ def audit_visual_matrix(browser): assert page.locator('.wire-main-fragment').count()==0 assert edge(page,1,"out")==initial and edge(page,5,"out")==focused page.screenshot(path=str(ROOT/ - f"pages-wire-main-{width}x{height}-{density}.png")) - assert not errors,(width,height,density,errors) + f"pages-wire-main-{width}x{height}-{presentation}.png")) + assert not errors,(width,height,presentation,errors) page.close() def run(): @@ -263,7 +273,7 @@ def run(): assert edge(page,5,"out") is None,"Snapshot SAFE overwrote live MAIN route" page.close() browser.close() - print("PASS WIRE A: nine Chromium viewport/density cable audits plus exact-edge MAIN gesture, Scene/SAFE, Undo") + print("PASS WIRE A: nine Chromium viewport/operator-state cable audits plus exact-edge MAIN gesture, Scene/SAFE, Undo") if __name__=="__main__": run() From 15cecda4d9f6bfe371751f6259b8e9c53ae46e4c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 13:34:49 +0700 Subject: [PATCH 170/219] test(fx): reconcile V53 Chromium rail tests with one approved operator density Keep 12 viewport/state cases using real fold and channel-refocus instead of hidden legacy selector. Retain FX grip, keyboard/DnD ordering, bypass, insert token identity, undo and header/fader geometry regressions; leave historical base CSS density checks intact. --- tests/pages_fx_rail_v53_smoke.py | 67 +++++++++++++++++--------------- 1 file changed, 36 insertions(+), 31 deletions(-) diff --git a/tests/pages_fx_rail_v53_smoke.py b/tests/pages_fx_rail_v53_smoke.py index fdc98323e..4e2a5f483 100644 --- a/tests/pages_fx_rail_v53_smoke.py +++ b/tests/pages_fx_rail_v53_smoke.py @@ -10,7 +10,7 @@ subprocess.run([sys.executable,str(ROOT/'scripts/build_pages.py'),'--out',_current_gui.name],cwd=ROOT,check=True,capture_output=True) PAGE=published_console(Path(_current_gui.name)) BREAKPOINTS=((1366,768),(1378,911),(1680,900),(1920,1080)) -DENSITIES=("comfort","standard","compact") +PRESENTATIONS=("default","wire-folded","refocused") def model(page,channel="1"): """Read only the public rendered rack; never reach private JS closure state.""" @@ -21,54 +21,46 @@ def model(page,channel="1"): bypassed:row.classList.contains('is-bypassed') })).filter(row=>row.id)""") -def check_geometry(page,width,density): +def check_geometry(page,width,presentation): root=page.locator('#tracks .strip[data-id="1"]') rack=root.locator('.fx-section') plate=rack.locator('.subhead') well=rack.locator('.fxslot-list') p=plate.bounding_box();w=well.bounding_box() - assert p and w and p["height"]>0 and w["height"]>0,(width,density,p,w) + assert p and w and p["height"]>0 and w["height"]>0,(width,presentation,p,w) assert abs(p["x"]-w["x"])<2 and abs(p["width"]-w["width"])<2,\ - (width,density,"FX plate and inset well must share side edges",p,w) + (width,presentation,"FX plate and inset well must share side edges",p,w) assert abs((p["y"]+p["height"])-w["y"])<=2.1,\ - (width,density,"FX header disconnected from processor well",p,w) + (width,presentation,"FX header disconnected from processor well",p,w) skin=plate.evaluate("""el=>({bg:getComputedStyle(el).backgroundImage, border:getComputedStyle(el).borderBottomWidth})""") - assert skin["bg"]!="none" and skin["border"]=="1px",(width,density,skin) + assert skin["bg"]!="none" and skin["border"]=="1px",(width,presentation,skin) assert page.locator('.section-rail .rail-cell.fx .rail-svg-icon').evaluate( - "el=>Math.round(el.getBoundingClientRect().width)")==16,(width,density,"oversized FX rail icon") + "el=>Math.round(el.getBoundingClientRect().width)")==16,(width,presentation,"oversized FX rail icon") assert page.locator("#master .strip .fx-section").count()==1, \ - (width,density,"pinned Master has no rack") + (width,presentation,"pinned Master has no rack") for channel in ('1',): root=page.locator(f'#tracks .strip[data-id="{channel}"]') for row in root.locator('.fxslot-row').all(): - assert row.get_attribute("draggable") is None,(width,density,"row-wide drag regressed") + assert row.get_attribute("draggable") is None,(width,presentation,"row-wide drag regressed") for row in root.locator('.fxslot-row.is-active,.fxslot-row.is-bypassed').all(): grip=row.locator('.fx-grip') remove=row.locator('[data-action="removeFx"]') assert grip.count()==remove.count()==1 g=grip.bounding_box();r=remove.bounding_box() assert g and r and g["x"]+g["width"] <= r["x"]+.5,\ - (width,density,"grip must precede REMOVE",g,r) + (width,presentation,"grip must precede REMOVE",g,r) assert grip.get_attribute("draggable")=="true" assert grip.get_attribute("aria-label"),"FX grip must be keyboard accessible" assert row.locator('.fx-pick').get_attribute("draggable") is None rail=page.locator('.section-rail [data-section="fx"]') assert rail.get_attribute("aria-expanded")=="true" - if density=="compact": - # Approved Narrow mode explicitly refuses FX/SEND disclosure changes to - # protect the calibrated vertical chassis. Verify zero accidental mutation. - before=page.locator(".console-body").get_attribute("class") - rail.click() - assert rail.get_attribute("aria-expanded")=="true",( - width,density,"Narrow mode changed FX disclosure unexpectedly") - assert page.locator(".console-body").get_attribute("class")==before,( - width,density,"Narrow mode shifted rack/fader geometry") - else: - rail.click() - assert rail.get_attribute("aria-expanded")=="false",(width,density,"FX collapse aria broken") - rail.click() - assert rail.get_attribute("aria-expanded")=="true",(width,density,"FX expand aria broken") + # V29 has one comfort density: actual FX rail disclosure must remain + # reversible across every operator state without swapping FX slot IDs. + rail.click() + assert rail.get_attribute("aria-expanded")=="false",(width,presentation,"FX collapse aria broken") + rail.click() + assert rail.get_attribute("aria-expanded")=="true",(width,presentation,"FX expand aria broken") def check_transactions(page): root=page.locator('#tracks .strip[data-id="1"]') @@ -140,17 +132,30 @@ def main(): page=browser.new_page(viewport={"width":width,"height":height},device_scale_factor=1) errors=[];page.on("pageerror",lambda error:errors.append(str(error))) page.goto(PAGE.as_uri()) - for density in DENSITIES: - page.locator("#densitySelect").select_option(density) - if "collapsed-fx" in (page.locator(".console-body").get_attribute("class") or ""): + # Composed /preview/ deliberately has one hidden legacy density ID. + # Keep twelve real viewport/operator-state cases without resurrecting it. + assert page.locator("#densitySelect").is_hidden() + assert page.locator(".console-body").get_attribute("data-density")=="comfort" + for presentation in PRESENTATIONS: + body=page.locator(".console-body") + if presentation=="wire-folded": + if "collapsed-send" not in (body.get_attribute("class") or ""): + page.locator('.section-rail [data-section="send"]').click() + assert "collapsed-send" in (body.get_attribute("class") or "") + elif presentation=="refocused": + if "collapsed-send" in (body.get_attribute("class") or ""): + page.locator('.section-rail [data-section="send"]').click() + page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() + page.locator('#tracks .strip[data-id="1"] .strip-identity-top').click() + if "collapsed-fx" in (body.get_attribute("class") or ""): page.locator('.section-rail [data-section="fx"]').click() - check_geometry(page,width,density) - if width==1680 and density=="comfort":check_transactions(page) - page.locator("#densitySelect").select_option("comfort") + check_geometry(page,width,presentation) + if width==1680 and presentation=="default":check_transactions(page) + assert page.locator(".console-body").get_attribute("data-density")=="comfort" page.screenshot(path=f"pages-v53-fx-rail-{width}.png",full_page=True) assert not errors,(width,errors) page.close() browser.close() - print("PASS V53 dedicated grip + reversible FX reorder, visual frame and rail on 4 sizes × 3 densities") + print("PASS V53 dedicated grip + reversible FX reorder, visual frame and rail on 4 sizes × 3 operator states") if __name__=="__main__":main() \ No newline at end of file From 842db8ac7ece522ad133194c2db6c74d0a3b3549 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 13:44:19 +0700 Subject: [PATCH 171/219] test(ui): reconcile remaining public Chromium density assertions in one verified change Preserve historical source's three-density geometry testing. Restrict V18/M1 assembled /preview/ cases to the approved comfort-only presentation, and validate V45/V46 physical WIRE sockets without acting on the deliberately hidden selector. Keep actual geometry, phase, meter, gain ruler and cable regressions intact. --- tests/pages_m1_meter_gain_calibration_smoke.py | 18 ++++++++++++++---- tests/pages_micro_fader_visual_v18_smoke.py | 14 +++++++++++--- tests/pages_wire_v45_socket_layout_smoke.py | 8 ++++++-- tests/pages_wire_v46_precision_smoke.py | 8 ++++++-- 4 files changed, 37 insertions(+), 11 deletions(-) diff --git a/tests/pages_m1_meter_gain_calibration_smoke.py b/tests/pages_m1_meter_gain_calibration_smoke.py index f3904a624..ff075e657 100644 --- a/tests/pages_m1_meter_gain_calibration_smoke.py +++ b/tests/pages_m1_meter_gain_calibration_smoke.py @@ -21,7 +21,14 @@ def close(a, b, tolerance=0.65): assert abs(a - b) <= tolerance, (a, b, tolerance) def geometry(page, density, label): - page.locator("#densitySelect").select_option(density) + picker=page.locator("#densitySelect") + if picker.is_visible(): + picker.select_option(density) + else: + # Approved Pages V29 is a single comfort-only product; density + # testing still covers all three variants in the historical source. + assert density=="comfort" and picker.is_hidden() + assert page.locator(".console-body").get_attribute("data-density")=="comfort" page.wait_for_selector("#tracks .strip[data-id='1'] .fader-scale") out = page.evaluate("""() => { const strip=document.querySelector('#tracks .strip[data-id="1"]'); @@ -215,18 +222,21 @@ def main(): errors=[] page.on("pageerror",lambda exc:errors.append(str(exc))) page.goto(html.as_uri()) - for density in ("comfort","standard","compact"): + modes=("comfort","standard","compact") if label=="canonical" else ("comfort",) + for density in modes: data=geometry(page,density,label) if width==1680 and label=="pages" and density=="comfort": page.locator("#tracks .strip[data-id='1'] .fader-section").screenshot( path="m1-calibrated-fader-meter-1680.png") - if label=="pages":page.locator("#densitySelect").select_option("comfort") + if label=="pages": + assert page.locator("#densitySelect").is_hidden() + assert page.locator(".console-body").get_attribute("data-density")=="comfort" math_and_preview(page,label) assert not errors,(label,width,errors) page.close() browser.close() print("PASS M1: dBFS meter and gain rulers calibrated to physical travel; " - "preview demo displays real dBFS percentages, 3 densities × 3 sizes, source + sole approved /preview/") + "preview demo displays real dBFS, source 3 densities × 3 viewports and the approved public comfort view") if __name__=="__main__": main() diff --git a/tests/pages_micro_fader_visual_v18_smoke.py b/tests/pages_micro_fader_visual_v18_smoke.py index 1d71127d0..151567f7e 100644 --- a/tests/pages_micro_fader_visual_v18_smoke.py +++ b/tests/pages_micro_fader_visual_v18_smoke.py @@ -54,8 +54,16 @@ def check(page,path,label): # No dB scale positions or real input values change: only typography and # major/minor rendering. The two physical ruler ends match the cap travel. - for density in ("comfort","standard","compact"): - page.locator("#densitySelect").select_option(density) + # Only the historical authoring source exposes density selection. + # The shipping /preview/ has one approved comfort view, with the + # compatibility dropdown intentionally hidden (V29 operator decision). + picker=page.locator("#densitySelect") + modes=("comfort","standard","compact") if picker.is_visible() else ("comfort",) + if not picker.is_visible(): + assert picker.is_hidden() and page.locator(".console-body").get_attribute("data-density")=="comfort",label + for density in modes: + if picker.is_visible(): + picker.select_option(density) page.wait_for_selector(channel+" .gain-scale-travel") tick=page.evaluate("""(sel)=>{ const strip=document.querySelector(sel); @@ -117,7 +125,7 @@ def main(): check(page,path,label) browser.close() print("PASS V18: Material delete+phase, 17px square buttons, calibrated rulers,") - print("no label overlaps across densities, PNG preserved, source + sole approved /preview/") + print("no ruler overlaps: 3 source densities + approved public comfort, original PNG preserved") if __name__=="__main__": main() diff --git a/tests/pages_wire_v45_socket_layout_smoke.py b/tests/pages_wire_v45_socket_layout_smoke.py index 214545fad..f8bd626ad 100644 --- a/tests/pages_wire_v45_socket_layout_smoke.py +++ b/tests/pages_wire_v45_socket_layout_smoke.py @@ -105,9 +105,13 @@ def main(): p.locator('#tracks .strip[data-id="3"] .strip-identity-top').click() restored=channel_ring(dest) assert restored["arrival"]=="true" and restored["border"]==connected["border"] and restored["background"]==connected["background"],(width,"visible accepted cable must relight destination",restored) - # Compact is a spatial fallback, not a different hit-test or route state. + # The historical source supports Compact; the compiled public GUI + # deliberately hides the selector. Never simulate an unsupported mode. if width==1366: - p.locator('#densitySelect').select_option(label="Compact") + picker=p.locator('#densitySelect') + if picker.is_visible():picker.select_option(label="Compact") + else: + assert picker.is_hidden() and body.get_attribute("data-density")=="comfort" label_geometry(p,width) assert not errors,(width,errors) p.close() diff --git a/tests/pages_wire_v46_precision_smoke.py b/tests/pages_wire_v46_precision_smoke.py index fef2b0cb7..5c7442c3a 100644 --- a/tests/pages_wire_v46_precision_smoke.py +++ b/tests/pages_wire_v46_precision_smoke.py @@ -141,8 +141,12 @@ def main(): lit=incoming_colors(dest) assert lit["connected"] and lit["center"]==lit["ring"] and lit["center"]!="rgb(75, 83, 91)",(width,"focus return must restore accepted visible endpoint",lit) if width==1366: - page.locator('#densitySelect').select_option(label="Compact") - exact(center(dest_pin),center(dest),width,"compact socket no longer concentric",.32) + picker=page.locator('#densitySelect') + if picker.is_visible():picker.select_option(label="Compact") + else: + assert picker.is_hidden() + assert page.locator(".console-body").get_attribute("data-density")=="comfort" + exact(center(dest_pin),center(dest),width,"responsive socket no longer concentric",.32) assert not errors,(width,errors) page.close() browser.close() From eaa39858971d982cac803807b06a032205403cd2 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 13:53:01 +0700 Subject: [PATCH 172/219] test(ui): reconcile V7 historical geometry with approved V29 live 50:50 operator layout For the composed /preview/, exercise eight real fold/unfold states, wait for ResizeObserver layout commit, verify equal halves when expanded, readable fader/FX/WIRE, exact rail and MAIN alignment and stable EdgeId. Preserve untouched V7 fixed-height baseline checks for the source fixture. --- tests/preview_v2_v7_visual_smoke.py | 93 +++++++++++++++++++++++++++++ 1 file changed, 93 insertions(+) diff --git a/tests/preview_v2_v7_visual_smoke.py b/tests/preview_v2_v7_visual_smoke.py index cfa008edb..b5d789e6a 100644 --- a/tests/preview_v2_v7_visual_smoke.py +++ b/tests/preview_v2_v7_visual_smoke.py @@ -97,8 +97,101 @@ def audit_geometry(page, title): + +def audit_v29_operator_collapse(page, label): + """Real published V29: one comfort layout, frame-synchronized 50:50. + + Keep all eight actual operator fold combinations, not the obsolete V7 + fixed-viewport fader-height law. Legacy V7 geometry remains independently + tested by audit_p0_collapse on the unassembled authoring source. + """ + body=page.locator(".console-body") + assert page.locator("#densitySelect").is_hidden(), label + assert body.get_attribute("data-density")=="comfort", label + keys=("route","fx","send") + rail={key:page.locator(f'.section-rail [data-section="{key}"]') for key in keys} + original=tuple("collapsed-"+key in (body.get_attribute("class") or "") for key in keys) + initial_edge=page.locator('#tracks .strip[data-id="5"] .wire-node-out').get_attribute("data-wire-main-edge") + assert initial_edge, (label,"missing original MAIN EdgeId") + seen=set() + try: + for n in range(8): + target=tuple(bool(n & (1< { + const root=document.querySelector('.console-body'), + strip=document.querySelector('#tracks .strip[data-id="1"]'), + master=document.querySelector('#master .strip'), + rail=document.querySelector('.section-rail'); + const box=node=>{const b=node.getBoundingClientRect();return {top:b.top,bottom:b.bottom,height:b.height};}; + const cells=['identity','route','fx','send','pan','switch','fader','footer']; + const slot=k=>k==='identity'?'.strip-identity-top':k==='footer'?'.bottom-section':'.'+k+'-section'; + const rows=Object.fromEntries(cells.map(k=>[ + k,{strip:box(strip.querySelector(slot(k))),rail:box(rail.querySelector('.rail-cell.'+k))}])); + return {root:box(root),rows,master:box(master.querySelector('.bottom-section')), + fxList:strip.querySelector('.fxslot-list').getBoundingClientRect().height, + wireDeck:getComputedStyle(strip.querySelector('.wire-deck')).display, + wireTray:getComputedStyle(strip.querySelector('.wire-tray')).display, + wireSvg:getComputedStyle(document.querySelector('#wireLayer')).display, + sendExpanded:rail.querySelector('[data-section="send"]').getAttribute('aria-expanded'), + overflow:strip.getBoundingClientRect().bottom-box(strip.querySelector('.bottom-section')).bottom}; + }""") + rows=data["rows"] + for key,part in rows.items(): + actual,expected=part["strip"],part["rail"] + assert abs(actual["top"]-expected["top"])<=1.5 and abs(actual["bottom"]-expected["bottom"])<=1.5,( + label,status,key,"rail/channel misaligned",actual,expected) + assert rows["fader"]["strip"]["height"]>=120,(label,status,"fader below usable limit",data) + assert rows["footer"]["strip"]["height"]>=32,(label,status,"missing channel labels",data) + assert abs(data["overflow"])<=3,(label,status,"strip footer truncated",data) + assert abs(data["master"]["bottom"]-rows["footer"]["strip"]["bottom"])<=2,( + label,status,"pinned MAIN footer not aligned",data) + if target[1]: + assert rows["fx"]["strip"]["height"]>=20,(label,status,"FX fold lost rack header",data) + else: + assert data["fxList"]>=88,(label,status,"expanded FX rack cannot show inserts",data) + if target[2]: + assert rows["send"]["strip"]["height"]<=29,(label,status,"WIRE fold not compact",data) + assert data["wireDeck"]=="none" and data["wireTray"]=="none" and data["wireSvg"]=="none",( + label,status,"WIRE fold leaves painted cables",data) + assert data["sendExpanded"]=="false",(label,status,"WIRE rail fold ARIA drift") + else: + assert rows["send"]["strip"]["height"]>=100,(label,status,"expanded WIRE bay missing",data) + assert data["wireDeck"]!="none" and data["wireTray"]!="none",( + label,status,"WIRE dock unexpectedly hidden",data) + assert data["sendExpanded"]=="true",(label,status,"WIRE rail expand ARIA drift") + # For ALL expanded upper modules the native V29 50:50 split + # must be actual computed geometry, not a forced old pixel target. + if not any(target): + upper=rows["pan"]["strip"]["top"]-data["root"]["top"] + lower=rows["footer"]["strip"]["bottom"]-rows["pan"]["strip"]["top"] + assert abs(upper-lower)<=3,(label,"V29 halves must be equal",upper,lower,data) + assert page.locator('#tracks .strip[data-id="5"] .wire-node-out').get_attribute("data-wire-main-edge")==initial_edge,( + label,status,"fold changed accepted MAIN EdgeId") + finally: + for i,key in enumerate(keys): + if ("collapsed-"+key in (body.get_attribute("class") or ""))!=original[i]: + rail[key].click() + page.wait_for_timeout(60) + assert len(seen)==8,(label,"missing actual operator fold states",seen) + assert tuple("collapsed-"+key in (body.get_attribute("class") or "") for key in keys)==original,( + label,"initial fold state was not restored") + return {"states":seen} + + def audit_p0_collapse(page, label): """Every ROUTE/FX/SEND combination preserves PAN/SWITCH/FADER/FOOTER.""" + if page.locator("#densitySelect").is_hidden(): + return audit_v29_operator_collapse(page,label) result=page.evaluate("""() => { const body=document.querySelector('.console-body'); const rail=document.querySelector('.section-rail'); From f3c24c4a0a90c625db4a0510488b146fcc3d083b Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 14:19:51 +0700 Subject: [PATCH 173/219] fix(storage): add explicit verified last-known-good Show recovery Before HEAD swap, atomically preserve verified prior generation in PREVIOUS. Provide explicit recoverPrevious that verifies every referenced FX blob before changing the active pointer; never silently downgrade on ordinary load. Exercise corrupted vendor bytes, malformed HEAD/PREVIOUS and complete FX restoration. --- src/NativeShowStore.h | 71 +++++++++++++++++++++++++++----- tests/native_show_store_test.cpp | 22 +++++++++- 2 files changed, 80 insertions(+), 13 deletions(-) diff --git a/src/NativeShowStore.h b/src/NativeShowStore.h index 626069892..61fb3b1bc 100644 --- a/src/NativeShowStore.h +++ b/src/NativeShowStore.h @@ -112,21 +112,56 @@ class NativeShowStore final { const auto committed=versions.getChildFile(generation); if(committed.exists()||!stage.moveFileTo(committed)) return "Unable to publish immutable generation directory"; + // Promote the former verified HEAD into a separate durable recovery + // pointer BEFORE replacing HEAD. If power is lost at any boundary, + // the old HEAD still works or an explicit recovery candidate survives. + // PREVIOUS never changes the active Show automatically. + const auto head=showRoot.getChildFile("HEAD"); + if(head.existsAsFile()) { + if(head.getSize()<1 || head.getSize()>128) + return "Existing Show HEAD invalid: refuse to discard recovery history"; + const auto previousId=head.loadFileAsString().trim(); + if(!detail::uuid(previousId)) + return "Existing Show HEAD invalid: refuse to discard recovery history"; + ShowV2 priorShow; + std::vector priorSnapshots; + const auto priorError=readFolder( + versions.getChildFile(previousId),priorShow,priorSnapshots); + if(priorError.isNotEmpty() || !priorShow.id.equalsIgnoreCase(show.id)) + return "Existing Show generation invalid: recover explicitly before overwrite"; + const auto backupError=writePointer(showRoot.getChildFile("PREVIOUS"),previousId); + if(backupError.isNotEmpty())return "Cannot preserve prior Show HEAD: "+backupError; + } // A failed HEAD write leaves previous generation intact; a new version // may remain orphaned but will never be loaded without its HEAD. - juce::TemporaryFile temp(showRoot.getChildFile("HEAD")); - auto stream=temp.getFile().createOutputStream(); - if(!stream) return "Cannot open temporary Show pointer"; - if(!stream->writeText(generation+"\n",false,false,"\n")) - return "Cannot write temporary Show pointer"; - stream->flush(); - if(stream->getStatus().failed())return "Failed to flush Show pointer"; - stream.reset(); - if(!temp.overwriteTargetFileWithTemporary()) - return "Cannot atomically commit Show pointer"; - return {}; + return writePointer(head,generation); } + // Explicit operator-directed disaster recovery. NEVER silently substitute + // PREVIOUS on normal load: that would turn a corrupted latest performance + // into an apparently successful, but stale, recalled Show. + // Verify the entire old generation including FX hashes BEFORE switching. + // After success, existing loadWithStates() can restore every verified blob. + juce::String recoverPrevious(const juce::String& requestedId) const { + if(!detail::uuid(requestedId))return "Invalid Show ID"; + const auto dir=root_.getChildFile(requestedId.toLowerCase()); + const auto backup=dir.getChildFile("PREVIOUS"); + if(!backup.existsAsFile() || backup.getSize()<1 || backup.getSize()>128) + return "Previous Show generation missing"; + const auto priorId=backup.loadFileAsString().trim(); + if(!detail::uuid(priorId))return "Unsafe previous Show pointer"; + ShowV2 recovered; + std::vector snapshots; + const auto error=readFolder(dir.getChildFile("versions").getChildFile(priorId), + recovered,snapshots); + if(error.isNotEmpty())return "Previous Show cannot be verified: "+error; + if(!recovered.id.equalsIgnoreCase(requestedId)) + return "Previous Show identity mismatch"; + // Pointer recovery is an explicit IO transaction, not PCM publication. + return writePointer(dir.getChildFile("HEAD"),priorId); + } + + // Read-and-verify entire generation before changing either output value. // Read-and-verify entire generation before changing either output value. juce::String load(const juce::String& requestedId,ShowV2& show, std::vector& snapshots) const { @@ -198,6 +233,20 @@ class NativeShowStore final { } private: juce::File root_; + static juce::String writePointer(const juce::File& target,const juce::String& id) { + if(!detail::uuid(id))return "Unsafe Show generation pointer"; + juce::TemporaryFile temp(target); + auto output=temp.getFile().createOutputStream(); + if(!output)return "Cannot open temporary Show pointer"; + if(!output->writeText(id+"\n",false,false,"\n")) + return "Cannot write temporary Show pointer"; + output->flush(); + if(output->getStatus().failed())return "Failed to flush Show pointer"; + output.reset(); + if(!temp.overwriteTargetFileWithTemporary()) + return "Cannot atomically replace Show pointer"; + return {}; + } static bool validHash(const juce::String& s) { if(s.length()!=64) return false; for(const auto ch:s.toStdString()) diff --git a/tests/native_show_store_test.cpp b/tests/native_show_store_test.cpp index a591ad592..cbc92197e 100644 --- a/tests/native_show_store_test.cpp +++ b/tests/native_show_store_test.cpp @@ -112,13 +112,31 @@ int main() { assert(store.load(show.id,loaded,retrieved).isNotEmpty()); assert(retrieved.size()==1&&retrieved[0].name=="Performance Ready"); - // Bad HEAD rejected before using unsafe path; backup remains intact. + // Explicit recovery validates prior JSON and BOTH vendor state hashes. + // A corrupt latest blob is not silently accepted by normal load. + const auto priorPointer=workspace.getChildFile("Shows").getChildFile(show.id) + .getChildFile("PREVIOUS"); + assert(priorPointer.existsAsFile()); + assert(priorPointer.loadFileAsString().trim()==first.getFileName()); + assert(store.recoverPrevious(show.id).isEmpty()); + assert(store.currentGeneration(show.id)==first); + restoredStates.clear(); + assert(store.loadWithStates(show.id,fxShow,fxSnaps,restoredStates).isEmpty()); + assert(restoredStates.size()==2 && fxSnaps[0].name=="Soundcheck"); + + // Bad HEAD rejected before using unsafe path; recovery must remain possible. auto head=workspace.getChildFile("Shows").getChildFile(show.id).getChildFile("HEAD"); assert(head.replaceWithText("../unsafe")); assert(store.load(show.id,loaded,retrieved).isNotEmpty()); assert(store.currentGeneration(show.id)==juce::File{}); assert(first.isDirectory()); + assert(store.recoverPrevious(show.id).isEmpty()); + assert(store.currentGeneration(show.id)==first); + // Corrupt PREVIOUS must never clobber the last accepted HEAD. + assert(priorPointer.replaceWithText("../../outside")); + assert(store.recoverPrevious(show.id).isNotEmpty()); + assert(store.currentGeneration(show.id)==first); base.deleteRecursively(); - std::cout<<"PASS: immutable Shows generation, staged VST3 hash, atomic HEAD, no partial recovery\n"; + std::cout<<"PASS: immutable Shows, staged VST3 hashes, explicit last-known-good recovery\n"; return 0; } From 83f6826482cc422b1698daec8f08bb1dfba40876 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 14:20:24 +0700 Subject: [PATCH 174/219] style(storage): keep explicit recovery API comment singular --- src/NativeShowStore.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/NativeShowStore.h b/src/NativeShowStore.h index 61fb3b1bc..bdc158a04 100644 --- a/src/NativeShowStore.h +++ b/src/NativeShowStore.h @@ -161,7 +161,6 @@ class NativeShowStore final { return writePointer(dir.getChildFile("HEAD"),priorId); } - // Read-and-verify entire generation before changing either output value. // Read-and-verify entire generation before changing either output value. juce::String load(const juce::String& requestedId,ShowV2& show, std::vector& snapshots) const { From 660f2eff4c86a23b3b8be992ec29ddc4b175112c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 14:33:03 +0700 Subject: [PATCH 175/219] feat(shows): expose verified Show lifecycle and safe last-good recovery in approved native mixer --- src/Main.cpp | 47 +++++++++++++ src/NativeShowSaveWorker.h | 52 ++++++++++---- src/NativeShowStore.h | 51 ++++++++++---- tests/native_show_store_test.cpp | 13 ++++ web/approved-native-bridge.js | 115 ++++++++++++++++++++++++++++++- 5 files changed, 252 insertions(+), 26 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index a45b19cf4..904965488 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2688,6 +2688,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr auto row=std::make_unique(); row->setProperty("id",item.id); row->setProperty("name",item.name); + row->setProperty("needsRecovery",item.needsRecovery); + row->setProperty("hasPrevious",item.hasPrevious); items.add(juce::var(row.release())); } ack->setProperty("items",juce::var(items)); @@ -2701,6 +2703,51 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr nativeShowBusy_=true; return; } + // Explicit recovery repairs only a damaged disk HEAD, never auto- + // recalls/arms audio and never overwrites a verified current Show. + if (action == "routingDryShowRecover") + { + const auto id=value.toString(); + const auto reject=[this](const juce::String& error) { + if(browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("ok",false); + ack->setProperty("error",error); + browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowRecoverAck",juce::var(ack.release())); + } + emitNotice("Show recovery unchanged: "+error,true); + }; + if(!armix::shows::detail::uuid(id)) + return reject("Select a valid saved Show identity."); + if(nativeShowBusy_||studioBackupBusy_||catalog_.busy()|| + engine_.isGraphSwitchPending()||!engine_.allOutputsDisarmed()) + return reject("MUTE both outputs and finish all Studio tasks before recovery."); + auto safe=juce::Component::SafePointer(this); + const bool started=nativeShowWorker_.recover(settingsDirectory(),id, + [safe](armix::shows::NativeShowSaveWorker::Result result) { + if(safe==nullptr)return; + safe->nativeShowBusy_=false; + if(result.ok()) + safe->diagnostics_.record("NATIVE_SHOW_LKG_RECOVERED",result.showId); + else safe->diagnostics_.record("NATIVE_SHOW_LKG_REJECTED",result.error); + if(safe->browser_.loaded) { + auto ack=std::make_unique(); + ack->setProperty("ok",result.ok()); + ack->setProperty("error",result.error); + ack->setProperty("showId",result.showId); + safe->browser_.emitEventIfBrowserIsVisible( + "arMixNativeShowRecoverAck",juce::var(ack.release())); + } + if(result.ok()) + safe->emitNotice("Last verified Show restored on disk. OUTPUT stays MUTED; review and RECALL explicitly."); + else + safe->emitNotice("Last-good Show recovery rejected: "+result.error,true); + }); + if(!started)return reject("Cannot start Show recovery IO worker."); + nativeShowBusy_=true; + return; + } if (action == "routingDryShowRecall") { const auto id=value.toString(); diff --git a/src/NativeShowSaveWorker.h b/src/NativeShowSaveWorker.h index f568003d2..773cde31e 100644 --- a/src/NativeShowSaveWorker.h +++ b/src/NativeShowSaveWorker.h @@ -16,10 +16,11 @@ namespace armix::shows { class NativeShowSaveWorker final : private juce::Thread { public: - enum class Operation { save, list, read }; + enum class Operation { save, list, read, recover }; struct Summary { juce::String id,name; juce::int64 modifiedMs=0; + bool needsRecovery=false,hasPrevious=false; }; struct Result { Operation operation=Operation::save; @@ -57,6 +58,14 @@ class NativeShowSaveWorker final : private juce::Thread { return false; return startOrRelease(); } + // Explicit recovery runs only on this serialized storage worker. + bool recover(juce::File studio,juce::String showId,Completion completion) { + if(!detail::uuid(showId)|| + !reserve(Operation::recover,std::move(studio),std::move(completion))) + return false; + requestedId_=std::move(showId); + return startOrRelease(); + } bool read(juce::File studio,juce::String showId, juce::int64 epoch,juce::int64 revision,Completion completion) { if(!detail::uuid(showId)||epoch<=0||revision<=0 || @@ -99,7 +108,8 @@ class NativeShowSaveWorker final : private juce::Thread { try { NativeShowStore store(studio_); if(operation_==Operation::save)save(store,result); - else if(operation_==Operation::list)listShows(result); + else if(operation_==Operation::list)listShows(store,result); + else if(operation_==Operation::recover)recoverShow(store,result); else readShow(store,result); } catch(const std::exception& e) { result.error="Native Show IO exception: "+juce::String(e.what()); @@ -144,7 +154,7 @@ class NativeShowSaveWorker final : private juce::Thread { } // Lightweight bounded metadata listing. Full data+SHA verification is // performed again by NativeShowStore::load before any recall can apply. - void listShows(Result& result) { + void listShows(NativeShowStore& store,Result& result) { const auto root=studio_.getChildFile("Shows"); if(!root.isDirectory())return; juce::DirectoryIterator iter(root,false,"*",juce::File::findDirectories); @@ -157,17 +167,26 @@ class NativeShowSaveWorker final : private juce::Thread { const auto folder=iter.getFile(); const auto id=folder.getFileName(); if(!detail::uuid(id))continue; + const bool hasPrevious=folder.getChildFile("PREVIOUS").existsAsFile(); const auto head=folder.getChildFile("HEAD"); - if(!head.existsAsFile()||head.getSize()>128)continue; - const auto version=head.loadFileAsString().trim(); - if(!detail::uuid(version))continue; - const auto meta=folder.getChildFile("versions") - .getChildFile(version).getChildFile("show.json"); - if(!meta.existsAsFile()||meta.getSize()>maxJsonBytes)continue; + juce::String version; + if(head.existsAsFile()&&head.getSize()>0&&head.getSize()<=128) + version=head.loadFileAsString().trim(); + const auto meta=detail::uuid(version) + ?folder.getChildFile("versions").getChildFile(version).getChildFile("show.json") + :juce::File{}; ShowV2 show; - if(!Codec::decode(meta.loadFileAsString(),show) || - !show.id.equalsIgnoreCase(id)||show.snapshotOrder.empty())continue; - result.items.push_back({show.id,show.name,show.modifiedMs}); + if(meta.existsAsFile()&&meta.getSize()>0&&meta.getSize()<=maxJsonBytes&& + Codec::decode(meta.loadFileAsString(),show)&& + show.id.equalsIgnoreCase(id)&&!show.snapshotOrder.empty()) { + result.items.push_back({show.id,show.name,show.modifiedMs,false,hasPrevious}); + } else if(hasPrevious) { + // A damaged HEAD must not make a verified prior Show invisible. + std::vector verified; + if(store.loadPrevious(id,show,verified).isEmpty() && + !show.snapshotOrder.empty()) + result.items.push_back({show.id,show.name,show.modifiedMs,true,true}); + } } std::sort(result.items.begin(),result.items.end(), [](const Summary& a,const Summary& b) { @@ -176,6 +195,15 @@ class NativeShowSaveWorker final : private juce::Thread { }); if(result.items.size()>64)result.items.resize(64); } + void recoverShow(NativeShowStore& store,Result& result) { + result.showId=requestedId_; + result.error=store.recoverPrevious(requestedId_); + if(result.error.isNotEmpty())return; + ShowV2 verified; + std::vector checked; + result.error=store.load(requestedId_,verified,checked); + if(result.error.isEmpty())result.name=verified.name; + } void readShow(NativeShowStore& store,Result& result) { result.showId=requestedId_; ShowV2 show; diff --git a/src/NativeShowStore.h b/src/NativeShowStore.h index bdc158a04..494d1dd39 100644 --- a/src/NativeShowStore.h +++ b/src/NativeShowStore.h @@ -137,6 +137,32 @@ class NativeShowStore final { return writePointer(head,generation); } + // Read-only last-known-good inspection. Verify the complete previous + // generation, including each vendor blob, before exposing its metadata. + // A corrupt HEAD must never force recovery or change the accepted graph. + juce::String loadPrevious(const juce::String& requestedId,ShowV2& show, + std::vector& snapshots, + juce::String* generation=nullptr) const { + if(!detail::uuid(requestedId))return "Invalid Show ID"; + const auto dir=root_.getChildFile(requestedId.toLowerCase()); + const auto pointer=dir.getChildFile("PREVIOUS"); + if(!pointer.existsAsFile()||pointer.getSize()<1||pointer.getSize()>128) + return "Previous Show generation missing"; + const auto id=pointer.loadFileAsString().trim(); + if(!detail::uuid(id))return "Unsafe previous Show pointer"; + ShowV2 candidate; + std::vector items; + const auto error=readFolder(dir.getChildFile("versions").getChildFile(id), + candidate,items); + if(error.isNotEmpty())return "Previous Show cannot be verified: "+error; + if(!candidate.id.equalsIgnoreCase(requestedId)) + return "Previous Show identity mismatch"; + show=std::move(candidate); + snapshots=std::move(items); + if(generation)*generation=id; + return {}; + } + // Explicit operator-directed disaster recovery. NEVER silently substitute // PREVIOUS on normal load: that would turn a corrupted latest performance // into an apparently successful, but stale, recalled Show. @@ -144,21 +170,20 @@ class NativeShowStore final { // After success, existing loadWithStates() can restore every verified blob. juce::String recoverPrevious(const juce::String& requestedId) const { if(!detail::uuid(requestedId))return "Invalid Show ID"; - const auto dir=root_.getChildFile(requestedId.toLowerCase()); - const auto backup=dir.getChildFile("PREVIOUS"); - if(!backup.existsAsFile() || backup.getSize()<1 || backup.getSize()>128) - return "Previous Show generation missing"; - const auto priorId=backup.loadFileAsString().trim(); - if(!detail::uuid(priorId))return "Unsafe previous Show pointer"; + // A valid current performance must never be overwritten with an + // older one merely because a recovery pointer exists. + ShowV2 current; + std::vector currentSnapshots; + if(load(requestedId,current,currentSnapshots).isEmpty()) + return "Current Show is verified: refusing to overwrite working performance"; + juce::String priorId; ShowV2 recovered; std::vector snapshots; - const auto error=readFolder(dir.getChildFile("versions").getChildFile(priorId), - recovered,snapshots); - if(error.isNotEmpty())return "Previous Show cannot be verified: "+error; - if(!recovered.id.equalsIgnoreCase(requestedId)) - return "Previous Show identity mismatch"; - // Pointer recovery is an explicit IO transaction, not PCM publication. - return writePointer(dir.getChildFile("HEAD"),priorId); + const auto error=loadPrevious(requestedId,recovered,snapshots,&priorId); + if(error.isNotEmpty())return error; + // Pointer repair is an explicit IO transaction, never PCM publication. + return writePointer(root_.getChildFile(requestedId.toLowerCase()) + .getChildFile("HEAD"),priorId); } // Read-and-verify entire generation before changing either output value. diff --git a/tests/native_show_store_test.cpp b/tests/native_show_store_test.cpp index cbc92197e..007837504 100644 --- a/tests/native_show_store_test.cpp +++ b/tests/native_show_store_test.cpp @@ -106,12 +106,25 @@ int main() { assert(store.load(show.id,loaded,retrieved).isEmpty()); assert(retrieved[0].name=="Performance Ready"); + // A valid current performance cannot be overwritten with older recovery. + assert(store.recoverPrevious(show.id).isNotEmpty()); + assert(store.currentGeneration(show.id)==second); + ShowV2 previousShow;std::vector previousItems; + juce::String previousGeneration; + assert(store.loadPrevious(show.id,previousShow,previousItems,&previousGeneration).isEmpty()); + assert(previousGeneration==first.getFileName()); + assert(previousItems.size()==1 && previousItems[0].name=="Soundcheck"); + // Missing/corrupt payload never partially replaces the accepted outputs. const auto vendor=second.getChildFile("blobs").getChildFile(blob.sha256+".bin"); assert(vendor.appendText("damaged")); assert(store.load(show.id,loaded,retrieved).isNotEmpty()); assert(retrieved.size()==1&&retrieved[0].name=="Performance Ready"); + // Read-only recovery inspection never mutates HEAD even after blob corruption. + assert(store.loadPrevious(show.id,previousShow,previousItems).isEmpty()); + assert(store.currentGeneration(show.id)==second); + // Explicit recovery validates prior JSON and BOTH vendor state hashes. // A corrupt latest blob is not silently accepted by normal load. const auto priorPointer=workspace.getChildFile("Shows").getChildFile(show.id) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 86aeb3c01..7bb8d7627 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1648,8 +1648,121 @@ if(Number.isFinite(bytes)&&bytes>0) nativeToast("Audio report copied · paste into engineering chat"); }); + // Native-only access to EXISTING JUCE Show storage, not browser scenes. + // ShowV2 is 10CH+4AUX; unsupported dynamic WIRE/GROUP is rejected by + // native capture rather than silently truncated. + const showHeading=item("span","more-tools-caption","STUDIO / VERIFIED SHOWS"); + const showSave=item("button","tool","Save Show"); + const showBrowse=item("button","tool","Browse Shows"); + const showSelect=item("select","toolbar-select",""); + const showRecall=item("button","tool","Recall Show"); + const showRecover=item("button","tool","Recover Last Good"); + const showNote=item("span","more-tools-caption", + "Verified Shows only · full dynamic-session autosave is not yet available"); + showNote.style.whiteSpace="normal"; + showSelect.setAttribute("aria-label","Saved native Show"); + showSelect.style.maxWidth="210px";showSelect.style.fontSize="11px"; + showSelect.hidden=true;showRecall.hidden=true;showRecover.hidden=true; + const showUuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; + let showBusy=false; + const showEntries=new Map(); + const showOption=(name,value)=>{ + const option=document.createElement("option"); + option.textContent=name;option.value=value;return option; + }; + function showControls(){ + const entry=showEntries.get(showSelect.value); + const muted=hardware?.device?.outputArmed===false && + hardware?.raw?.monitor!==true; + showSave.disabled=showBusy; + showBrowse.disabled=showBusy; + showRecall.disabled=showBusy||!muted||!entry||entry.needsRecovery; + showRecover.disabled=showBusy||!muted||!entry||!entry.hasPrevious; + } + function showRefresh(){ + showBusy=true;showControls(); + showNote.textContent="Browsing verified native Shows…"; + backend.emitEvent("arMixAction",{action:"routingDryShowList"}); + } + showSave.addEventListener("click",()=>{ + if(showBusy)return; + if(hardware?.device?.outputArmed!==false||hardware?.raw?.monitor===true){ + status("SHOW SAVE requires MUTED output");return; + } + showBusy=true;showControls(); + showNote.textContent="Capturing accepted routing and VST3 state…"; + backend.emitEvent("arMixAction",{action:"routingDryShowSave"}); + }); + showBrowse.addEventListener("click",()=>{if(!showBusy)showRefresh();}); + showSelect.addEventListener("change",showControls); + showRecall.addEventListener("click",()=>{ + const id=showSelect.value,entry=showEntries.get(id); + if(showBusy||!entry||entry.needsRecovery||!showUuid.test(id)|| + hardware?.device?.outputArmed!==false)return; + showBusy=true;showControls(); + showNote.textContent="Verifying Show / preparing native FX · output stays MUTED…"; + backend.emitEvent("arMixAction",{action:"routingDryShowRecall",value:id}); + }); + showRecover.addEventListener("click",()=>{ + const id=showSelect.value,entry=showEntries.get(id); + if(showBusy||!entry?.hasPrevious||!showUuid.test(id)|| + hardware?.device?.outputArmed!==false)return; + showBusy=true;showControls(); + showNote.textContent="Verifying previous generation · valid latest will NOT be overwritten…"; + backend.emitEvent("arMixAction",{action:"routingDryShowRecover",value:id}); + }); + backend.addEventListener("arMixNativeShowSaveAck",ack=>{ + showBusy=false;showControls(); + if(ack?.ok===true){ + status("SHOW SAVED · native verified state · OUTPUT MUTED"); + showRefresh(); + }else{ + showNote.textContent="Save rejected: "+String(ack?.error||"Native capture rejected"); + status(showNote.textContent); + } + }); + backend.addEventListener("arMixNativeShowListAck",ack=>{ + showBusy=false;showEntries.clear(); + showSelect.replaceChildren(showOption("Choose verified Show…","")); + if(ack?.ok===true&&Array.isArray(ack.items)){ + for(const entry of ack.items.slice(0,64)){ + if(!showUuid.test(entry?.id))continue; + showEntries.set(entry.id,{ + hasPrevious:entry.hasPrevious===true, + needsRecovery:entry.needsRecovery===true + }); + showSelect.append(showOption( + String(entry.name||"Saved Show")+(entry.needsRecovery?" · RECOVERY":""), + entry.id)); + } + } + showSelect.hidden=false;showRecall.hidden=false;showRecover.hidden=false; + showNote.textContent=ack?.ok===true + ?showEntries.size+" saved Shows · mute output before recall/recovery" + :"Browse rejected: "+String(ack?.error||"Native storage unavailable"); + showControls(); + }); + backend.addEventListener("arMixNativeShowRecallAck",ack=>{ + showBusy=false;showControls(); + showNote.textContent=ack?.ok===true + ?"SHOW RESTORED · OUTPUT MUTED; verify physical pins before MONITOR ON" + :"Recall rejected: "+String(ack?.error||"Native route unchanged"); + if(ack?.ok===true)controller?.subscribe(); + status(showNote.textContent); + }); + backend.addEventListener("arMixNativeShowRecoverAck",ack=>{ + showBusy=false;showControls(); + if(ack?.ok===true){ + status("Last verified Show restored on disk · muted; recall explicitly"); + showRefresh(); + }else{ + showNote.textContent="Recovery rejected: "+String(ack?.error||"Previous generation invalid"); + status(showNote.textContent); + } + }); menu.append(caption,setup,muteBtn,hardwareNote, - healthTitle,mark,report,advanced); + healthTitle,mark,report,advanced, + showHeading,showSave,showBrowse,showSelect,showRecall,showRecover,showNote); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. const toolbar=document.querySelector(".command-bar"); From ceb3e92606dd49f357326252bd226a63800f291f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 14:35:24 +0700 Subject: [PATCH 176/219] test(ui): exercise approved native Save/Recall/Last Good Show IO and muted safety --- tests/approved_native_cold_start_smoke.py | 48 +++++++++++++++++++++++ 1 file changed, 48 insertions(+) diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index c16dfcffd..9a970f4b2 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -45,6 +45,54 @@ def main(): g0['mixerSession']={'authority':'NONE','deviceEpoch':g0['device']['epoch'],'channels':[]} g0['legacyM4']={'active':True,'routeAccepted':False,'routingRevision':'1'} emit(page,'arMixConsoleSnapshot',g0) + # Native-only Studio controls must use real JUCE Show I/O; the + # public Pages scene model must never acknowledge a persisted Show. + show_panel = "#moreTools .more-tools-panel" + show_id = "11111111-2222-4333-8444-555555555555" + corrupt_id = "aaaaaaaa-bbbb-4ccc-8ddd-eeeeeeeeeeee" + def show_click(text): + page.evaluate("""([selector,text])=>{ + const buttons=[...document.querySelectorAll(selector+' button')]; + const button=buttons.find(b=>b.textContent===text); + if(!button)throw Error('Missing native Show button: '+text); + button.click(); + }""",[show_panel,text]) + def show_select(value): + return page.evaluate("""([selector,value])=>{ + const node=document.querySelector(selector+' select[aria-label="Saved native Show"]'); + if(!node)throw Error('Native Show selector absent'); + node.value=value;node.dispatchEvent(new Event('change')); + const buttons=[...document.querySelectorAll(selector+' button')]; + const available=name=>buttons.find(b=>b.textContent===name)?.disabled===false; + return {recall:available('Recall Show'),recover:available('Recover Last Good')}; + }""",[show_panel,value]) + show_click("Browse Shows") + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ + {"id":show_id,"name":"Valid Performance","hasPrevious":True,"needsRecovery":False}, + {"id":corrupt_id,"name":"Damaged HEAD","hasPrevious":True,"needsRecovery":True}]}) + assert show_select(show_id)=={"recall":True,"recover":True} + assert show_select(corrupt_id)=={"recall":False,"recover":True} + show_click("Recover Last Good") + recovery=page.evaluate("()=>window.__events.at(-1).payload") + assert recovery=={"action":"routingDryShowRecover","value":corrupt_id} + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") + emit(page,"arMixNativeShowRecoverAck",{"ok":True,"showId":corrupt_id}) + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ + {"id":corrupt_id,"name":"Recovered Performance","hasPrevious":True,"needsRecovery":False}]}) + assert show_select(corrupt_id)["recall"] is True + show_click("Recall Show") + recalled=page.evaluate("()=>window.__events.at(-1).payload") + assert recalled=={"action":"routingDryShowRecall","value":corrupt_id} + emit(page,"arMixNativeShowRecallAck",{"ok":False,"error":"DEVICE_REBIND_REQUIRED"}) + assert "DEVICE_REBIND_REQUIRED" in page.locator(show_panel).inner_text() + show_click("Save Show") + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowSave" + emit(page,"arMixNativeShowSaveAck",{"ok":True,"showId":show_id}) + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[]}) + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") if 'collapsed-send' in (page.locator('.console-body').get_attribute('class') or ''): page.locator('.section-rail [data-section="send"]').click() # Release before bootstrap SOURCE's later native readback arrives. From f4cc0b4d097a85e14ccdc189adbd8b77e4208804 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 14:39:33 +0700 Subject: [PATCH 177/219] test(ui): inspect native Show status in collapsed More panel without visibility-dependent innerText --- tests/approved_native_cold_start_smoke.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 9a970f4b2..04ec5f1a5 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -86,7 +86,7 @@ def show_select(value): recalled=page.evaluate("()=>window.__events.at(-1).payload") assert recalled=={"action":"routingDryShowRecall","value":corrupt_id} emit(page,"arMixNativeShowRecallAck",{"ok":False,"error":"DEVICE_REBIND_REQUIRED"}) - assert "DEVICE_REBIND_REQUIRED" in page.locator(show_panel).inner_text() + assert "DEVICE_REBIND_REQUIRED" in page.locator(show_panel).text_content() show_click("Save Show") assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowSave" emit(page,"arMixNativeShowSaveAck",{"ok":True,"showId":show_id}) From 734dc8ce8a7252969f28a495a95d478ee57381df Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 14:41:20 +0700 Subject: [PATCH 178/219] feat(shows): save a new verified generation of selected Show, retaining previous VST state --- src/Main.cpp | 5 +++- src/NativeShowSaveWorker.h | 29 ++++++++++++++++++----- tests/approved_native_cold_start_smoke.py | 7 ++++++ web/approved-native-bridge.js | 18 +++++++++++--- 4 files changed, 49 insertions(+), 10 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 904965488..2c331a9a0 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -2552,6 +2552,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } if (action == "routingDryShowSave") { + const auto updateShowId=value.isString()?value.toString():juce::String(); const auto reject=[this](const juce::String& reason) { if(browser_.loaded) { auto ack=std::make_unique(); @@ -2562,6 +2563,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr } emitNotice("Show not saved: "+reason,true); }; + if(updateShowId.isNotEmpty()&&!armix::shows::detail::uuid(updateShowId)) + return reject("Invalid Show identity for version update."); if (nativeShowBusy_ || studioBackupBusy_ || catalog_.busy() || engine_.isGraphSwitchPending() || engine_.hasTemporaryDiagnosticDevice()) return reject("Finish the current Studio task before capturing a native Show."); @@ -2656,7 +2659,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr safe->browser_.emitEventIfBrowserIsVisible("arMixNativeShowSaveAck", juce::var(ack.release())); } - }); + },updateShowId); if(!started)return reject("Native Show worker is busy. No session was modified."); nativeShowBusy_=true; return emitNotice("Saving ACK-verified routing and binary VST3 state on the Show IO worker."); diff --git a/src/NativeShowSaveWorker.h b/src/NativeShowSaveWorker.h index 773cde31e..4465c5823 100644 --- a/src/NativeShowSaveWorker.h +++ b/src/NativeShowSaveWorker.h @@ -43,14 +43,17 @@ class NativeShowSaveWorker final : private juce::Thread { std::move(completion)); } bool launch(juce::File studio,SnapshotV2 snapshot, - std::vector binaryStates,Completion completion) { + std::vector binaryStates,Completion completion, + juce::String updateShowId={}) { // Reject invalid requests BEFORE reserving or retaining a potentially // large vendor-state payload on this long-lived worker. if(!detail::uuid(snapshot.id) || + (updateShowId.isNotEmpty()&&!detail::uuid(updateShowId)) || !reserve(Operation::save,std::move(studio),std::move(completion))) return false; snapshot_=std::move(snapshot); blobs_=std::move(binaryStates); + updateShowId_=std::move(updateShowId); return startOrRelease(); } bool list(juce::File studio,Completion completion) { @@ -90,6 +93,7 @@ class NativeShowSaveWorker final : private juce::Thread { blobs_.clear(); blobs_.shrink_to_fit(); requestedId_={}; + updateShowId_={}; requestEpoch_=0;requestRevision_=0; studio_={}; finished_={}; @@ -132,15 +136,27 @@ class NativeShowSaveWorker final : private juce::Thread { } void save(NativeShowStore& store,Result& result) { result.snapshotId=snapshot_.id; - result.name=snapshot_.name; ShowV2 show; - show.id=juce::Uuid().toDashedString().toLowerCase(); - show.name=snapshot_.name; - show.createdMs=snapshot_.createdMs; - show.modifiedMs=snapshot_.modifiedMs; + if(updateShowId_.isNotEmpty()) { + // Verify every byte of the existing Show before introducing a + // replacement generation. Never overwrite damaged or stale work. + std::vector verifiedOld; + result.error=store.load(updateShowId_,show,verifiedOld); + if(result.error.isNotEmpty())return; + // The old snapshot remains immutable in PREVIOUS; only the + // current head gets the new accepted performance snapshot. + show.snapshotOrder.clear(); + show.modifiedMs=juce::jmax(show.modifiedMs+1,snapshot_.modifiedMs); + } else { + show.id=juce::Uuid().toDashedString().toLowerCase(); + show.name=snapshot_.name; + show.createdMs=snapshot_.createdMs; + show.modifiedMs=snapshot_.modifiedMs; + } show.currentSnapshotId=snapshot_.id; show.snapshotOrder.push_back(snapshot_.id); result.showId=show.id; + result.name=show.name; result.error=store.commit(show,{snapshot_},blobs_); if(result.error.isNotEmpty())return; ShowV2 verified; @@ -228,6 +244,7 @@ class NativeShowSaveWorker final : private juce::Thread { SnapshotV2 snapshot_; std::vector blobs_; // captured on CONTROL, hashed/written on IO worker juce::String requestedId_; + juce::String updateShowId_; // target of an EXPLICIT user version save juce::int64 requestEpoch_=0,requestRevision_=0; Completion finished_; std::shared_ptr> alive_= diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 04ec5f1a5..a7619b11a 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -87,6 +87,13 @@ def show_select(value): assert recalled=={"action":"routingDryShowRecall","value":corrupt_id} emit(page,"arMixNativeShowRecallAck",{"ok":False,"error":"DEVICE_REBIND_REQUIRED"}) assert "DEVICE_REBIND_REQUIRED" in page.locator(show_panel).text_content() + show_click("Save New Version") + assert page.evaluate("()=>window.__events.at(-1).payload")=={ + "action":"routingDryShowSave","value":corrupt_id} + emit(page,"arMixNativeShowSaveAck",{"ok":True,"showId":corrupt_id}) + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" + emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ + {"id":corrupt_id,"name":"Recovered Performance","hasPrevious":True,"needsRecovery":False}]}) show_click("Save Show") assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowSave" emit(page,"arMixNativeShowSaveAck",{"ok":True,"showId":show_id}) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 7bb8d7627..a6b426f32 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1653,6 +1653,7 @@ // native capture rather than silently truncated. const showHeading=item("span","more-tools-caption","STUDIO / VERIFIED SHOWS"); const showSave=item("button","tool","Save Show"); + const showUpdate=item("button","tool","Save New Version"); const showBrowse=item("button","tool","Browse Shows"); const showSelect=item("select","toolbar-select",""); const showRecall=item("button","tool","Recall Show"); @@ -1662,7 +1663,8 @@ showNote.style.whiteSpace="normal"; showSelect.setAttribute("aria-label","Saved native Show"); showSelect.style.maxWidth="210px";showSelect.style.fontSize="11px"; - showSelect.hidden=true;showRecall.hidden=true;showRecover.hidden=true; + showSelect.hidden=true;showUpdate.hidden=true; + showRecall.hidden=true;showRecover.hidden=true; const showUuid=/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i; let showBusy=false; const showEntries=new Map(); @@ -1676,6 +1678,7 @@ hardware?.raw?.monitor!==true; showSave.disabled=showBusy; showBrowse.disabled=showBusy; + showUpdate.disabled=showBusy||!muted||!entry||entry.needsRecovery; showRecall.disabled=showBusy||!muted||!entry||entry.needsRecovery; showRecover.disabled=showBusy||!muted||!entry||!entry.hasPrevious; } @@ -1693,6 +1696,14 @@ showNote.textContent="Capturing accepted routing and VST3 state…"; backend.emitEvent("arMixAction",{action:"routingDryShowSave"}); }); + showUpdate.addEventListener("click",()=>{ + const id=showSelect.value,entry=showEntries.get(id); + if(showBusy||!entry||entry.needsRecovery||!showUuid.test(id)|| + hardware?.device?.outputArmed!==false)return; + showBusy=true;showControls(); + showNote.textContent="Saving verified next generation · previous Show retained…"; + backend.emitEvent("arMixAction",{action:"routingDryShowSave",value:id}); + }); showBrowse.addEventListener("click",()=>{if(!showBusy)showRefresh();}); showSelect.addEventListener("change",showControls); showRecall.addEventListener("click",()=>{ @@ -1736,7 +1747,8 @@ entry.id)); } } - showSelect.hidden=false;showRecall.hidden=false;showRecover.hidden=false; + showSelect.hidden=false;showUpdate.hidden=false; + showRecall.hidden=false;showRecover.hidden=false; showNote.textContent=ack?.ok===true ?showEntries.size+" saved Shows · mute output before recall/recovery" :"Browse rejected: "+String(ack?.error||"Native storage unavailable"); @@ -1762,7 +1774,7 @@ }); menu.append(caption,setup,muteBtn,hardwareNote, healthTitle,mark,report,advanced, - showHeading,showSave,showBrowse,showSelect,showRecall,showRecover,showNote); + showHeading,showSave,showBrowse,showSelect,showUpdate,showRecall,showRecover,showNote); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. const toolbar=document.querySelector(".command-bar"); From 5d7ee3fb95b6ceccc27815fb742675604daa0539 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:06:59 +0700 Subject: [PATCH 179/219] feat(session): exact stable ChannelId/EdgeId snapshot import and typed mixer document codec --- engine/core/DynamicChannelRoster.h | 50 +++++ src/NativeMixerSessionDocument.h | 345 +++++++++++++++++++++++++++++ 2 files changed, 395 insertions(+) create mode 100644 src/NativeMixerSessionDocument.h diff --git a/engine/core/DynamicChannelRoster.h b/engine/core/DynamicChannelRoster.h index 10b3e526e..70113e091 100644 --- a/engine/core/DynamicChannelRoster.h +++ b/engine/core/DynamicChannelRoster.h @@ -682,6 +682,56 @@ class DynamicChannelRoster final { return result; } + // Restore stable native ChannelIds and EdgeIds without replaying CREATE, + // which would invent new identities, reorder wires and break external FX. + // CONTROL ONLY; no audio is ever published by this operation. + bool restoreExact(std::uint64_t restoredRevision, + std::span entries) { + if(restoredRevision==0 || entries.empty() || + !withinBudget(std::vector(entries.begin(),entries.end()))) + return false; + std::unordered_set ids,edges; + std::uint64_t maxId=0,maxEdge=0; + int mains=0,monitors=0; + for(const auto& ch:entries) { + if(!ch.id.value || ch.id.value==std::numeric_limits::max() || + !ids.insert(ch.id.value).second || + !std::isfinite(ch.faderLinear) || ch.faderLinear<0.f || + ch.faderLinear>4.f || !std::isfinite(ch.pan) || + ch.pan< -1.f || ch.pan>1.f)return false; + maxId=std::max(maxId,ch.id.value); + mains+=ch.role==ChannelRole::main; + monitors+=ch.role==ChannelRole::monitor; + int primary=0; + for(const auto& send:ch.sends) { + if(!send.edgeId || + send.edgeId==std::numeric_limits::max() || + !send.destination.value || send.destination==ch.id || + !edges.insert(send.edgeId).second || + !std::isfinite(send.gain)||send.gain<0.f||send.gain>4.f || + !std::isfinite(send.pan)||send.pan< -1.f||send.pan>1.f) + return false; + primary+=send.primaryOutput; + maxEdge=std::max(maxEdge,send.edgeId); + } + if(primary>1 || (ch.role==ChannelRole::main && !ch.sends.empty()) || + (ch.role==ChannelRole::monitor && !ch.sends.empty()))return false; + } + if(mains!=1||monitors>1)return false; + for(const auto& ch:entries) + for(const auto& send:ch.sends) + if(ids.count(send.destination.value)==0)return false; + auto candidate=std::vector(entries.begin(),entries.end()); + auto index=buildIndex(candidate); + if(index.size()!=candidate.size())return false; + channels_.swap(candidate); + index_.swap(index); + revision_=restoredRevision; + nextId_=maxId+1; + nextEdgeId_=maxEdge+1; + return true; + } + private: static bool assignMissingEdgeIds( std::vector& rows,std::uint64_t& next) { diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h new file mode 100644 index 000000000..5ded49b17 --- /dev/null +++ b/src/NativeMixerSessionDocument.h @@ -0,0 +1,345 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "../engine/core/UnifiedLegacyProductionAdmission.h" +#include "NativeShowStore.h" +#include +#include +#include +#include +#include +#include + +// The logical session and its hardware binding are deliberately separate. +// This is a DOCUMENT, not another graph, DSP engine or audio callback. +// All validation/conversion occurs on the JUCE CONTROL / I/O threads. +namespace armix::session { +using namespace armix::mixer; + +struct HardwareBinding final { + juce::String backend,capture,playback,inputMask,outputMask; + double rate=0.; + int frames=0; +}; +struct StoredInsert final { + ChannelId channel{}; + std::size_t slot=0; + juce::String catalogId,path,sha256,name; + int uid=0; + bool bypass=false; +}; +struct MixerSessionDocument final { + juce::String id; + DynamicChannelRoster roster{ChannelRosterBudget{ + 32u*1024u*1024u,8u,static_cast(maxChannelSends+maxAuxSends+2)}}; + DynamicGraphRequest request{}; + LegacyChannelIds legacyIds{}; + VerifiedNativeOutputs outputs{}; + HardwareBinding binding{}; + std::vector inserts; + std::vector rackBypassed; + float masterGain=1.f; + bool masterMute=false,masterMono=false; + std::uint64_t acceptedRevision=0; + juce::int64 savedMs=0; +}; +inline juce::String decimal(std::uint64_t value) { + return juce::String(std::to_string(value)); +} +inline bool parseDecimal(const juce::var& v,std::uint64_t& result,bool allowZero=false) { + if(!v.isString())return false; + const auto s=v.toString().toStdString(); + if(s.empty()||s.size()>20||(s[0]=='0'&&s.size()!=1))return false; + std::uint64_t n=0; + auto [end,err]=std::from_chars(s.data(),s.data()+s.size(),n); + if(err!=std::errc{}||end!=s.data()+s.size()||(!allowZero&&!n))return false; + result=n;return true; +} +inline bool real(const juce::var& v,double& n,double lo,double hi) { + if(!(v.isDouble()||v.isInt()||v.isInt64()))return false; + n=static_cast(v); + return std::isfinite(n)&&n>=lo&&n<=hi; +} +inline bool integral(const juce::var& v,int& n,int lo,int hi) { + if(!v.isInt())return false; + n=static_cast(v); + return n>=lo&&n<=hi; +} +inline juce::var get(const juce::var& v,const char* key) { + return v.isObject()?v.getProperty(key,juce::var()):juce::var(); +} +inline bool strictBool(const juce::var& v,bool& out) { + if(!v.isBool())return false; + out=static_cast(v);return true; +} +inline bool textField(const juce::var& v,juce::String& out,int max,bool empty=false) { + if(!v.isString()||v.toString().getNumBytesAsUTF8()>max|| + (!empty&&v.toString().isEmpty()))return false; + out=v.toString();return true; +} +class Codec final { + static juce::var object(){return juce::var(new juce::DynamicObject());} + static void set(juce::var& obj,const char* k,const juce::var& v) { + obj.getDynamicObject()->setProperty(k,v); + } + static juce::var ids(const LegacyChannelIds& ids) { + auto v=object(); + juce::Array in,aux; + for(auto id:ids.inputs)in.add(decimal(id.value)); + for(auto id:ids.aux)aux.add(decimal(id.value)); + set(v,"inputs",juce::var(in));set(v,"aux",juce::var(aux)); + set(v,"main",decimal(ids.main.value)); + set(v,"monitor",decimal(ids.monitor.value)); + return v; + } + static bool readIds(const juce::var& v,LegacyChannelIds& ids) { + const auto* in=get(v,"inputs").getArray(),*aux=get(v,"aux").getArray(); + if(!in||!aux||in->size()!=stripCount||aux->size()!=auxBusCount) + return false; + for(int i=0;igetReference(i),ids.inputs[i].value))return false; + for(int i=0;igetReference(i),ids.aux[i].value))return false; + return parseDecimal(get(v,"main"),ids.main.value) && + parseDecimal(get(v,"monitor"),ids.monitor.value,true); + } +public: + static juce::String encode(const MixerSessionDocument& d) { + auto root=object(); + set(root,"schema","arsonmix.mixer-session.v1"); + set(root,"id",d.id); + set(root,"acceptedRevision",decimal(d.acceptedRevision)); + set(root,"savedMs",decimal(static_cast(d.savedMs))); + set(root,"legacyIds",ids(d.legacyIds)); + auto bind=object(); + set(bind,"backend",d.binding.backend); + set(bind,"capture",d.binding.capture); + set(bind,"playback",d.binding.playback); + set(bind,"inputMask",d.binding.inputMask); + set(bind,"outputMask",d.binding.outputMask); + set(bind,"rate",d.binding.rate); + set(bind,"frames",d.binding.frames); + set(root,"binding",bind); + auto output=object(); + set(output,"active",d.outputs.activeOutputChannels); + set(output,"mainL",d.outputs.mainL);set(output,"mainR",d.outputs.mainR); + set(output,"monitorL",d.outputs.monitorL); + set(output,"monitorR",d.outputs.monitorR); + set(output,"monitorEnabled",d.outputs.monitorEnabled); + set(root,"outputs",output); + auto master=object(); + set(master,"gain",d.masterGain);set(master,"mute",d.masterMute); + set(master,"mono",d.masterMono);set(root,"master",master); + juce::Array channels; + for(const auto& row:d.roster.channels()) { + auto ch=object(); + set(ch,"id",decimal(row.id.value)); + set(ch,"role",static_cast(row.role)); + set(ch,"format",static_cast(row.format)); + set(ch,"name",juce::String::fromUTF8(row.name.c_str())); + set(ch,"gain",row.faderLinear); + set(ch,"pan",row.pan);set(ch,"mute",row.mute);set(ch,"solo",row.solo); + juce::Array catalogs,sends; + for(const auto& c:row.insertCatalogIds) + catalogs.add(juce::String::fromUTF8(c.c_str())); + for(const auto& s:row.sends){ + auto e=object(); + set(e,"edgeId",decimal(s.edgeId)); + set(e,"to",decimal(s.destination.value)); + set(e,"gain",s.gain);set(e,"pan",s.pan); + set(e,"pre",s.preFader);set(e,"primary",s.primaryOutput); + sends.add(e); + } + set(ch,"catalogs",juce::var(catalogs)); + set(ch,"sends",juce::var(sends)); + channels.add(ch); + } + set(root,"channels",juce::var(channels)); + auto request=object(); + set(request,"physicalInputs",d.request.physicalInputs); + set(request,"maxFrames",d.request.maxFrames); + set(request,"mainMonoAfterFx",d.request.mainMonoAfterFx); + juce::Array sources; + for(const auto& p:d.request.sources) { + auto source=object(); + set(source,"id",decimal(p.id.value)); + set(source,"left",p.inputL); + set(source,"right",p.inputR); + set(source,"stereo",p.stereo); + sources.add(source); + } + set(request,"sources",juce::var(sources)); + set(root,"request",request); + juce::Array inserts,racks; + for(const auto& f:d.inserts) { + auto fx=object(); + set(fx,"channel",decimal(f.channel.value)); + set(fx,"slot",static_cast(f.slot)); + set(fx,"catalogId",f.catalogId);set(fx,"path",f.path); + set(fx,"uid",f.uid);set(fx,"name",f.name); + set(fx,"sha256",f.sha256);set(fx,"bypass",f.bypass); + inserts.add(fx); + } + for(auto id:d.rackBypassed)racks.add(decimal(id.value)); + set(root,"inserts",juce::var(inserts));set(root,"rackBypassed",juce::var(racks)); + return juce::JSON::toString(root,false); + } + static bool decode(const juce::String& json,MixerSessionDocument& output) { + if(json.getNumBytesAsUTF8()>4U*1024U*1024U)return false; + auto root=juce::JSON::parse(json); + if(!root.isObject()||get(root,"schema").toString()!="arsonmix.mixer-session.v1") + return false; + MixerSessionDocument doc; + if(!textField(get(root,"id"),doc.id,48)|| + !armix::shows::detail::uuid(doc.id)|| + !parseDecimal(get(root,"acceptedRevision"),doc.acceptedRevision)|| + !readIds(get(root,"legacyIds"),doc.legacyIds)) + return false; + std::uint64_t ms=0; + if(!parseDecimal(get(root,"savedMs"),ms)||ms>static_cast( + std::numeric_limits::max()))return false; + doc.savedMs=static_cast(ms); + const auto binding=get(root,"binding"); + if(!textField(get(binding,"backend"),doc.binding.backend,128)|| + !textField(get(binding,"capture"),doc.binding.capture,256)|| + !textField(get(binding,"playback"),doc.binding.playback,256)|| + !textField(get(binding,"inputMask"),doc.binding.inputMask,256)|| + !textField(get(binding,"outputMask"),doc.binding.outputMask,256)) + return false; + double n=0.; + if(!real(get(binding,"rate"),n,8000.,384000.))return false; + doc.binding.rate=n; + if(!integral(get(binding,"frames"),doc.binding.frames,16,8192)) + return false; + auto outputs=get(root,"outputs"); + if(!integral(get(outputs,"active"),doc.outputs.activeOutputChannels,2,256)|| + !integral(get(outputs,"mainL"),doc.outputs.mainL,0,255)|| + !integral(get(outputs,"mainR"),doc.outputs.mainR,0,255)|| + !integral(get(outputs,"monitorL"),doc.outputs.monitorL,-1,255)|| + !integral(get(outputs,"monitorR"),doc.outputs.monitorR,-1,255)|| + !strictBool(get(outputs,"monitorEnabled"),doc.outputs.monitorEnabled)|| + !doc.outputs.valid())return false; + auto master=get(root,"master"); + if(!real(get(master,"gain"),n,0.,4.))return false; + doc.masterGain=static_cast(n); + if(!strictBool(get(master,"mute"),doc.masterMute)|| + !strictBool(get(master,"mono"),doc.masterMono))return false; + const auto* channels=get(root,"channels").getArray(); + if(!channels||channels->size()<15||channels->size()>2048)return false; + std::vector entries; + entries.reserve(static_cast(channels->size())); + for(const auto& ch:*channels) { + ChannelStripDefinition row; + int role=0,format=0; + if(!parseDecimal(get(ch,"id"),row.id.value)|| + !integral(get(ch,"role"),role,0,4)|| + !integral(get(ch,"format"),format,0,1))return false; + row.role=static_cast(role); + row.format=static_cast(format); + juce::String name; + if(!textField(get(ch,"name"),name,96)|| + !real(get(ch,"gain"),n,0.,4.))return false; + row.name=name.toStdString();row.faderLinear=static_cast(n); + if(!real(get(ch,"pan"),n,-1.,1.))return false; + row.pan=static_cast(n); + if(!strictBool(get(ch,"mute"),row.mute)|| + !strictBool(get(ch,"solo"),row.solo))return false; + const auto* catalogs=get(ch,"catalogs").getArray(); + const auto* sends=get(ch,"sends").getArray(); + if(!catalogs||!sends||catalogs->size()>8||sends->size()>128) + return false; + for(const auto& catalog:*catalogs) { + juce::String value; + if(!textField(catalog,value,256))return false; + row.insertCatalogIds.push_back(value.toStdString()); + } + for(const auto& send:*sends) { + ChannelSendRef edge; + if(!parseDecimal(get(send,"edgeId"),edge.edgeId)|| + !parseDecimal(get(send,"to"),edge.destination.value)|| + !real(get(send,"gain"),n,0.,4.))return false; + edge.gain=static_cast(n); + if(!real(get(send,"pan"),n,-1.,1.))return false; + edge.pan=static_cast(n); + if(!strictBool(get(send,"pre"),edge.preFader)|| + !strictBool(get(send,"primary"),edge.primaryOutput))return false; + row.sends.push_back(edge); + } + entries.push_back(std::move(row)); + } + if(!doc.roster.restoreExact(doc.acceptedRevision,entries))return false; + const auto seek=[&doc](ChannelId id,ChannelRole role){ + const auto* row=doc.roster.find(id); + return row && row->role==role; + }; + for(auto id:doc.legacyIds.inputs)if(!seek(id,ChannelRole::input))return false; + for(auto id:doc.legacyIds.aux)if(!seek(id,ChannelRole::fxReturn))return false; + if(!seek(doc.legacyIds.main,ChannelRole::main) || + (doc.legacyIds.monitor.value&&!seek(doc.legacyIds.monitor,ChannelRole::monitor))) + return false; + auto req=get(root,"request"); + if(!integral(get(req,"physicalInputs"),doc.request.physicalInputs,1,256)|| + !integral(get(req,"maxFrames"),doc.request.maxFrames,16,8192)|| + !strictBool(get(req,"mainMonoAfterFx"),doc.request.mainMonoAfterFx)) + return false; + const auto* sources=get(req,"sources").getArray(); + if(!sources||sources->size()>channels->size())return false; + std::set seenSources; + for(const auto& src:*sources) { + DynamicSourcePatch p; + if(!parseDecimal(get(src,"id"),p.id.value)|| + !seenSources.insert(p.id.value).second || + !seek(p.id,ChannelRole::input) || + !integral(get(src,"left"),p.inputL,0,doc.request.physicalInputs-1)|| + !integral(get(src,"right"),p.inputR,-1,doc.request.physicalInputs-1)|| + !strictBool(get(src,"stereo"),p.stereo)|| + (p.stereo && (p.inputR<0||p.inputR==p.inputL))|| + (!p.stereo&&p.inputR>=0)) + return false; + doc.request.sources.push_back(p); + } + const auto* fx=get(root,"inserts").getArray(); + const auto* racks=get(root,"rackBypassed").getArray(); + if(!fx||!racks||fx->size()>16384||racks->size()>channels->size())return false; + std::set> seenFx; + for(const auto& item:*fx) { + StoredInsert p;int slot=0; + if(!parseDecimal(get(item,"channel"),p.channel.value)|| + !doc.roster.find(p.channel)|| + !integral(get(item,"slot"),slot,0,7))return false; + p.slot=static_cast(slot); + if(!seenFx.emplace(p.channel.value,p.slot).second|| + !textField(get(item,"catalogId"),p.catalogId,256)|| + !textField(get(item,"path"),p.path,2048,true)|| + !textField(get(item,"name"),p.name,256,true)|| + !integral(get(item,"uid"),p.uid,std::numeric_limits::min(), + std::numeric_limits::max())|| + !textField(get(item,"sha256"),p.sha256,64)|| + p.sha256.length()!=64 || + !p.sha256.containsOnly("0123456789abcdef")|| + !strictBool(get(item,"bypass"),p.bypass))return false; + doc.inserts.push_back(std::move(p)); + } + for(const auto& item:*racks) { + ChannelId id; + if(!parseDecimal(item,id.value)||!doc.roster.find(id)|| + std::find(doc.rackBypassed.begin(),doc.rackBypassed.end(),id)!= + doc.rackBypassed.end())return false; + doc.rackBypassed.push_back(id); + } + for(const auto& ch:doc.roster.channels()) { + std::size_t slot=0; + for(const auto& fxRow:doc.inserts) + if(fxRow.channel==ch.id) { + if(fxRow.slot!=slot++)return false; + if(!ch.insertCatalogIds.empty() && + ch.insertCatalogIds[fxRow.slot]!=fxRow.catalogId.toStdString()) + return false; + } + if(!ch.insertCatalogIds.empty()&&slot!=ch.insertCatalogIds.size()) + return false; + } + output=std::move(doc); + return true; + } +}; +} // namespace armix::session From 0767d4781f4cb48d7760de339e00066edd0c5552 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:07:45 +0700 Subject: [PATCH 180/219] fix(session): keep decoded JUCE arrays alive for full strict validation --- src/NativeMixerSessionDocument.h | 22 +++++++++++++++------- 1 file changed, 15 insertions(+), 7 deletions(-) diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 5ded49b17..e6393a435 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -92,7 +92,8 @@ class Codec final { return v; } static bool readIds(const juce::var& v,LegacyChannelIds& ids) { - const auto* in=get(v,"inputs").getArray(),*aux=get(v,"aux").getArray(); + const auto inputVar=get(v,"inputs"),auxVar=get(v,"aux"); + const auto* in=inputVar.getArray(),*aux=auxVar.getArray(); if(!in||!aux||in->size()!=stripCount||aux->size()!=auxBusCount) return false; for(int i=0;i(n); if(!strictBool(get(master,"mute"),doc.masterMute)|| !strictBool(get(master,"mono"),doc.masterMono))return false; - const auto* channels=get(root,"channels").getArray(); + const auto channelsVar=get(root,"channels"); + const auto* channels=channelsVar.getArray(); if(!channels||channels->size()<15||channels->size()>2048)return false; std::vector entries; entries.reserve(static_cast(channels->size())); @@ -243,8 +245,9 @@ class Codec final { row.pan=static_cast(n); if(!strictBool(get(ch,"mute"),row.mute)|| !strictBool(get(ch,"solo"),row.solo))return false; - const auto* catalogs=get(ch,"catalogs").getArray(); - const auto* sends=get(ch,"sends").getArray(); + const auto catalogsVar=get(ch,"catalogs"),sendsVar=get(ch,"sends"); + const auto* catalogs=catalogsVar.getArray(); + const auto* sends=sendsVar.getArray(); if(!catalogs||!sends||catalogs->size()>8||sends->size()>128) return false; for(const auto& catalog:*catalogs) { @@ -281,7 +284,8 @@ class Codec final { !integral(get(req,"maxFrames"),doc.request.maxFrames,16,8192)|| !strictBool(get(req,"mainMonoAfterFx"),doc.request.mainMonoAfterFx)) return false; - const auto* sources=get(req,"sources").getArray(); + const auto sourcesVar=get(req,"sources"); + const auto* sources=sourcesVar.getArray(); if(!sources||sources->size()>channels->size())return false; std::set seenSources; for(const auto& src:*sources) { @@ -297,8 +301,9 @@ class Codec final { return false; doc.request.sources.push_back(p); } - const auto* fx=get(root,"inserts").getArray(); - const auto* racks=get(root,"rackBypassed").getArray(); + const auto fxVar=get(root,"inserts"),racksVar=get(root,"rackBypassed"); + const auto* fx=fxVar.getArray(); + const auto* racks=racksVar.getArray(); if(!fx||!racks||fx->size()>16384||racks->size()>channels->size())return false; std::set> seenFx; for(const auto& item:*fx) { @@ -326,6 +331,9 @@ class Codec final { doc.rackBypassed.end())return false; doc.rackBypassed.push_back(id); } + // Encode always emits in ChannelId/slot order. A manually shuffled or + // duplicated slot manifest is rejected; its vendor states must never + // attach to a different processor or channel. for(const auto& ch:doc.roster.channels()) { std::size_t slot=0; for(const auto& fxRow:doc.inserts) From c388184bb2e2b68395115339356fc027b30ef0fe Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:08:42 +0700 Subject: [PATCH 181/219] feat(session): immutable SHA-verified MixerSession generations and explicit last-good recovery --- src/NativeMixerSessionStore.h | 185 ++++++++++++++++++++++++++++++++++ 1 file changed, 185 insertions(+) create mode 100644 src/NativeMixerSessionStore.h diff --git a/src/NativeMixerSessionStore.h b/src/NativeMixerSessionStore.h new file mode 100644 index 000000000..883f2b2e5 --- /dev/null +++ b/src/NativeMixerSessionStore.h @@ -0,0 +1,185 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativeMixerSessionDocument.h" +#include +#include +#include +#include +#include + +// One durable device-independent MixerSessionDocument per Studio workspace. +// No audio thread access. Generations are immutable. A single atomic HEAD +// pointer is the commit boundary, and PREVIOUS remains explicit recovery only. +namespace armix::session { +class NativeMixerSessionStore final { +public: + explicit NativeMixerSessionStore(juce::File studio) + : root_(studio.getChildFile("MixerSession")) {} + static constexpr juce::int64 maxJson=4*1024*1024; + static constexpr juce::int64 maxState=8*1024*1024; + static constexpr juce::int64 maxTotal=128*1024*1024; + static constexpr std::size_t maxStates=16384; + + juce::String commit(const MixerSessionDocument& doc, + const std::vector& states) const { + if(!armix::shows::detail::uuid(doc.id)||states.size()>maxStates) + return "Mixer session ID/state count invalid"; + const auto json=Codec::encode(doc); + if(json.getNumBytesAsUTF8()>maxJson)return "Mixer session document exceeds 4 MB"; + MixerSessionDocument verified; + if(!Codec::decode(json,verified))return "Mixer session graph cannot be serialized safely"; + std::set hashes,referenced; + juce::int64 total=json.getNumBytesAsUTF8(); + for(const auto& fx:doc.inserts)referenced.insert(fx.sha256.toLowerCase()); + for(const auto& state:states) { + if(!safeHash(state.sha256)||!hashes.insert(state.sha256.toLowerCase()).second|| + state.bytes.getSize()>static_cast(maxState)|| + juce::SHA256(state.bytes).toHexString()!=state.sha256.toLowerCase()) + return "Mixer vendor state duplicate, oversized or wrong SHA"; + total+=static_cast(state.bytes.getSize()); + if(total>maxTotal)return "Mixer session exceeds 128 MB budget"; + } + if(hashes!=referenced)return "Mixer vendor state manifest is incomplete"; + if(!root_.isDirectory()&&root_.createDirectory().failed()) + return "MixerSession directory is not writable"; + const auto versions=root_.getChildFile("versions"); + if(!versions.isDirectory()&&versions.createDirectory().failed()) + return "MixerSession versions directory unavailable"; + const auto id=juce::Uuid().toDashedString().toLowerCase(); + if(!armix::shows::detail::uuid(id))return "Cannot allocate generation"; + const auto stage=root_.getChildFile(".staging-"+id); + if(stage.exists()||stage.createDirectory().failed()) + return "Cannot create mixer staging directory"; + struct Clean final { + juce::File dir; + ~Clean(){if(dir.exists())dir.deleteRecursively();} + } cleanup{stage}; + const auto payload=stage.getChildFile("blobs"); + if(payload.createDirectory().failed())return "Cannot create vendor state directory"; + const auto checksum=juce::SHA256(json.toRawUTF8(),json.getNumBytesAsUTF8()).toHexString(); + if(!stage.getChildFile("mixer.json").replaceWithText(json)|| + !stage.getChildFile("mixer.sha256").replaceWithText(checksum)) + return "Cannot write mixer document or checksum"; + for(const auto& state:states) { + const auto path=payload.getChildFile(state.sha256.toLowerCase()+".bin"); + if(!path.replaceWithData(state.bytes.getData(),state.bytes.getSize())|| + path.getSize()!=static_cast(state.bytes.getSize())|| + !juce::SHA256(path).toHexString().equalsIgnoreCase(state.sha256)) + return "Cannot durably stage verified vendor state"; + } + MixerSessionDocument reread; + std::vector copies; + if(readGeneration(stage,reread,copies).isNotEmpty()|| + Codec::encode(reread)!=json)return "Staged session readback changed"; + const auto committed=versions.getChildFile(id); + if(committed.exists()||!stage.moveFileTo(committed)) + return "Cannot publish immutable mixer generation"; + const auto head=root_.getChildFile("HEAD"); + if(head.existsAsFile()) { + const auto previous=readPointer(head); + if(previous.isEmpty())return "Current mixer HEAD invalid; recover explicitly"; + MixerSessionDocument older; + std::vector oldStates; + const auto error=readGeneration(versions.getChildFile(previous),older,oldStates); + if(error.isNotEmpty()) + return "Current mixer generation invalid; preserve it for recovery: "+error; + const auto backupError=writePointer(root_.getChildFile("PREVIOUS"),previous); + if(backupError.isNotEmpty())return backupError; + } + return writePointer(head,id); + } + + // Read normal HEAD only: no silent fallback to an older performance. + juce::String load(MixerSessionDocument& out, + std::vector& states) const { + const auto pointer=readPointer(root_.getChildFile("HEAD")); + if(pointer.isEmpty())return "Mixer session HEAD missing or invalid"; + MixerSessionDocument doc; + std::vector binary; + const auto error=readGeneration(root_.getChildFile("versions").getChildFile(pointer), + doc,binary); + if(error.isNotEmpty())return error; + if(readPointer(root_.getChildFile("HEAD"))!=pointer) + return "Mixer HEAD changed during read"; + out=std::move(doc);states=std::move(binary); + return {}; + } + bool exists() const noexcept {return root_.getChildFile("HEAD").existsAsFile();} + // Recovery does NOT arm output or publish a graph. Valid HEAD wins. + juce::String recoverPrevious() const { + MixerSessionDocument current; + std::vector currentStates; + if(load(current,currentStates).isEmpty()) + return "Current mixer is verified; refusing rollback"; + const auto pointer=readPointer(root_.getChildFile("PREVIOUS")); + if(pointer.isEmpty())return "Last-good mixer pointer missing"; + MixerSessionDocument verified; + std::vector binary; + const auto error=readGeneration(root_.getChildFile("versions").getChildFile(pointer), + verified,binary); + if(error.isNotEmpty())return "Previous mixer generation invalid: "+error; + return writePointer(root_.getChildFile("HEAD"),pointer); + } +private: + juce::File root_; + static bool safeHash(const juce::String& hash) { + return hash.length()==64 && hash.containsOnly("0123456789abcdef"); + } + static juce::String readPointer(const juce::File& file) { + if(!file.existsAsFile()||file.getSize()<1||file.getSize()>128)return {}; + const auto name=file.loadFileAsString().trim(); + return armix::shows::detail::uuid(name)?name:juce::String{}; + } + static juce::String writePointer(const juce::File& file,const juce::String& id) { + if(!armix::shows::detail::uuid(id))return "Invalid mixer generation pointer"; + juce::TemporaryFile staging(file); + auto output=staging.getFile().createOutputStream(); + if(!output||!output->writeText(id+"\n",false,false,"\n")) + return "Cannot stage mixer HEAD"; + output->flush(); + if(output->getStatus().failed())return "Cannot flush mixer HEAD"; + output.reset(); + return staging.overwriteTargetFileWithTemporary() + ?juce::String{}:juce::String("Cannot atomically publish mixer HEAD"); + } + static juce::String readGeneration(const juce::File& generation, + MixerSessionDocument& out, + std::vector& states) { + const auto jsonFile=generation.getChildFile("mixer.json"); + const auto sumFile=generation.getChildFile("mixer.sha256"); + if(!generation.isDirectory()||!jsonFile.existsAsFile()|| + jsonFile.getSize()<1||jsonFile.getSize()>maxJson|| + !sumFile.existsAsFile()||sumFile.getSize()!=64) + return "Mixer JSON generation missing/oversized"; + const auto text=jsonFile.loadFileAsString(); + const auto expected=sumFile.loadFileAsString().trim(); + if(!safeHash(expected)|| + juce::SHA256(text.toRawUTF8(),text.getNumBytesAsUTF8()).toHexString()!=expected) + return "Mixer document SHA mismatch"; + MixerSessionDocument doc; + if(!Codec::decode(text,doc)) + return "Mixer session semantic validation rejected"; + std::set hashes; + for(const auto& insert:doc.inserts)hashes.insert(insert.sha256); + if(hashes.size()>maxStates)return "Mixer vendor state reference count exceeded"; + std::vector binaries; + juce::int64 total=0; + for(const auto& hash:hashes) { + if(!safeHash(hash))return "Unsafe mixer state hash"; + const auto file=generation.getChildFile("blobs").getChildFile(hash+".bin"); + if(!file.existsAsFile()||file.getSize()<0||file.getSize()>maxState) + return "Mixer VST3 state missing or oversized"; + total+=file.getSize(); + if(total>maxTotal)return "Mixer vendor state budget exceeded"; + armix::shows::BinaryState blob; + blob.sha256=hash; + if(!file.loadFileAsData(blob.bytes)|| + juce::SHA256(blob.bytes).toHexString()!=hash) + return "Mixer vendor state changed on disk"; + binaries.push_back(std::move(blob)); + } + out=std::move(doc);states=std::move(binaries); + return {}; + } +}; +} // namespace armix::session From 91fddf8036509ae660b0d1e036daf2a1722be891 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:09:53 +0700 Subject: [PATCH 182/219] test(session): exercise large stable native graph, vendor integrity, and crash HEAD recovery --- CMakeLists.txt | 8 ++ tests/native_mixer_session_store_test.cpp | 148 ++++++++++++++++++++++ 2 files changed, 156 insertions(+) create mode 100644 tests/native_mixer_session_store_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index 74bd93196..bf964b1ff 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -332,6 +332,14 @@ if(BUILD_TESTING) target_link_libraries(ARMixShowStoreTests PRIVATE juce::juce_core juce::juce_cryptography juce::juce_recommended_config_flags) target_compile_features(ARMixShowStoreTests PRIVATE cxx_std_20) add_test(NAME P4ImmutableNativeShowsAndVendorStateRoundTrip COMMAND ARMixShowStoreTests) + # Full-size stable ChannelId MixerSession document (never the fixed ShowV2). + juce_add_console_app(ARMixDurableMixerSessionTests PRODUCT_NAME "ArSonMix Durable Dynamic Mixer Session Tests") + target_sources(ARMixDurableMixerSessionTests PRIVATE tests/native_mixer_session_store_test.cpp + src/NativeMixerSessionDocument.h src/NativeMixerSessionStore.h) + target_link_libraries(ARMixDurableMixerSessionTests PRIVATE + juce::juce_audio_processors juce::juce_cryptography juce::juce_recommended_config_flags) + target_compile_features(ARMixDurableMixerSessionTests PRIVATE cxx_std_20) + add_test(NAME P0DynamicMixerSessionDocumentAndCrashSafeRecovery COMMAND ARMixDurableMixerSessionTests) # Eight-band native PEQ: deterministic sweep, stereo isolation, RT no-heap, # smoothing and Nyquist guards. Built with the existing Windows native lane. diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp new file mode 100644 index 000000000..1a274fd71 --- /dev/null +++ b/tests/native_mixer_session_store_test.cpp @@ -0,0 +1,148 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include "../src/NativeMixerSessionStore.h" + +using namespace armix::mixer; +using namespace armix::session; +using armix::shows::BinaryState; + +static MixerSessionDocument makeSession() { + MixerSessionDocument d; + d.id="11111111-2222-4333-8444-555555555555"; + d.savedMs=1762520000000LL; + d.binding={"ASIO","Verified ASIO","Verified ASIO","3","3",48000.,256}; + d.outputs={2,0,1,-1,-1,false}; + d.request.physicalInputs=2;d.request.maxFrames=256; + d.request.maxScratchBytes=32u*1024u*1024u; + d.masterGain=.7f;d.masterMute=true;d.masterMono=false; + std::vector rows; + for(int i=1;i<=10;++i) { + ChannelStripDefinition row; + row.id={static_cast(i)}; + row.role=ChannelRole::input; + row.name="CH "+std::to_string(i); + row.format=i==1?ProcessingFormat::mono:ProcessingFormat::stereo; + if(i==1){ + row.sends.push_back({{16},1.f,false,0.f,true,100}); + row.sends.push_back({{11},.3f,true,-.25f,false,101}); + row.insertCatalogIds.push_back("TestVendor|9|0"); + } else if(i==2)row.sends.push_back({{15},1.f,false,0.f,true,102}); + rows.push_back(std::move(row)); + d.legacyIds.inputs[i-1]={static_cast(i)}; + } + for(int i=0;i<4;++i) { + ChannelStripDefinition aux; + aux.id={static_cast(11+i)}; + aux.role=ChannelRole::fxReturn; + aux.format=ProcessingFormat::stereo; + aux.name="AUX "+std::to_string(i+1); + aux.sends.push_back({{15},1.f,false,0.f,true, + static_cast(200+i)}); + d.legacyIds.aux[i]=aux.id; + rows.push_back(std::move(aux)); + } + ChannelStripDefinition group; + group.id={16};group.role=ChannelRole::group; + group.name="Vocal Group";group.format=ProcessingFormat::stereo; + group.sends.push_back({{15},1.f,false,0.f,true,105}); + rows.push_back(std::move(group)); + ChannelStripDefinition main; + main.id={15};main.role=ChannelRole::main; + main.name="MAIN";main.format=ProcessingFormat::stereo; + rows.push_back(std::move(main)); + d.legacyIds.main={15}; + d.acceptedRevision=52; + assert(d.roster.restoreExact(d.acceptedRevision,rows)); + d.request.sources.push_back({{1},0,-1,false}); + d.rackBypassed.push_back({1}); + return d; +} +int main(){ + juce::ScopedJuceInitialiser_GUI init; + auto d=makeSession(); + const auto before=Codec::encode(d); + MixerSessionDocument restored; + assert(Codec::decode(before,restored)); + assert(restored.roster.size()==16); + assert(restored.roster.revision()==52); + assert(Codec::encode(restored)==before); + const auto* vocal=restored.roster.find({1}); + assert(vocal&&vocal->sends.size()==2); + assert(vocal->sends[0].edgeId==100&&vocal->sends[0].destination.value==16); + assert(vocal->sends[1].preFader&&vocal->sends[1].gain==.3f); + assert(restored.request.sources.size()==1); + assert(restored.request.sources[0].inputL==0); + assert(restored.binding.backend=="ASIO"); + assert(restored.outputs.mainR==1); + ChannelEdit newChannel; + newChannel.kind=ChannelEdit::Kind::add; + newChannel.position=15;newChannel.role=ChannelRole::input; + newChannel.format=ProcessingFormat::stereo; + newChannel.text="Added after restart"; + const std::array edits{newChannel}; + auto result=restored.roster.edit(restored.roster.revision(),edits); + assert(result.ok()&&result.createdIds.size()==1&&result.createdIds[0].value==17); + // Bad IDs, duplicate EdgeIDs or missing physical binding cannot be + // imported into an accepted PCM graph. + std::vector duplicate=d.roster.channels(); + duplicate[1].id=duplicate[0].id; + DynamicChannelRoster invalid; + assert(!invalid.restoreExact(1,duplicate)); + duplicate=d.roster.channels(); + duplicate[1].sends[0].edgeId=duplicate[0].sends[0].edgeId; + assert(!invalid.restoreExact(1,duplicate)); + auto bad=juce::JSON::parse(before); + bad.getDynamicObject()->setProperty("schema","untrusted.version"); + assert(!Codec::decode(juce::JSON::toString(bad,false),restored)); + bad=juce::JSON::parse(before); + auto binds=bad.getProperty("binding",{}); + binds.getDynamicObject()->setProperty("rate",0.0); + assert(!Codec::decode(juce::JSON::toString(bad,false),restored)); + + // Immutable generation chain with a REAL vendor state hash. + const auto base=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("ArSonMixDynamicSession","",false); + const auto studio=base.getChildFile("Studio"); + assert(studio.createDirectory().wasOk()); + NativeMixerSessionStore store(studio); + BinaryState binary; + const char bytes[]={'V','S','T','3','-','S','T','A','T','E',0,1,2}; + binary.bytes.append(bytes,sizeof(bytes)); + binary.sha256=juce::SHA256(binary.bytes).toHexString(); + d.inserts.push_back({{1},0,"TestVendor|9|0","C:/FX/Test.vst3", + binary.sha256,"EQ",9,false}); + assert(store.commit(d,{binary}).isEmpty()); + MixerSessionDocument loaded; + std::vector readback; + assert(store.load(loaded,readback).isEmpty()); + assert(readback.size()==1&&readback[0].bytes==binary.bytes); + const auto firstId=studio.getChildFile("MixerSession").getChildFile("HEAD") + .loadFileAsString().trim(); + assert(armix::shows::detail::uuid(firstId)); + d.masterGain=.35f;d.savedMs+=1000; + assert(store.commit(d,{binary}).isEmpty()); + assert(store.load(loaded,readback).isEmpty()); + assert(loaded.masterGain==.35f); + assert(store.recoverPrevious().isNotEmpty()); // NEVER roll back valid HEAD + const auto head=studio.getChildFile("MixerSession").getChildFile("HEAD"); + const auto secondId=head.loadFileAsString().trim(); + const auto vendor=studio.getChildFile("MixerSession").getChildFile("versions") + .getChildFile(secondId).getChildFile("blobs") + .getChildFile(binary.sha256+".bin"); + assert(vendor.appendText("CORRUPTED")); + assert(store.load(loaded,readback).isNotEmpty()); + assert(loaded.masterGain==.35f); // rejection did not replace output + assert(store.recoverPrevious().isEmpty()); + assert(store.load(loaded,readback).isEmpty()); + assert(loaded.masterGain==.7f); + assert(readback[0].bytes==binary.bytes); + assert(!store.recoverPrevious().isEmpty()); + assert(base.deleteRecursively()); + std::cout<<"PASS: dynamic ChannelId/EdgeId graph, persistent vendor blobs and" + " explicit verified HEAD recovery\n"; + return 0; +} From 69017209154b1b47e4ede026abde5323c4ebe2e7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:11:41 +0700 Subject: [PATCH 183/219] fix(session): support legacy AUX metadata without misclassifying uninstalled VST3 --- src/NativeMixerSessionDocument.h | 8 ++++++-- tests/native_mixer_session_store_test.cpp | 1 - 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index e6393a435..970b7bf6c 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -343,8 +343,12 @@ class Codec final { ch.insertCatalogIds[fxRow.slot]!=fxRow.catalogId.toStdString()) return false; } - if(!ch.insertCatalogIds.empty()&&slot!=ch.insertCatalogIds.size()) - return false; + // The old four AUX are declared as legacy:aux-rack placeholders + // even when no plugin is installed. They are NOT vendor leases. + const bool legacyMarker=ch.insertCatalogIds.size()==1 && + ch.insertCatalogIds[0]=="legacy:aux-rack"; + if(!legacyMarker&&!ch.insertCatalogIds.empty()&& + slot!=ch.insertCatalogIds.size())return false; } output=std::move(doc); return true; diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index 1a274fd71..d2ab16ac5 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -62,7 +62,6 @@ static MixerSessionDocument makeSession() { return d; } int main(){ - juce::ScopedJuceInitialiser_GUI init; auto d=makeSession(); const auto before=Codec::encode(d); MixerSessionDocument restored; From 006959dd0fd168a04db9b0067245ed0fad001a25 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:14:19 +0700 Subject: [PATCH 184/219] feat(session): transactional device-epoch VST3 reconstruction outside audio callback --- src/NativeMixerSessionFxRestore.h | 103 ++++++++++++++++++++++++++++++ 1 file changed, 103 insertions(+) create mode 100644 src/NativeMixerSessionFxRestore.h diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h new file mode 100644 index 000000000..9310b8cff --- /dev/null +++ b/src/NativeMixerSessionFxRestore.h @@ -0,0 +1,103 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativeMixerSessionDocument.h" +#include "VstBusLayout.h" +#include "../engine/builtin_fx/ChannelEqProcessor.h" +#include +#include +#include +#include +#include + +// Prepare ALL owned VST3 processors on CONTROL before the one ChannelId PCM +// publisher commit. Never re-use a previous device epoch's processor. +namespace armix::session { +class NativeMixerSessionFxRestore final { +public: + using Bank=armix::mixer::DynamicChannelFxLeaseBank; + using Lease=armix::mixer::LiveChannelFxGraph::InstanceLease; + static juce::String prepare(const MixerSessionDocument& doc, + const std::vector& states, + juce::AudioPluginFormatManager& formats,double sampleRate, + int frames,std::uint64_t epoch,std::uint64_t pcmRevision, + std::shared_ptr& result) { + if(!(sampleRate>=8000.&&sampleRate<=384000.)||frames<32|| + frames>armix::mixer::PreparedMixerBlock::hardFrameLimit|| + epoch==0||pcmRevision==0) + return "Invalid driver/epoch for VST3 restoration"; + auto* format=formats.getFormat(0); + std::vector assignments; + assignments.reserve(doc.roster.size()); + try { + for(const auto& ch:doc.roster.channels()) { + Bank::Assignment lane; + lane.id=ch.id;lane.format=ch.format; + if(std::find(doc.rackBypassed.begin(),doc.rackBypassed.end(),ch.id) + !=doc.rackBypassed.end()) + lane.rackBypassed=std::make_shared>(true); + for(const auto& insert:doc.inserts) { + if(insert.channel!=ch.id)continue; + if(insert.slot!=lane.inserts.size()) + return "Saved FX slots are not contiguous"; + auto state=std::find_if(states.begin(),states.end(), + [&](const armix::shows::BinaryState& v){ + return v.sha256==insert.sha256; + }); + if(state==states.end()|| + state->bytes.getSize()>8U*1024U*1024U|| + juce::SHA256(state->bytes).toHexString()!=insert.sha256) + return "Missing or corrupt saved VST3 state"; + std::unique_ptr processor; + if(insert.catalogId== + armix::builtin_fx::ChannelEqProcessor::catalogIdentity) { + auto eq=std::make_unique(); + eq->prepareToPlay(sampleRate,frames); + if(!eq->isReady())return "Built-in EQ could not prepare"; + processor=std::move(eq); + } else { + if(!format|| + !format->fileMightContainThisPluginType(insert.path)) + return "Saved VST3 unavailable: "+insert.catalogId; + juce::OwnedArray descriptions; + format->findAllTypesForFile(descriptions,insert.path); + juce::PluginDescription* chosen=nullptr; + for(auto* d:descriptions) + if(d&&d->uniqueId==insert.uid&&!d->isInstrument) + {chosen=d;break;} + if(!chosen)return "Saved VST3 identity not found: "+insert.catalogId; + juce::String pluginError; + processor=formats.createPluginInstance(*chosen,sampleRate,frames,pluginError); + if(!processor) + return "VST3 instance unavailable: "+pluginError; + const auto layout=armix::vst::prepareStereoEffectLayout(*processor); + if(layout.isNotEmpty()) + return "Saved VST3 stereo layout rejected: "+layout; + processor->prepareToPlay(sampleRate,frames); + } + processor->setStateInformation(state->bytes.getData(), + static_cast(state->bytes.getSize())); + const int latency=processor->getLatencySamples(); + if(latency<0|| + latency>armix::dsp::StereoLatencyDelay::maximumSamples) + return "Saved FX latency exceeds graph PDC budget"; + auto owner=std::make_shared( + std::move(processor),insert.catalogId,insert.name, + armix::mixer::PreparedMixerBlock::hardFrameLimit); + owner->bypassRequested.store(insert.bypass,std::memory_order_release); + lane.inserts.push_back(std::move(owner)); + } + assignments.push_back(std::move(lane)); + } + Bank prepared; + const auto fault=Bank::prepare(epoch,pcmRevision,assignments,prepared); + if(fault!=Bank::Fault::none) + return "Saved native FX lease rejected: "+ + juce::String(static_cast(fault)); + result=std::make_shared(std::move(prepared)); + return {}; + }catch(const std::exception& ex) { + return "VST3 restore rejected: "+juce::String(ex.what()); + }catch(...) {return "VST3 restore aborted without PCM mutation";} + } +}; +} // namespace armix::session From be597e18d39a59a5f435c219be7219be333d5a5d Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:15:05 +0700 Subject: [PATCH 185/219] feat(session): capture authoritative ChannelId/VST3 state and publish atomic restored graph muted --- src/LiveDryRoutingLab.h | 129 ++++++++++++++++++++++++++++++++++++++++ 1 file changed, 129 insertions(+) diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 3f1f97af9..a7b804604 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -11,6 +11,7 @@ #include "../engine/core/NativeDryRouteCommand.h" #include "NativeVerifiedSourcePatch.h" #include "NativeTopologyEditSafety.h" +#include "NativeMixerSessionDocument.h" #include "../engine/device/JuceActivePortSnapshot.h" #include "../engine/core/RealtimeRoutePublisher.h" #include "../engine/core/RealtimeRenderPermit.h" @@ -2023,6 +2024,134 @@ class LiveDryRoutingLab final { } // CONTROL snapshot: genuine stable ChannelIds from the SAME publisher // as physical PCM. No guessed IDs, synthetic UI routes or JS DSP. + + // CONTROL-only capture of the currently INSTALLED ChannelId PCM graph. + // Fail closed if any vendor cannot supply a quiescent binary state. + juce::String captureNativeMixerSession( + armix::session::MixerSessionDocument& document, + std::vector& blobs) noexcept { + using namespace armix::mixer; + if(!channelIdPhysicalPcmActive()|| + !nativeAccepted_.matches(nativePublisher_,epoch(),nativeAccepted_.pcmRevision)) + return "No authoritative native ChannelId graph"; + if(nativeAccepted_.fxOwners->externalChannel().value) + return "External CH1 FX owner cannot yet be serialized independently"; + try { + armix::session::MixerSessionDocument draft; + draft.roster=nativeAccepted_.graph.roster; + draft.acceptedRevision=draft.roster.revision(); + draft.legacyIds=nativeAccepted_.graph.ids; + draft.outputs=nativeAccepted_.hardware; + draft.request=nativeAccepted_.graph.request; + std::vector staged; + std::set hashes; + juce::int64 total=0; + for(const auto& channel:draft.roster.channels()) { + const auto count=nativeAccepted_.fxOwners->insertCount(channel.id); + if(count>static_cast(FxGraph::maxInsertsPerStrip)) + return "Native FX count exceeded per-channel rack"; + if(nativeAccepted_.fxOwners->rackBypassed(channel.id)) + draft.rackBypassed.push_back(channel.id); + for(std::size_t slot=0;slotownerForControl(channel.id,slot); + if(!owner||!*owner||!(*owner)->processor|| + (*owner)->catalogId.isEmpty()) + return "Native FX lease missing during capture"; + juce::MemoryBlock bytes; + if(!(*owner)->tryCaptureState(bytes)) + return "VST3 state not quiescent: "+(*owner)->catalogId; + total+=static_cast(bytes.getSize()); + if(total>128LL*1024LL*1024LL) + return "Native mixer vendor-state budget exceeded"; + const auto hash=juce::SHA256(bytes).toHexString(); + draft.inserts.push_back({channel.id,slot,(*owner)->catalogId, + {},hash,(*owner)->name,0, + (*owner)->bypassRequested.load(std::memory_order_acquire)}); + if(hashes.insert(hash).second) { + armix::shows::BinaryState entry; + entry.sha256=hash;entry.bytes=std::move(bytes); + staged.push_back(std::move(entry)); + } + } + } + if(epoch()!=nativeAccepted_.deviceEpoch || + !nativeAccepted_.matches(nativePublisher_,epoch(),nativeAccepted_.pcmRevision)) + return "Native graph changed during FX snapshot"; + document=std::move(draft); + blobs=std::move(staged); + return {}; + } catch(...) {return "Native graph/VST3 state capture failed";} + } + + // Restore the validated persisted ChannelId roster with exactly ONE + // native PCM publication. Rejected sessions leave the current unpatched + // graph and hardware MUTE untouched. No native FX construction here. + juce::String restoreNativeMixerSession( + armix::session::MixerSessionDocument document, + std::shared_ptr bank, + bool outputsDisarmed) { + using namespace armix::mixer; + if(!outputsDisarmed||!ready()|| + !registryValid_.load(std::memory_order_acquire)|| + channelIdPhysicalPcmActive()||!bank) + return "Restore requires verified unpatched and muted device"; + if(document.request.physicalInputs!=portCount_.load(std::memory_order_acquire)|| + document.outputs.activeOutputChannels!=callbackOutputCount_.load(std::memory_order_acquire)) + return "NEEDS_REMAP: callback port layout changed"; + const auto generation=epoch(); + const auto* active=publisher_.controlPrepared(generation,revision()); + if(!active || document.outputs.mainL!=active->mainOutputLeft() || + document.outputs.mainR!=active->mainOutputRight() || + document.outputs.monitorEnabled!=active->monitorEnabled() || + (document.outputs.monitorEnabled && + (document.outputs.monitorL!=active->monitorOutputLeft()|| + document.outputs.monitorR!=active->monitorOutputRight()))) + return "NEEDS_REMAP: physical MAIN/MONITOR output pair changed"; + if(document.request.maxFrames<=0)return "Invalid saved mixer quantum"; + try { + document.request.maxFrames=active->maxFramesPerPlugin(); + document.request.maxScratchBytes=32U*1024U*1024U; + const auto previous=nativePublisher_.acceptedRevision(); + DynamicNativeSessionPublisher::FxPlan fx; + fx.owner=std::static_pointer_cast(bank); + fx.context=bank.get(); + fx.deviceEpoch=generation;fx.graphRevision=previous+1; + fx.render=+[](void* p,ChannelId id,float* l,float* r,int n) noexcept { + (*static_cast(p))(id,l,r,n); + }; + fx.latency=+[](void* p,ChannelId id) noexcept { + return static_cast(p)->latencySamples(id); + }; + const auto published=nativePublisher_.commit( + document.roster,document.request,previous,generation,epoch(), + true,std::move(fx)); + if(!published.ok()) + return "Native ChannelId PCM rejected persisted topology: "+ + juce::String(static_cast(published.fault)); + nativeAccepted_.graph.roster=std::move(document.roster); + nativeAccepted_.graph.request=std::move(document.request); + nativeAccepted_.graph.ids=document.legacyIds; + nativeAccepted_.graph.revision=nativeAccepted_.graph.roster.revision(); + nativeAccepted_.hardware=document.outputs; + nativeAccepted_.fxOwners=std::move(bank); + nativeAccepted_.deviceEpoch=generation; + nativeAccepted_.pcmRevision=published.revision; + nativeStructureLive_=true; + nativeControlDirty_=true; + nativeMeterEpoch_.store(0,std::memory_order_release); + // Only the logical source patch is restored. Physical OUT remains + // disarmed until the user independently enables monitoring. + userPatched_.store(true,std::memory_order_release); + channelIdPcmEpoch_.store(generation,std::memory_order_release); + return {}; + }catch(...) {return "Native session restore exception";} + } + + std::uint64_t nativeGraphRevisionForRestore() const noexcept { + const auto current=nativePublisher_.acceptedRevision(); + return current==std::numeric_limits::max()?0:current+1; + } + juce::var nativeBusStatus(bool retained=false) const { if(!nativeAccepted_.fxOwners || (!retained && !channelIdPhysicalPcmActive()))return {}; From 538ad143f1831145f0bae49bc5339431080dc424 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:15:38 +0700 Subject: [PATCH 186/219] feat(session): validate hardware binding then restore VST3 vendor state into real PCM graph --- src/LiveAudioEngine.h | 78 +++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 78 insertions(+) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index b6265d758..c9f89328a 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -7,6 +7,7 @@ #include "VstBusLayout.h" #include "LiveGraphHandoff.h" #include "LiveDryRoutingLab.h" +#include "NativeMixerSessionFxRestore.h" #include "NativeTopologyEditSafety.h" #include "../engine/dsp/NativeMasterLoudness.h" #include "../engine/builtin_fx/ChannelEqProcessor.h" @@ -1432,6 +1433,83 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return "MUTE OUTPUT and use verified DIRECT before FX state capture"; return dryRoutingLab_.captureRoutedFxStates(epoch,revision,states); } + + // Native session serialization is CONTROL-owned; all vendor binary reads + // require MUTED MAIN/STREAM, with zero I/O in the physical audio callback. + juce::String captureNativeMixerSession( + armix::session::MixerSessionDocument& document, + std::vector& states) { + if(!allOutputsDisarmed()||independent_.active()|| + !directFence_.permitted()|| + routeReconfiguring_.load(std::memory_order_acquire)|| + handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0) + return "MUTE MAIN/STREAM and finish FX handoff before session save"; + const auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device||!device->isOpen())return "Audio device unavailable for session capture"; + auto error=dryRoutingLab_.captureNativeMixerSession(document,states); + if(error.isNotEmpty())return error; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + document.binding={ + deviceManager_.getCurrentAudioDeviceType(), + setup.inputDeviceName,setup.outputDeviceName, + device->getActiveInputChannels().toString(16), + device->getActiveOutputChannels().toString(16), + device->getCurrentSampleRate(), + device->getCurrentBufferSizeSamples()}; + document.masterGain=masterGain_.load(std::memory_order_acquire); + document.masterMute=masterMute_.load(std::memory_order_acquire); + document.masterMono=masterMono_.load(std::memory_order_acquire); + return {}; + } + + // STARTUP: fresh vendor processors are prepared and all hashes validated + // before the ONE native PCM publication. No saved physical ARM state. + juce::String restoreNativeMixerSession( + armix::session::MixerSessionDocument document, + const std::vector& states) { + if(!allOutputsDisarmed()||independent_.active()||!attached_|| + !directFence_.permitted()||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + routeReconfiguring_.load(std::memory_order_acquire)) + return "MUTE output and verify DIRECT before restoring mixer"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device||!device->isOpen()) + return "NEEDS_REMAP: saved audio device unavailable"; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + if(document.binding.backend!=deviceManager_.getCurrentAudioDeviceType()|| + document.binding.capture!=setup.inputDeviceName|| + document.binding.playback!=setup.outputDeviceName|| + document.binding.inputMask!=device->getActiveInputChannels().toString(16)|| + document.binding.outputMask!=device->getActiveOutputChannels().toString(16)|| + document.binding.rate!=device->getCurrentSampleRate()) + return "NEEDS_REMAP: driver, endpoint, pin mask or rate changed"; + if(document.request.physicalInputs!= + device->getActiveInputChannels().countNumberOfSetBits()) + return "NEEDS_REMAP: callback-ordered physical input pins changed"; + const auto ep=dryRoutingLab_.epoch(); + const auto next=dryRoutingLab_.nativeGraphRevisionForRestore(); + if(!ep||!next)return "No valid native epoch for session restore"; + std::shared_ptr bank; + const auto error=armix::session::NativeMixerSessionFxRestore::prepare( + document,states,formats_,device->getCurrentSampleRate(), + juce::jmax(32,device->getCurrentBufferSizeSamples()),ep,next,bank); + if(error.isNotEmpty())return error; + const auto gain=document.masterGain; + const auto mute=document.masterMute; + const auto mono=document.masterMono; + const auto applied=dryRoutingLab_.restoreNativeMixerSession( + std::move(document),std::move(bank),allOutputsDisarmed()); + if(applied.isNotEmpty())return applied; + setMasterGainLinear(gain); + setMasterMuted(mute);setMasterMono(mono); + setMonitorEnabled(false); + return {}; + } + std::uint64_t dryRoutingLabEpoch() const noexcept {return dryRoutingLab_.epoch();} std::uint64_t dryRoutingLabRevision() const noexcept {return dryRoutingLab_.revision();} // One native ChannelId bus transaction on the installed DIRECT device. From 6f9869bdbe17037339b4821642020e45ae42f305 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:17:04 +0700 Subject: [PATCH 187/219] feat(session): bounded asynchronous immutable MixerSession disk writer off realtime --- src/NativeMixerSessionSaveWorker.h | 66 ++++++++++++++++++++++++++++++ 1 file changed, 66 insertions(+) create mode 100644 src/NativeMixerSessionSaveWorker.h diff --git a/src/NativeMixerSessionSaveWorker.h b/src/NativeMixerSessionSaveWorker.h new file mode 100644 index 000000000..6c4494dd9 --- /dev/null +++ b/src/NativeMixerSessionSaveWorker.h @@ -0,0 +1,66 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include "NativeMixerSessionStore.h" +#include +#include +#include +#include +#include +#include + +// Snapshot ownership moves from JUCE CONTROL to this single IO thread. +// No file IO or SHA-256 in the realtime callback. An immutable generation is +// promoted only after all bytes verify, with a message-thread completion. +namespace armix::session { +class NativeMixerSessionSaveWorker final : private juce::Thread { +public: + using Completion=std::function; + NativeMixerSessionSaveWorker():juce::Thread("ArSonMix MixerSession IO"){} + ~NativeMixerSessionSaveWorker() override { + alive_->store(false,std::memory_order_release); + signalThreadShouldExit(); + stopThread(-1); + } + bool busy() const noexcept {return busy_.load(std::memory_order_acquire);} + bool save(juce::File studio,MixerSessionDocument document, + std::vector binary, + Completion completion) { + if(busy_.exchange(true,std::memory_order_acq_rel))return false; + studio_=std::move(studio); + doc_=std::move(document); + states_=std::move(binary); + done_=std::move(completion); + if(!startThread()){ + busy_.store(false,std::memory_order_release); + done_={};states_.clear(); + return false; + } + return true; + } +private: + void run() override { + juce::String error; + try { + NativeMixerSessionStore store(studio_); + error=store.commit(doc_,states_); + }catch(...) {error="Mixer session IO worker exception";} + // Release potentially large VST3 binary buffers before callback. + states_.clear(); + auto alive=alive_; + juce::MessageManager::callAsync([this,alive,error]() mutable { + if(!alive->load(std::memory_order_acquire))return; + busy_.store(false,std::memory_order_release); + auto callback=std::move(done_); + done_={}; + if(callback)callback(std::move(error)); + }); + } + juce::File studio_; + MixerSessionDocument doc_; + std::vector states_; + Completion done_; + std::atomic busy_{false}; + std::shared_ptr> alive_= + std::make_shared>(true); +}; +} // namespace armix::session From 3d6fa3164b70caefc35770892b3ba3d6f4bb5145 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:21:02 +0700 Subject: [PATCH 188/219] feat(session): wire durable native autosave/startup restore to JUCE host with safe hardware gates --- src/Main.cpp | 177 +++++++++++++++++++++++++++++++ src/NativeMixerSessionDocument.h | 6 +- 2 files changed, 180 insertions(+), 3 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 2c331a9a0..fb441992d 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -33,6 +33,7 @@ #include "NativeLiveShowCapture.h" #include "NativeDryShowRecall.h" #include "NativeShowSaveWorker.h" +#include "NativeMixerSessionSaveWorker.h" #include #include #include @@ -322,6 +323,10 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr Browser browser_; armix::storage::StudioBackup::Worker studioBackupWorker_; armix::shows::NativeShowSaveWorker nativeShowWorker_; + armix::session::NativeMixerSessionSaveWorker mixerSessionWorker_; + juce::String mixerSessionId_,mixerSessionStatus_="NO_SAVED_SESSION"; + juce::String mixerSessionError_,lastMixerSessionFingerprint_; + bool mixerSessionStartupInspected_=false; bool nativeShowBusy_ = false; bool studioBackupBusy_ = false; std::unique_ptr chooser_; @@ -1768,6 +1773,126 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "arMixBuiltinEqAck",juce::var(ack.release())); } + + // Never confuse durable logical ChannelId state with a physical device + // authorization. This message-thread report is status only, not PCM. + void emitMixerSessionAck(const juce::String& operation, + const juce::String& error={}) { + auto ack=std::make_unique(); + ack->setProperty("operation",operation); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + ack->setProperty("state",mixerSessionStatus_); + ack->setProperty("saved",mixerSessionId_.isNotEmpty()); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixNativeSessionAck", + juce::var(ack.release())); + } + + // Called once immediately after startup and again only on user-directed + // restore. No implicit mapping to a different soundcard or active output. + juce::String restoreSavedMixerSession() { + if(!engine_.allOutputsDisarmed() || mixerSessionWorker_.busy() || + nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending()) + return "MUTE output and finish Studio IO before restoring mixer"; + armix::session::NativeMixerSessionStore store(settingsDirectory()); + if(!store.exists()) { + mixerSessionStatus_="NO_SAVED_SESSION"; + return "No saved dynamic mixer session"; + } + armix::session::MixerSessionDocument doc; + std::vector states; + auto error=store.load(doc,states); + if(error.isNotEmpty()) { + mixerSessionStatus_="DAMAGED_SESSION"; + mixerSessionError_=error; + diagnostics_.record("DYNAMIC_MIXER_READ_REJECTED",error); + return error; + } + mixerSessionId_=doc.id; + // Existing live graphs cannot be replaced by startup autosave or + // a stale More-button click. Never demote the true native renderer. + const auto live=engine_.status().getProperty("dryRoutingLab",{}); + if(static_cast(live.getProperty("nativeChannelIdPcmActive",false))) { + mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; + return "Live native mixer already active; refusing to replace it"; + } + error=engine_.restoreNativeMixerSession(std::move(doc),states); + if(error.isNotEmpty()) { + mixerSessionStatus_=error.contains("NEEDS_REMAP") + ?"NEEDS_REMAP":"RESTORE_REJECTED"; + mixerSessionError_=error; + diagnostics_.record("DYNAMIC_MIXER_RESTORE_REJECTED",error); + return error; + } + mixerSessionStatus_="RESTORED_MUTED"; + mixerSessionError_.clear(); + diagnostics_.record("DYNAMIC_MIXER_RESTORED", + "Exact native ChannelId/WIRE/VST3; outputs remain DISARMED"); + emitApprovedNativeSnapshot(); + return {}; + } + + // Explicit user SAVE and bounded checkpoint autosave share the same + // transaction. Native owner state only; no browser WIRE or demo scene. + juce::String saveMixerSession(bool automatic=false) { + if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_|| + catalog_.busy()||engine_.isGraphSwitchPending()|| + !engine_.allOutputsDisarmed()) + return "Mixer session save requires MUTED output and idle Studio IO"; + armix::session::MixerSessionDocument doc; + std::vector states; + auto error=engine_.captureNativeMixerSession(doc,states); + if(error.isNotEmpty())return error; + doc.id=mixerSessionId_.isNotEmpty()?mixerSessionId_: + juce::Uuid().toDashedString().toLowerCase(); + // Use the verified installed vendor identity; never load using a + // browser-provided plugin name or relocate an arbitrary VST3 path. + for(auto& fx:doc.inserts) { + if(fx.catalogId== + armix::builtin_fx::ChannelEqProcessor::catalogIdentity) { + fx.path={};fx.uid=0;continue; + } + const auto* catalog=catalog_.find(fx.catalogId); + if(!catalog)return "Session VST3 no longer in verified native catalog: "+fx.catalogId; + fx.path=catalog->path;fx.uid=catalog->uid; + fx.name=catalog->name; + } + doc.savedMs=1; // signature excludes wall time; includes FX state hashes + const auto canonical=armix::session::Codec::encode(doc); + armix::session::MixerSessionDocument verified; + if(!armix::session::Codec::decode(canonical,verified)) + return "Mixer session document validation rejected"; + const auto fingerprint=juce::SHA256(canonical.toRawUTF8(), + canonical.getNumBytesAsUTF8()).toHexString(); + if(automatic&&fingerprint==lastMixerSessionFingerprint_) + return {}; + doc.savedMs=juce::Time::currentTimeMillis(); + const auto pendingId=doc.id; + auto safe=juce::Component::SafePointer(this); + if(!mixerSessionWorker_.save(settingsDirectory(),std::move(doc), + std::move(states), + [safe,pendingId,fingerprint,automatic](juce::String failure){ + if(safe==nullptr)return; + if(failure.isEmpty()) { + safe->mixerSessionId_=pendingId; + safe->lastMixerSessionFingerprint_=fingerprint; + safe->mixerSessionStatus_="SAVED_VERIFIED_MUTED"; + safe->mixerSessionError_.clear(); + safe->diagnostics_.record("DYNAMIC_MIXER_SAVED", + automatic?"AUTO_CHECKPOINT":"OPERATOR_SAVE"); + }else{ + safe->mixerSessionStatus_="SAVE_REJECTED"; + safe->mixerSessionError_=failure; + safe->diagnostics_.record("DYNAMIC_MIXER_SAVE_REJECTED",failure); + if(!automatic)safe->emitNotice("Mixer session not saved: "+failure,true); + } + if(!automatic)safe->emitMixerSessionAck("SAVE",failure); + }))return "Mixer session IO worker unavailable"; + mixerSessionStatus_="SAVING"; + return {}; + } + void onAction (const juce::var& args) { const auto action = args.getProperty ("action", {}).toString(); @@ -2550,6 +2675,38 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr else emitNotice(error,true); return; } + + if(action=="nativeSessionInspect") { + emitMixerSessionAck("INSPECT", + mixerSessionStatus_=="DAMAGED_SESSION"?mixerSessionError_:juce::String{}); + return; + } + if(action=="nativeSessionSave" || action=="nativeSessionRestore" || + action=="nativeSessionRecover") { + juce::String result; + if(action=="nativeSessionSave")result=saveMixerSession(false); + else if(action=="nativeSessionRestore") + result=restoreSavedMixerSession(); + else { + if(!engine_.allOutputsDisarmed()||mixerSessionWorker_.busy()|| + nativeShowBusy_||studioBackupBusy_) + result="MUTE output and finish IO before last-good recovery"; + else { + armix::session::NativeMixerSessionStore store(settingsDirectory()); + result=store.recoverPrevious(); + if(result.isEmpty()) { + mixerSessionStatus_="RECOVERED_ON_DISK_MUTED"; + mixerSessionError_.clear(); + diagnostics_.record("DYNAMIC_MIXER_LAST_GOOD_RECOVERED", + "Disk pointer restored; manual load still required"); + } + } + } + if(result.isNotEmpty())emitNotice("MIXER SESSION: "+result,true); + emitMixerSessionAck(action=="nativeSessionSave"?"SAVE": + action=="nativeSessionRestore"?"RESTORE":"RECOVER",result); + return; + } if (action == "routingDryShowSave") { const auto updateShowId=value.isString()?value.toString():juce::String(); @@ -3497,6 +3654,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.devices().addChangeListener (this); diagnostics_.record ("STARTUP", startupError_.isEmpty() ? "Audio device initialized" : startupError_); + if(!mixerSessionStartupInspected_) { + mixerSessionStartupInspected_=true; + if(armix::session::NativeMixerSessionStore(settingsDirectory()).exists()){ + const auto error=restoreSavedMixerSession(); + if(error.isNotEmpty()) + emitNotice("Saved mixer retained; "+error,true); + } + } if (onStartupStage_) onStartupStage_ (2); } // ONE actionable notice per unexpected DIRECT reroute. The audio @@ -3518,6 +3683,15 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr // Audio thread publishes only fault flags. A bounded message-thread // restore transaction handles device failures without hot-plug spin. serviceDirectRestore(); + // Autosave only while ALL outputs are muted. Vendor-state reads + // happen on CONTROL; disk commits run on ONE serialized IO worker. + // A performance with armed speakers/stream is never interrupted for + // snapshot capture. One bounded attempt per 60 seconds of idle UI. + if(audioEngineStarted_ && timerTicks_%720==0 && + engine_.allOutputsDisarmed() && !mixerSessionWorker_.busy() && + !nativeShowBusy_ && !studioBackupBusy_ && !catalog_.busy() && + !engine_.isGraphSwitchPending() && !engine_.hasTemporaryDiagnosticDevice()) + (void)saveMixerSession(true); if (engine_.finalizeGraphSwitch()) { ++fxGraphRevision_; @@ -3630,6 +3804,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr !engine_.retainsRoutedFxEditor(routedEditorEpoch_,routedEditorOwner_)) closePluginEditor(); annotateRecovery (state); + state.getDynamicObject()->setProperty("mixerSessionStatus",mixerSessionStatus_); + if(mixerSessionError_.isNotEmpty()) + state.getDynamicObject()->setProperty("mixerSessionError",mixerSessionError_); state.getDynamicObject()->setProperty ("diagnosticsDropped", static_cast (diagnostics_.lostRecords())); state.getDynamicObject()->setProperty ("diagnosticsTruncated", diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 970b7bf6c..3288d567a 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -336,17 +336,17 @@ class Codec final { // attach to a different processor or channel. for(const auto& ch:doc.roster.channels()) { std::size_t slot=0; + const bool legacyMarker=ch.insertCatalogIds.size()==1 && + ch.insertCatalogIds[0]=="legacy:aux-rack"; for(const auto& fxRow:doc.inserts) if(fxRow.channel==ch.id) { if(fxRow.slot!=slot++)return false; - if(!ch.insertCatalogIds.empty() && + if(!legacyMarker && !ch.insertCatalogIds.empty() && ch.insertCatalogIds[fxRow.slot]!=fxRow.catalogId.toStdString()) return false; } // The old four AUX are declared as legacy:aux-rack placeholders // even when no plugin is installed. They are NOT vendor leases. - const bool legacyMarker=ch.insertCatalogIds.size()==1 && - ch.insertCatalogIds[0]=="legacy:aux-rack"; if(!legacyMarker&&!ch.insertCatalogIds.empty()&& slot!=ch.insertCatalogIds.size())return false; } From f875468db46d22af999b1cbda2cee00390a02788 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:21:51 +0700 Subject: [PATCH 189/219] feat(session): expose real native MixerSession Save/Restore/Last Good under approved More UI --- web/approved-native-bridge.js | 50 +++++++++++++++++++++++++++++++++++ 1 file changed, 50 insertions(+) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index a6b426f32..0b1158b16 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1772,8 +1772,57 @@ status(showNote.textContent); } }); + + // One durable ChannelId MixerSession, separate from the limited legacy + // ShowV2. These buttons NEVER stage browser-only mixer/FX state. + const sessionHeading=item("span","more-tools-caption", + "STUDIO / COMPLETE MIXER SESSION"); + const sessionSave=item("button","tool","Save Mixer Session"); + const sessionRestore=item("button","tool","Restore Saved Mixer"); + const sessionRecover=item("button","tool","Recover Previous Mixer"); + const sessionState=item("span","more-tools-caption", + "Checking native ChannelId session…"); + sessionState.style.whiteSpace="normal"; + sessionState.dataset.nativeSessionState="true"; + const sessionAction=(action)=>{ + if(hardware?.device?.outputArmed!==false || + hardware?.raw?.monitor===true){ + status("Mixer session: first MUTE physical output and STREAM"); + return; + } + backend.emitEvent("arMixAction",{action}); + sessionState.textContent=action==="nativeSessionSave"? + "Capturing native ChannelIds, WIRE, FX and vendor state…": + "Verifying saved native session and hardware identity…"; + }; + sessionSave.addEventListener("click",()=>sessionAction("nativeSessionSave")); + sessionRestore.addEventListener("click",()=>sessionAction("nativeSessionRestore")); + sessionRecover.addEventListener("click",()=>sessionAction("nativeSessionRecover")); + backend.addEventListener("arMixNativeSessionAck",ack=>{ + const state=String(ack?.state||"UNAVAILABLE"); + sessionState.textContent=state+(ack?.error?" · "+String(ack.error):""); + if(ack?.operation==="INSPECT")return; + if(ack?.ok===true){ + status(ack.operation==="SAVE"? + "Verified native MixerSession written; output remains MUTED": + ack.operation==="RESTORE"? + "Mixer Session restored; inspect routing then explicitly enable MONITOR": + "Previous MixerSession generation recovered on disk; RESTORE explicitly"); + controller?.subscribe(); + }else{ + status("MIXER SESSION: "+String(ack?.error||"No native ACK")); + nativeToast(String(ack?.error||"Mixer operation rejected")); + } + }); + backend.addEventListener("arMixStatus",state=>{ + const next=state?.mixerSessionStatus; + if(typeof next!=="string"||!next)return; + const label=next+(state.mixerSessionError?" · "+String(state.mixerSessionError):""); + if(sessionState.textContent!==label)sessionState.textContent=label; + }); menu.append(caption,setup,muteBtn,hardwareNote, healthTitle,mark,report,advanced, + sessionHeading,sessionSave,sessionRestore,sessionRecover,sessionState, showHeading,showSave,showBrowse,showSelect,showUpdate,showRecall,showRecover,showNote); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. @@ -2766,6 +2815,7 @@ const ready=()=>{ presentNativeOnlyTools(); installFirstSoundMenu(); + backend.emitEvent("arMixAction",{action:"nativeSessionInspect"}); scope?.setNativeCatalog?.([]); // no synthetic/demo VST3 in Windows host updateHardwarePanel(null); stopDemo(); From 0d5d956d544b85a95b5420fbc35a8497fbb524c6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:22:56 +0700 Subject: [PATCH 190/219] fix(session-ui): keep original native GUI-ready handshake event order intact --- web/approved-native-bridge.js | 1 - 1 file changed, 1 deletion(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 0b1158b16..847d6b18f 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2815,7 +2815,6 @@ const ready=()=>{ presentNativeOnlyTools(); installFirstSoundMenu(); - backend.emitEvent("arMixAction",{action:"nativeSessionInspect"}); scope?.setNativeCatalog?.([]); // no synthetic/demo VST3 in Windows host updateHardwarePanel(null); stopDemo(); From fd83a4b2a5482c5ebda2924843d77c71101efe5f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:24:26 +0700 Subject: [PATCH 191/219] test(ui): verify dynamic MixerSession native Save/Restore/Recovery ACK without auto-monitor --- tests/approved_native_cold_start_smoke.py | 20 ++++++++++++++++++++ 1 file changed, 20 insertions(+) diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index a7619b11a..3c5c56550 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -66,6 +66,26 @@ def show_select(value): const available=name=>buttons.find(b=>b.textContent===name)?.disabled===false; return {recall:available('Recall Show'),recover:available('Recover Last Good')}; }""",[show_panel,value]) + # The full dynamic ChannelId session is not the fixed ShowV2 + # and always passes through the real JUCE backend authority. + show_click("Save Mixer Session") + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeSessionSave" + emit(page,"arMixNativeSessionAck",{ + "operation":"SAVE","ok":True,"state":"SAVED_VERIFIED_MUTED"}) + assert "SAVED_VERIFIED_MUTED" in page.locator(show_panel).text_content() + show_click("Restore Saved Mixer") + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeSessionRestore" + emit(page,"arMixNativeSessionAck",{ + "operation":"RESTORE","ok":False,"state":"NEEDS_REMAP", + "error":"NEEDS_REMAP: physical ASIO input mask changed"}) + assert "NEEDS_REMAP" in page.locator(show_panel).text_content() + show_click("Recover Previous Mixer") + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeSessionRecover" + emit(page,"arMixNativeSessionAck",{ + "operation":"RECOVER","ok":True,"state":"RECOVERED_ON_DISK_MUTED"}) + assert "RECOVERED_ON_DISK_MUTED" in page.locator(show_panel).text_content() + # None of these three operations authorizes physical MONITOR. + assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") show_click("Browse Shows") assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" emit(page,"arMixNativeShowListAck",{"ok":True,"items":[ From 287ec41a9f952cb181177bb29d1152d8e49f0903 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 15:31:36 +0700 Subject: [PATCH 192/219] hardening(session): restrict restored VST3 to verified catalog and validate native EQ state; safe exit checkpoint --- src/Main.cpp | 36 +++++++++++++++++++++++++++++++ src/NativeMixerSessionFxRestore.h | 12 ++++++++--- 2 files changed, 45 insertions(+), 3 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index fb441992d..4c8be6bc4 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -306,6 +306,19 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr closePluginEditor(); audioSetupWindow_.reset(); engine_.devices().removeChangeListener (this); + // Best-effort clean-exit checkpoint, after emergency physical MUTE. + // A pending worker already owns a safe immutable snapshot. Never + // block or mutate the audio callback for session disk persistence. + engine_.setOutputMuted(true); + engine_.disconnectSecondaryOutput(); + if(!mixerSessionWorker_.busy()) { + const auto lab=engine_.status().getProperty("dryRoutingLab",{}); + if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false))) { + const auto error=saveMixerSession(true); + if(error.isNotEmpty()) + diagnostics_.record("DYNAMIC_MIXER_EXIT_SAVE_REJECTED",error); + } + } engine_.stop(); browser_.setVisible (false); } @@ -1810,6 +1823,29 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionId_=doc.id; + // A disk SHA is NOT permission to instantiate executable code. + // Every external VST3 must still match today's verified catalog + // identity, exact UID and registered path. A moved or tampered + // binary needs an explicit catalog remap, never a blind load. + for(const auto& insert:doc.inserts) { + if(insert.catalogId== + armix::builtin_fx::ChannelEqProcessor::catalogIdentity) { + if(insert.path.isNotEmpty() || insert.uid!=0) + return "Saved built-in EQ identity was modified"; + continue; + } + const auto* registered=catalog_.find(insert.catalogId); + if(!registered || registered->uid!=insert.uid || + registered->path!=insert.path || + registered->key()!=insert.catalogId) { + mixerSessionStatus_="NEEDS_VST3_REMAP"; + mixerSessionError_= + "Saved external VST3 identity unavailable: "+insert.catalogId; + diagnostics_.record("DYNAMIC_MIXER_VST3_REMAP_REQUIRED", + mixerSessionError_); + return mixerSessionError_; + } + } // Existing live graphs cannot be replaced by startup autosave or // a stale More-button click. Never demote the true native renderer. const auto live=engine_.status().getProperty("dryRoutingLab",{}); diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h index 9310b8cff..f1b785152 100644 --- a/src/NativeMixerSessionFxRestore.h +++ b/src/NativeMixerSessionFxRestore.h @@ -52,7 +52,11 @@ class NativeMixerSessionFxRestore final { armix::builtin_fx::ChannelEqProcessor::catalogIdentity) { auto eq=std::make_unique(); eq->prepareToPlay(sampleRate,frames); - if(!eq->isReady())return "Built-in EQ could not prepare"; + if(!eq->isReady()|| + !eq->restoreUnpublishedState( + state->bytes.getData(), + static_cast(state->bytes.getSize()))) + return "Saved native EQ state rejected; graph unchanged"; processor=std::move(eq); } else { if(!format|| @@ -74,8 +78,10 @@ class NativeMixerSessionFxRestore final { return "Saved VST3 stereo layout rejected: "+layout; processor->prepareToPlay(sampleRate,frames); } - processor->setStateInformation(state->bytes.getData(), - static_cast(state->bytes.getSize())); + if(insert.catalogId!= + armix::builtin_fx::ChannelEqProcessor::catalogIdentity) + processor->setStateInformation(state->bytes.getData(), + static_cast(state->bytes.getSize())); const int latency=processor->getLatencySamples(); if(latency<0|| latency>armix::dsp::StereoLatencyDelay::maximumSamples) From 54a2cd5615628c4f0c2a56c0a2159b91abeb9a06 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:20:49 +0700 Subject: [PATCH 193/219] fix(session): fail-closed FX roster validation and indexed ChannelId/VST3 recovery with corruption tests --- src/NativeMixerSessionDocument.h | 13 ++++--- src/NativeMixerSessionFxRestore.h | 41 ++++++++++++++++------- tests/native_mixer_session_store_test.cpp | 28 +++++++++++++++- 3 files changed, 64 insertions(+), 18 deletions(-) diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index 3288d567a..d24adae0e 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -341,14 +341,19 @@ class Codec final { for(const auto& fxRow:doc.inserts) if(fxRow.channel==ch.id) { if(fxRow.slot!=slot++)return false; - if(!legacyMarker && !ch.insertCatalogIds.empty() && - ch.insertCatalogIds[fxRow.slot]!=fxRow.catalogId.toStdString()) + // A malformed, otherwise SHA-correct document can claim + // more FX slots than the accepted roster's catalog. + // Bound-check BEFORE indexing: never allow UB on restore. + if(!legacyMarker && + (fxRow.slot>=ch.insertCatalogIds.size() || + ch.insertCatalogIds[fxRow.slot]!=fxRow.catalogId.toStdString())) return false; } // The old four AUX are declared as legacy:aux-rack placeholders // even when no plugin is installed. They are NOT vendor leases. - if(!legacyMarker&&!ch.insertCatalogIds.empty()&& - slot!=ch.insertCatalogIds.size())return false; + // No orphan leases, and no phantom roster FX. In particular an + // empty catalog cannot authorize an installed vendor processor. + if(!legacyMarker&&slot!=ch.insertCatalogIds.size())return false; } output=std::move(doc); return true; diff --git a/src/NativeMixerSessionFxRestore.h b/src/NativeMixerSessionFxRestore.h index f1b785152..7bab6ca48 100644 --- a/src/NativeMixerSessionFxRestore.h +++ b/src/NativeMixerSessionFxRestore.h @@ -7,6 +7,8 @@ #include #include #include +#include +#include #include // Prepare ALL owned VST3 processors on CONTROL before the one ChannelId PCM @@ -28,6 +30,18 @@ class NativeMixerSessionFxRestore final { auto* format=formats.getFormat(0); std::vector assignments; assignments.reserve(doc.roster.size()); + // Index ONCE. A large dynamic mixer must not rescan every channel + // against all VST3 inserts and binary states at every restart. + // Manifest validity is established by Codec; preserve slot order. + std::unordered_map> byChannel; + std::unordered_map byHash; + byChannel.reserve(doc.roster.size()); + byHash.reserve(states.size()); + for(const auto& insert:doc.inserts) + byChannel[insert.channel.value].push_back(&insert); + for(const auto& state:states) + if(!byHash.emplace(state.sha256.toStdString(),&state).second) + return "Duplicate mixer vendor-state blob identity"; try { for(const auto& ch:doc.roster.channels()) { Bank::Assignment lane; @@ -35,17 +49,18 @@ class NativeMixerSessionFxRestore final { if(std::find(doc.rackBypassed.begin(),doc.rackBypassed.end(),ch.id) !=doc.rackBypassed.end()) lane.rackBypassed=std::make_shared>(true); - for(const auto& insert:doc.inserts) { - if(insert.channel!=ch.id)continue; + const auto laneIt=byChannel.find(ch.id.value); + if(laneIt!=byChannel.end()) + for(const StoredInsert* stored:laneIt->second) { + const auto& insert=*stored; if(insert.slot!=lane.inserts.size()) return "Saved FX slots are not contiguous"; - auto state=std::find_if(states.begin(),states.end(), - [&](const armix::shows::BinaryState& v){ - return v.sha256==insert.sha256; - }); - if(state==states.end()|| - state->bytes.getSize()>8U*1024U*1024U|| - juce::SHA256(state->bytes).toHexString()!=insert.sha256) + const auto found=byHash.find(insert.sha256.toStdString()); + if(found==byHash.end()) + return "Missing saved VST3 state"; + const auto& state=*found->second; + if(state.bytes.getSize()>8U*1024U*1024U|| + juce::SHA256(state.bytes).toHexString()!=insert.sha256) return "Missing or corrupt saved VST3 state"; std::unique_ptr processor; if(insert.catalogId== @@ -54,8 +69,8 @@ class NativeMixerSessionFxRestore final { eq->prepareToPlay(sampleRate,frames); if(!eq->isReady()|| !eq->restoreUnpublishedState( - state->bytes.getData(), - static_cast(state->bytes.getSize()))) + state.bytes.getData(), + static_cast(state.bytes.getSize()))) return "Saved native EQ state rejected; graph unchanged"; processor=std::move(eq); } else { @@ -80,8 +95,8 @@ class NativeMixerSessionFxRestore final { } if(insert.catalogId!= armix::builtin_fx::ChannelEqProcessor::catalogIdentity) - processor->setStateInformation(state->bytes.getData(), - static_cast(state->bytes.getSize())); + processor->setStateInformation(state.bytes.getData(), + static_cast(state.bytes.getSize())); const int latency=processor->getLatencySamples(); if(latency<0|| latency>armix::dsp::StereoLatencyDelay::maximumSamples) diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index d2ab16ac5..e1afb9ce4 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -29,7 +29,6 @@ static MixerSessionDocument makeSession() { if(i==1){ row.sends.push_back({{16},1.f,false,0.f,true,100}); row.sends.push_back({{11},.3f,true,-.25f,false,101}); - row.insertCatalogIds.push_back("TestVendor|9|0"); } else if(i==2)row.sends.push_back({{15},1.f,false,0.f,true,102}); rows.push_back(std::move(row)); d.legacyIds.inputs[i-1]={static_cast(i)}; @@ -114,6 +113,33 @@ int main(){ binary.sha256=juce::SHA256(binary.bytes).toHexString(); d.inserts.push_back({{1},0,"TestVendor|9|0","C:/FX/Test.vst3", binary.sha256,"EQ",9,false}); + { + auto installed=d.roster.channels(); + installed[0].insertCatalogIds.push_back("TestVendor|9|0"); + assert(d.roster.restoreExact(d.acceptedRevision,installed)); + } + // Semantic corruption must be rejected, even if the surrounding JSON + // is otherwise well-formed or would have a valid SHA-256 on disk. + const auto validWithFx=Codec::encode(d); + MixerSessionDocument rejected; + auto damaged=juce::JSON::parse(validWithFx); + auto channels=damaged.getProperty("channels",{}); + auto* entries=channels.getArray(); + assert(entries && !entries->isEmpty()); + auto catalog=entries->getReference(0).getProperty("catalogs",{}); + catalog.getArray()->clear(); + assert(!Codec::decode(juce::JSON::toString(damaged,false),rejected)); + // A ghost slot may not point past the one accepted catalog entry. + damaged=juce::JSON::parse(validWithFx); + auto inserts=damaged.getProperty("inserts",{}); + inserts.getArray()->getReference(0).getDynamicObject()->setProperty("slot",1); + assert(!Codec::decode(juce::JSON::toString(damaged,false),rejected)); + // Wrong plugin on the same slot is not a valid ChannelId FX recovery. + damaged=juce::JSON::parse(validWithFx); + inserts=damaged.getProperty("inserts",{}); + inserts.getArray()->getReference(0).getDynamicObject() + ->setProperty("catalogId","OtherVendor|99|0"); + assert(!Codec::decode(juce::JSON::toString(damaged,false),rejected)); assert(store.commit(d,{binary}).isEmpty()); MixerSessionDocument loaded; std::vector readback; From d3267e69e892c6fde2bc3231fd83ecd14141076c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:23:11 +0700 Subject: [PATCH 194/219] fix(gui): enable one-click and keyboard channel identity editing with durable native ChannelId presentation --- scripts/build_approved_native_gui.py | 2 +- ...roved_operator_ux_native_identity_smoke.py | 29 +++++++- tests/approved_operator_ux_smoke.py | 8 +- web/approved-native-bridge.js | 74 ++++++++++++++++--- 4 files changed, 95 insertions(+), 18 deletions(-) diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index e44a9a227..d8984eefb 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -234,7 +234,7 @@ def accepted_pages_html() -> str: " renderPluginCatalog();renderFastPicker();return pluginCatalog.length;\n" " },\n" " closeNativePicker(){setFastPicker(false);},\n" - " colors:COLORS,wireGraph:ArSonWireGraph,\n" + " colors:COLORS,channelIcons:CHANNEL_ICONS,wireGraph:ArSonWireGraph,\n" " allocateWireId(){return nextWireId++;},\n" " installGraph(channels,main,edges){\n" " tracks=channels;master=main;wireEdges=edges;\n" diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py index 9816e8758..c5aa6dcda 100644 --- a/tests/approved_operator_ux_native_identity_smoke.py +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -45,9 +45,19 @@ def open_page(): assert page.locator('#wireNavigatorToggle').is_visible() emit(page,"arMixConsoleSnapshot",state) page.wait_for_selector('#tracks .strip[data-id="1"]') - page.locator('#tracks .strip[data-id="1"] .strip-identity-top').dblclick() + # Single click on the top identity, not double click, is the + # discoverable native edit path. It must not create PCM intents. + page.locator('#tracks .strip[data-id="1"] .strip-identity-top').click() editor=page.locator('#channelIdentity') - assert editor.is_visible(),"native bridge still blocks identity window" + assert editor.is_visible(),"single-click native identity editor did not open" + assert page.locator('#identityName').is_focused() + page.locator('#identityName').fill("Discard this") + page.locator('#identityCancel').click() + assert editor.is_hidden(),"Cancel must dismiss without modifying the channel" + assert "Discard this" not in page.locator('#tracks .strip[data-id="1"]').inner_text() + # A normal click on the nameplate is also actionable. + page.locator('#tracks .strip[data-id="1"] .footer-label .name').click() + assert editor.is_visible(),"footer name click did not open editor" page.locator('#identityName').fill("Studio Vox") color="#c32974" page.locator(f'#identityColors [data-identity-color="{color}"]').click() @@ -75,16 +85,27 @@ def open_page(): emit(page,"arMixConsoleSnapshot",state) page.wait_for_selector('#tracks .strip[data-id="1"]') assert "Studio Vox" in page.locator('#tracks .strip[data-id="1"]').inner_text() - page.locator('#tracks .strip[data-id="2"] .strip-identity-top').dblclick() + # Keyboard F2 edits the selected loaded channel; Enter on focused + # footer name is accessible when using keyboard-only navigation. + page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() + assert page.locator('#channelIdentity').is_visible() + page.locator('#identityCancel').click() + page.keyboard.press('F2') + assert page.locator('#channelIdentity').is_visible(),"F2 edit not available" page.locator('#identityName').fill('Studio Vox') page.locator('#identitySave').click() assert page.locator('#channelIdentity').is_visible(),\ "duplicate visible channel names should not silently collide" page.locator('#identityClose').click() + page.locator('#tracks .strip[data-id="2"] .footer-label .name').focus() + page.keyboard.press('Enter') + assert page.locator('#channelIdentity').is_visible(),"keyboard Enter did not open editor" + page.keyboard.press('Escape') + assert page.locator('#channelIdentity').is_hidden() assert page.evaluate("()=>window.__nativeIntents.length")==0 assert not errors,errors page.close() context.close();browser.close() - print("PASS native identity: real edit name/icon/color; exact ChannelId; readback/reload; duplicate reject; no PCM graph intents") + print("PASS native identity: click/header/footer, F2/Enter, Cancel/Escape, edited name/icon/color, readback/reload, duplicate reject, exact ChannelId, zero PCM intents") if __name__=="__main__":main() diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index 42a59c79a..353a239e4 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -64,7 +64,13 @@ def test_native_hooks_and_audio_input_default(self): engine=(ROOT/"src/LiveAudioEngine.h").read_text(encoding="utf-8") self.assertIn("openChannelIdentity,closeChannelIdentity",build) self.assertIn("?.applyIdentity?.())return;",build) - self.assertIn("scope?.openChannelIdentity?.(t,event.target)",bridge) + self.assertIn("openNativeIdentity(t,event.target)",bridge) + self.assertIn('if(action==="editIdentity"||action==="rename")',bridge) + self.assertIn("openNativeIdentity(t,btn)",bridge) + self.assertIn('event.key!=="F2"',bridge) + self.assertIn("identityChannelFor=t=>",bridge) + self.assertIn("Channel identity saved",bridge) + self.assertIn("channelIcons:CHANNEL_ICONS",build) self.assertIn("const identityStoreKey=",bridge) self.assertIn("channelPresentation.set(nativeId",bridge) self.assertIn("deviceManager_.initialise (2, 2, savedSettings, !savedRoute)",engine) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 847d6b18f..11732a781 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -34,13 +34,30 @@ } }catch(_){ /* unavailable storage must never break live mixer */ } const displayNameFor=ch=>channelPresentation.get(ch.id)?.name||ch.name; + // A channel's cosmetic identity can be edited when its exact native id is + // present in the current acknowledged OR retained graph. No physical + // audio device, output arm or PCM graph mutation is required. + const identityChannelFor=t=>{ + const id=nativeIdFor(t),current=controller?.state()?.current; + return id && (current?.admitted||current?.retained) && + current.graph?.channels?.some(ch=>ch.id===id)?id:null; + }; + const identityEligible=t=>Boolean(identityChannelFor(t)); + function openNativeIdentity(t,anchor){ + if(!identityEligible(t)){ + nativeToast("Channel identity unavailable until its native channel is loaded"); + return false; + } + scope?.openChannelIdentity?.(t,anchor); + return true; + } function acceptIdentityPresentation(){ const id=scope?.identityTrackId,t=scope?.tracks?.concat(scope.master||[]) ?.find(x=>x.id===id),nativeId=nativeIdFor(t); const name=String(document.getElementById("identityName")?.value||"") .trim().replace(/\s+/g," ").slice(0,30); - if(!nativeId||!flags.acceptedGraphConnected){ - status("Select an admitted native channel before editing its identity");return false; + if(!nativeId||!identityEligible(t)){ + nativeToast("Select a loaded native channel before editing its identity");return false; } if(!name||scope.tracks.concat(scope.master).some( x=>x.id!==id&&x.name.toLowerCase()===name.toLowerCase())){ @@ -48,13 +65,22 @@ } const color=/^#[0-9a-fA-F]{6}$/.test(scope.identityColor||"") ?scope.identityColor:t.color; - const icon=typeof scope.identityIcon==="string"&&scope.identityIcon.length<=4 + const icon=scope.channelIcons?.includes?.(scope.identityIcon) ?scope.identityIcon:t.icon; + const previous=channelPresentation.get(nativeId); channelPresentation.set(nativeId,{name,color,icon}); try{ const channels=Object.fromEntries([...channelPresentation].slice(-128)); - window.localStorage?.setItem(identityStoreKey,JSON.stringify({version:1,channels})); - }catch(_){status("Channel display changed; local storage unavailable");} + if(!window.localStorage)throw new Error("Channel identity storage unavailable"); + window.localStorage.setItem(identityStoreKey,JSON.stringify({version:1,channels})); + }catch(_){ + // Never claim a saved identity if it cannot survive a WebView2 restart. + if(previous)channelPresentation.set(nativeId,previous); + else channelPresentation.delete(nativeId); + nativeToast("Cannot save channel identity; check WebView storage access"); + return false; + } + nativeToast("Channel identity saved · "+name); return true; // original approved editor updates the single UI model } const pendingWireGains=new Map(); @@ -2434,8 +2460,14 @@ consumeAction(t,action,btn) { if (!connected)return false; // Selection, WIRE inspection and section presentation are UI-only. - if (["wireExpand","wireSource","wireRoute","editIdentity","rename"].includes(action)) - return !["wireExpand","wireSource","wireRoute"].includes(action); + if(action==="editIdentity"||action==="rename"){ + // A single click on the channel header/name now opens the SAME + // original name/color/icon editor. No demo graph changes. + openNativeIdentity(t,btn); + return true; + } + if (["wireExpand","wireSource","wireRoute"].includes(action)) + return false; if(action==="removeFx") { const slot=Number(btn?.dataset.slot),id=nativeIdFor(t),current=controller?.state()?.current; const token=current?.graph?.channels.find(ch=>ch.id===id)?.inserts?.[slot]?.id; @@ -2707,11 +2739,8 @@ if(m4ControlIsOwner()&&m4Verified())sendM4Control("pan",t,0); else intent("SET_PAN",t,{value:0}); } - else if(event.target.closest?.(".footer-label,.strip-identity-top")){ - if(nativeIdFor(t) && flags.acceptedGraphConnected) - scope?.openChannelIdentity?.(t,event.target); - else status("Channel identity available after verified native admission"); - } + else if(event.target.closest?.(".footer-label,.strip-identity-top")) + openNativeIdentity(t,event.target); return true; }, applyIdentity:acceptIdentityPresentation, @@ -2765,6 +2794,27 @@ // finishFaderPointer via build_approved_native_gui.py hook. A later // window.pointerup listener would run after that handler clears the gesture. + // Editing is accessible without a mouse. F2 operates on the selected + // loaded channel; Enter/Space activates the focusable footer name. + document.addEventListener("keydown",event=>{ + if(!connected||event.altKey||event.ctrlKey||event.metaKey)return; + const target=event.target; + if(target?.closest?.('input,textarea,select,[contenteditable="true"]'))return; + const focused=target?.closest?.('.footer-label .name'); + if(focused && ["Enter"," "].includes(event.key)){ + const track=scope?.tracks?.concat(scope.master||[])?.find( + item=>item.id===Number(focused.closest(".strip")?.dataset.id)); + event.preventDefault();event.stopImmediatePropagation(); + openNativeIdentity(track,focused);return; + } + if(event.key!=="F2")return; + const selected=scope?.tracks?.concat(scope.master||[])?.find(t=>t.selected); + if(!selected)return; + event.preventDefault();event.stopImmediatePropagation(); + openNativeIdentity(selected,document.querySelector('.strip.selected .footer-label')|| + document.querySelector('.strip.selected .strip-identity-top')); + },true); + // Pages' reference-only controls must not masquerade as working native // operations. Keep REAL audio/FX/WIRE/device controls fully interactive; // until full device-independent Show is implemented, hide unsafe demo From 33057bdf45371d01934c6267e07f91407f6f8db4 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:23:56 +0700 Subject: [PATCH 195/219] ci(identity): run genuine Chromium channel editor FAT on this exact PR --- .github/workflows/ui-smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 6d2ff22f7..793dfdbc2 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -118,7 +118,7 @@ jobs: operator-ux-fat: name: Operator UX real Chromium / native-assembled GUI (5 viewports) needs: quick - if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107' }} + if: ${{ github.event_name == 'pull_request' && (github.head_ref == 'fix/approved-operator-ux-20261107' || github.head_ref == 'fix/native-channel-identity-editor-20261107') }} runs-on: ubuntu-latest timeout-minutes: 15 steps: From ea11e191c916d6395116985bbc57481b324c6709 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:26:04 +0700 Subject: [PATCH 196/219] test(identity): use supported Playwright focus evaluation for native edit FAT --- tests/approved_operator_ux_native_identity_smoke.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py index c5aa6dcda..2020be509 100644 --- a/tests/approved_operator_ux_native_identity_smoke.py +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -50,7 +50,7 @@ def open_page(): page.locator('#tracks .strip[data-id="1"] .strip-identity-top').click() editor=page.locator('#channelIdentity') assert editor.is_visible(),"single-click native identity editor did not open" - assert page.locator('#identityName').is_focused() + assert page.locator('#identityName').evaluate("el=>el===document.activeElement") page.locator('#identityName').fill("Discard this") page.locator('#identityCancel').click() assert editor.is_hidden(),"Cancel must dismiss without modifying the channel" From f5403b94ec6a881e9243ac55667eae2c8ac81ab6 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:28:25 +0700 Subject: [PATCH 197/219] fix(identity): retain focused native channel across Cancel/render for reliable F2 editor --- web/approved-native-bridge.js | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 11732a781..c7957c2e7 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -43,11 +43,13 @@ current.graph?.channels?.some(ch=>ch.id===id)?id:null; }; const identityEligible=t=>Boolean(identityChannelFor(t)); + let lastEditedChannelId=null; function openNativeIdentity(t,anchor){ if(!identityEligible(t)){ nativeToast("Channel identity unavailable until its native channel is loaded"); return false; } + lastEditedChannelId=t.id; scope?.openChannelIdentity?.(t,anchor); return true; } @@ -2808,11 +2810,16 @@ openNativeIdentity(track,focused);return; } if(event.key!=="F2")return; - const selected=scope?.tracks?.concat(scope.master||[])?.find(t=>t.selected); + const tracks=scope?.tracks?.concat(scope.master||[])||[]; + const focusedTrack=target?.closest?.(".strip")?.dataset.id; + const selected=tracks.find(t=>t.id===Number(focusedTrack))|| + tracks.find(t=>t.selected && identityEligible(t))|| + tracks.find(t=>t.id===lastEditedChannelId && identityEligible(t)); if(!selected)return; event.preventDefault();event.stopImmediatePropagation(); - openNativeIdentity(selected,document.querySelector('.strip.selected .footer-label')|| - document.querySelector('.strip.selected .strip-identity-top')); + const anchor=document.querySelector('.strip[data-id="'+selected.id+'"] .footer-label')|| + document.querySelector('.strip[data-id="'+selected.id+'"] .strip-identity-top'); + openNativeIdentity(selected,anchor); },true); // Pages' reference-only controls must not masquerade as working native From bbc918cc37b8e74fd4860224a7d7c08a78d53328 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:30:42 +0700 Subject: [PATCH 198/219] fix(identity): restore editor focus and allow F2 after closing hidden input --- web/approved-native-bridge.js | 20 +++++++++++++++++++- 1 file changed, 19 insertions(+), 1 deletion(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index c7957c2e7..5794f8c19 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2801,7 +2801,13 @@ document.addEventListener("keydown",event=>{ if(!connected||event.altKey||event.ctrlKey||event.metaKey)return; const target=event.target; - if(target?.closest?.('input,textarea,select,[contenteditable="true"]'))return; + const editorHidden=Boolean(document.getElementById("channelIdentity")?.hidden); + const textEntry=target?.closest?.('input,textarea,select,[contenteditable="true"]'); + // Closing the editor can leave DOM focus on its now-hidden input under + // WebView2. F2 must still reopen the last selected channel, rather than + // being swallowed by the generic text-entry shortcut guard. + if(textEntry && !(event.key==="F2" && editorHidden && + target?.id==="identityName"))return; const focused=target?.closest?.('.footer-label .name'); if(focused && ["Enter"," "].includes(event.key)){ const track=scope?.tracks?.concat(scope.master||[])?.find( @@ -2822,6 +2828,18 @@ openNativeIdentity(selected,anchor); },true); + // Preserve keyboard focus when closing the modeless identity window. + // The original Pages close handlers own visibility; never replace them. + for(const id of ["identityCancel","identityClose","identitySave"]){ + document.getElementById(id)?.addEventListener("click",()=>{ + requestAnimationFrame(()=>{ + if(!document.getElementById("channelIdentity")?.hidden)return; + const name=document.querySelector('.strip[data-id="'+lastEditedChannelId+'"] .footer-label .name'); + name?.focus?.(); + }); + }); + } + // Pages' reference-only controls must not masquerade as working native // operations. Keep REAL audio/FX/WIRE/device controls fully interactive; // until full device-independent Show is implemented, hide unsafe demo From c7b4c89f65014a80058d65fbdf29105ca0d08c30 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:32:55 +0700 Subject: [PATCH 199/219] ci(identity): restore normal runner scope after passing real Chromium editor FAT --- .github/workflows/ui-smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 793dfdbc2..6d2ff22f7 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -118,7 +118,7 @@ jobs: operator-ux-fat: name: Operator UX real Chromium / native-assembled GUI (5 viewports) needs: quick - if: ${{ github.event_name == 'pull_request' && (github.head_ref == 'fix/approved-operator-ux-20261107' || github.head_ref == 'fix/native-channel-identity-editor-20261107') }} + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107' }} runs-on: ubuntu-latest timeout-minutes: 15 steps: From 903f1652e539ef167cb7666889c0a58fba9acdf0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:45:20 +0700 Subject: [PATCH 200/219] fix(gui): native channel identity editor opens on double-click only; single-click selects --- ...roved_operator_ux_native_identity_smoke.py | 19 +++++++++++-------- tests/approved_operator_ux_smoke.py | 3 ++- web/approved-native-bridge.js | 6 +++--- 3 files changed, 16 insertions(+), 12 deletions(-) diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py index 2020be509..64510bee9 100644 --- a/tests/approved_operator_ux_native_identity_smoke.py +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -45,19 +45,23 @@ def open_page(): assert page.locator('#wireNavigatorToggle').is_visible() emit(page,"arMixConsoleSnapshot",state) page.wait_for_selector('#tracks .strip[data-id="1"]') - # Single click on the top identity, not double click, is the - # discoverable native edit path. It must not create PCM intents. + # DAW convention: single click selects channel; only double-click + # on its header/footer opens the name/color/icon editor. page.locator('#tracks .strip[data-id="1"] .strip-identity-top').click() editor=page.locator('#channelIdentity') - assert editor.is_visible(),"single-click native identity editor did not open" + assert editor.is_hidden(),"single-click must only select the channel" + page.locator('#tracks .strip[data-id="1"] .strip-identity-top').dblclick() + assert editor.is_visible(),"double-click on header did not open editor" assert page.locator('#identityName').evaluate("el=>el===document.activeElement") page.locator('#identityName').fill("Discard this") page.locator('#identityCancel').click() assert editor.is_hidden(),"Cancel must dismiss without modifying the channel" assert "Discard this" not in page.locator('#tracks .strip[data-id="1"]').inner_text() - # A normal click on the nameplate is also actionable. + # Footer name follows the same single-select/double-edit contract. page.locator('#tracks .strip[data-id="1"] .footer-label .name').click() - assert editor.is_visible(),"footer name click did not open editor" + assert editor.is_hidden(),"single-click on footer name opened editor" + page.locator('#tracks .strip[data-id="1"] .footer-label .name').dblclick() + assert editor.is_visible(),"footer double-click did not open editor" page.locator('#identityName').fill("Studio Vox") color="#c32974" page.locator(f'#identityColors [data-identity-color="{color}"]').click() @@ -88,8 +92,7 @@ def open_page(): # Keyboard F2 edits the selected loaded channel; Enter on focused # footer name is accessible when using keyboard-only navigation. page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() - assert page.locator('#channelIdentity').is_visible() - page.locator('#identityCancel').click() + assert page.locator('#channelIdentity').is_hidden() page.keyboard.press('F2') assert page.locator('#channelIdentity').is_visible(),"F2 edit not available" page.locator('#identityName').fill('Studio Vox') @@ -106,6 +109,6 @@ def open_page(): assert not errors,errors page.close() context.close();browser.close() - print("PASS native identity: click/header/footer, F2/Enter, Cancel/Escape, edited name/icon/color, readback/reload, duplicate reject, exact ChannelId, zero PCM intents") + print("PASS native identity: single-click selects; double-click header/footer edits; F2/Enter, Cancel/Escape, name/icon/color, reload, duplicate reject, exact ChannelId, zero PCM intents") if __name__=="__main__":main() diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index 353a239e4..a86d2495f 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -66,7 +66,8 @@ def test_native_hooks_and_audio_input_default(self): self.assertIn("?.applyIdentity?.())return;",build) self.assertIn("openNativeIdentity(t,event.target)",bridge) self.assertIn('if(action==="editIdentity"||action==="rename")',bridge) - self.assertIn("openNativeIdentity(t,btn)",bridge) + self.assertIn("return true;\n }\n if ([\"wireExpand\",\"wireSource\",\"wireRoute\"].includes(action))",bridge) + self.assertIn("openNativeIdentity(t,event.target)",bridge) self.assertIn('event.key!=="F2"',bridge) self.assertIn("identityChannelFor=t=>",bridge) self.assertIn("Channel identity saved",bridge) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 5794f8c19..38ef97fb8 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2463,9 +2463,9 @@ if (!connected)return false; // Selection, WIRE inspection and section presentation are UI-only. if(action==="editIdentity"||action==="rename"){ - // A single click on the channel header/name now opens the SAME - // original name/color/icon editor. No demo graph changes. - openNativeIdentity(t,btn); + // DAW convention: one click only selects/focuses this channel. + // The existing native consumeDoubleClick opens the identity editor; + // never open it from the click event preceding a double-click. return true; } if (["wireExpand","wireSource","wireRoute"].includes(action)) From d15d53bc1b49134ee04f37ecbd9827e34cccc3b7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:45:46 +0700 Subject: [PATCH 201/219] ci: verify DAW double-click interaction in real Chromium native UI --- .github/workflows/ui-smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index 6d2ff22f7..f4ffcee3e 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -118,7 +118,7 @@ jobs: operator-ux-fat: name: Operator UX real Chromium / native-assembled GUI (5 viewports) needs: quick - if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107' }} + if: ${{ github.event_name == 'pull_request' && (github.head_ref == 'fix/approved-operator-ux-20261107' || github.head_ref == 'fix/native-identity-double-click-20261107') }} runs-on: ubuntu-latest timeout-minutes: 15 steps: From 9c544ce2806e37ccb49f9eed6dd716d2c59cf76e Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:47:21 +0700 Subject: [PATCH 202/219] feat(session): verify current device output pair and operator-approved mixer rebind policy --- src/LiveAudioEngine.h | 80 ++++++++++++++++++----- src/LiveDryRoutingLab.h | 26 ++++++++ src/NativeMixerSessionDocument.h | 45 +++++++++++++ tests/native_mixer_session_store_test.cpp | 25 +++++++ 4 files changed, 160 insertions(+), 16 deletions(-) diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index c9f89328a..1cb4bec6a 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1444,7 +1444,7 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback routeReconfiguring_.load(std::memory_order_acquire)|| handoff_.busy()||fxMovePhase_.load(std::memory_order_acquire)!=0) return "MUTE MAIN/STREAM and finish FX handoff before session save"; - const auto* device=deviceManager_.getCurrentAudioDevice(); + auto* device=deviceManager_.getCurrentAudioDevice(); if(!device||!device->isOpen())return "Audio device unavailable for session capture"; auto error=dryRoutingLab_.captureNativeMixerSession(document,states); if(error.isNotEmpty())return error; @@ -1463,11 +1463,63 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback return {}; } + struct MixerBindingInspection final { + armix::session::HardwareBinding live; + armix::mixer::VerifiedNativeOutputs outputs{}; + int callbackInputs=0; + std::uint64_t epoch=0; + bool changed=false; + }; + // A read-only control-thread preview for explicit hardware rebind. + juce::String inspectNativeMixerSessionBinding( + const armix::session::MixerSessionDocument& saved, + MixerBindingInspection& out) { + if(!allOutputsDisarmed()||independent_.active()||!attached_|| + !directFence_.permitted()||handoff_.busy()|| + fxMovePhase_.load(std::memory_order_acquire)!=0|| + diagnosticRoute_.load(std::memory_order_acquire)!= + armix::diagnostics::Route::normal|| + routeReconfiguring_.load(std::memory_order_acquire)) + return "MUTE output and verify DIRECT before device inspection"; + auto* device=deviceManager_.getCurrentAudioDevice(); + if(!device||!device->isOpen()) + return "NEEDS_REMAP: current audio device unavailable"; + MixerBindingInspection candidate; + juce::AudioDeviceManager::AudioDeviceSetup setup; + deviceManager_.getAudioDeviceSetup(setup); + candidate.live={ + deviceManager_.getCurrentAudioDeviceType(), + setup.inputDeviceName,setup.outputDeviceName, + device->getActiveInputChannels().toString(16), + device->getActiveOutputChannels().toString(16), + device->getCurrentSampleRate(), + device->getCurrentBufferSizeSamples()}; + candidate.callbackInputs=device->getActiveInputChannels().countNumberOfSetBits(); + candidate.epoch=dryRoutingLab_.epoch(); + if(!dryRoutingLab_.currentHardwareForSession(candidate.outputs) || + !candidate.epoch) + return "NEEDS_REMAP: live MAIN output pair is not verified"; + auto probe=saved; + const auto reason=armix::session::MixerDeviceBindingPolicy::apply( + probe,candidate.live,candidate.outputs,candidate.callbackInputs,true); + if(reason.isNotEmpty())return reason; + candidate.changed=! + armix::session::MixerDeviceBindingPolicy::sameBinding( + saved.binding,candidate.live) || + !armix::session::MixerDeviceBindingPolicy::sameOutputs( + saved.outputs,candidate.outputs); + if(candidate.epoch!=dryRoutingLab_.epoch()) + return "NEEDS_REMAP: device changed during inspection"; + out=std::move(candidate); + return {}; + } + // STARTUP: fresh vendor processors are prepared and all hashes validated // before the ONE native PCM publication. No saved physical ARM state. juce::String restoreNativeMixerSession( armix::session::MixerSessionDocument document, - const std::vector& states) { + const std::vector& states, + bool explicitDeviceRebind=false) { if(!allOutputsDisarmed()||independent_.active()||!attached_|| !directFence_.permitted()||handoff_.busy()|| fxMovePhase_.load(std::memory_order_acquire)!=0|| @@ -1475,21 +1527,17 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::diagnostics::Route::normal|| routeReconfiguring_.load(std::memory_order_acquire)) return "MUTE output and verify DIRECT before restoring mixer"; + MixerBindingInspection inspected; + auto bindingError=inspectNativeMixerSessionBinding(document,inspected); + if(bindingError.isNotEmpty())return bindingError; + bindingError=armix::session::MixerDeviceBindingPolicy::apply( + document,inspected.live,inspected.outputs, + inspected.callbackInputs,explicitDeviceRebind); + if(bindingError.isNotEmpty())return bindingError; auto* device=deviceManager_.getCurrentAudioDevice(); - if(!device||!device->isOpen()) - return "NEEDS_REMAP: saved audio device unavailable"; - juce::AudioDeviceManager::AudioDeviceSetup setup; - deviceManager_.getAudioDeviceSetup(setup); - if(document.binding.backend!=deviceManager_.getCurrentAudioDeviceType()|| - document.binding.capture!=setup.inputDeviceName|| - document.binding.playback!=setup.outputDeviceName|| - document.binding.inputMask!=device->getActiveInputChannels().toString(16)|| - document.binding.outputMask!=device->getActiveOutputChannels().toString(16)|| - document.binding.rate!=device->getCurrentSampleRate()) - return "NEEDS_REMAP: driver, endpoint, pin mask or rate changed"; - if(document.request.physicalInputs!= - device->getActiveInputChannels().countNumberOfSetBits()) - return "NEEDS_REMAP: callback-ordered physical input pins changed"; + if(!device||!device->isOpen() || + dryRoutingLab_.epoch()!=inspected.epoch) + return "NEEDS_REMAP: device epoch changed before PCM publish"; const auto ep=dryRoutingLab_.epoch(); const auto next=dryRoutingLab_.nativeGraphRevisionForRestore(); if(!ep||!next)return "No valid native epoch for session restore"; diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index a7b804604..84fbeaefc 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2083,6 +2083,32 @@ class LiveDryRoutingLab final { } catch(...) {return "Native graph/VST3 state capture failed";} } + // Read the CURRENT legacy publisher's physical destinations on CONTROL. + // A persisted pair must never be mistaken for hardware authorization. + bool currentHardwareForSession( + armix::mixer::VerifiedNativeOutputs& result) const noexcept { + if(!ready() || !registryValid_.load(std::memory_order_acquire)) + return false; + const auto generation=epoch(); + const auto* active=publisher_.controlPrepared(generation,revision()); + const int count=callbackOutputCount_.load(std::memory_order_acquire); + if(!active || count<2 || count>256)return false; + armix::mixer::VerifiedNativeOutputs observed{}; + observed.activeOutputChannels=count; + observed.mainL=active->mainOutputLeft(); + observed.mainR=active->mainOutputRight(); + observed.monitorEnabled=active->monitorEnabled(); + if(observed.monitorEnabled) { + observed.monitorL=active->monitorOutputLeft(); + observed.monitorR=active->monitorOutputRight(); + } + if(!observed.valid() || epoch()!=generation || + !registryValid_.load(std::memory_order_acquire)) + return false; + result=observed; + return true; + } + // Restore the validated persisted ChannelId roster with exactly ONE // native PCM publication. Rejected sessions leave the current unpatched // graph and hardware MUTE untouched. No native FX construction here. diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index d24adae0e..6797ec04d 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -42,6 +42,51 @@ struct MixerSessionDocument final { std::uint64_t acceptedRevision=0; juce::int64 savedMs=0; }; +// Logical topology never authorizes a different physical endpoint. An +// operator-confirmed rebind changes only verified hardware metadata; it +// cannot change the ChannelId graph, vendor state, or ARM an output. +struct MixerDeviceBindingPolicy final { + static bool sameBinding(const HardwareBinding& a,const HardwareBinding& b) { + return a.backend==b.backend && a.capture==b.capture && + a.playback==b.playback && a.inputMask==b.inputMask && + a.outputMask==b.outputMask && a.rate==b.rate; + } + static bool sameOutputs(const VerifiedNativeOutputs& a, + const VerifiedNativeOutputs& b) { + return a.activeOutputChannels==b.activeOutputChannels && + a.mainL==b.mainL && a.mainR==b.mainR && + a.monitorEnabled==b.monitorEnabled && + (!a.monitorEnabled || + (a.monitorL==b.monitorL && a.monitorR==b.monitorR)); + } + static juce::String apply(MixerSessionDocument& document, + const HardwareBinding& live, + const VerifiedNativeOutputs& outputs, + int callbackInputs,bool operatorApproved) { + if(!outputs.valid() || callbackInputs<1 || callbackInputs>256 || + live.backend.isEmpty() || live.capture.isEmpty() || + live.playback.isEmpty() || live.inputMask.isEmpty() || + live.outputMask.isEmpty() || !std::isfinite(live.rate) || + live.rate<8000. || live.rate>384000. || + live.frames<16 || live.frames>8192) + return "NEEDS_REMAP: live device verification incomplete"; + if(document.request.physicalInputs!=callbackInputs) + return "NEEDS_REMAP: active input count changed; reassign IN explicitly"; + for(const auto& source:document.request.sources) + if(source.inputL<0 || source.inputL>=callbackInputs || + (source.stereo && (source.inputR<0 || + source.inputR>=callbackInputs))) + return "NEEDS_REMAP: saved source patch exceeds active pins"; + if(sameBinding(document.binding,live) && + sameOutputs(document.outputs,outputs)) + return {}; + if(!operatorApproved) + return "NEEDS_REMAP: different device, pin mask, outputs or rate; confirm rebind"; + document.binding=live; + document.outputs=outputs; + return {}; + } +}; inline juce::String decimal(std::uint64_t value) { return juce::String(std::to_string(value)); } diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index e1afb9ce4..3687e3479 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -76,6 +76,31 @@ int main(){ assert(restored.request.sources[0].inputL==0); assert(restored.binding.backend=="ASIO"); assert(restored.outputs.mainR==1); + // Refuse unconfirmed or incompatible device remaps without mutating + // the saved ChannelId/EdgeId graph; accept only a verified live pair. + auto remap=d; + HardwareBinding replacement={"WASAPI","New capture","New playback", + "5","c",44100.,512}; + VerifiedNativeOutputs verifiedPair={2,1,0,-1,-1,false}; + const auto graphBefore=Codec::encode(remap); + auto refusal=MixerDeviceBindingPolicy::apply(remap,replacement, + verifiedPair,2,false); + assert(refusal.startsWith("NEEDS_REMAP")); + assert(Codec::encode(remap)==graphBefore); + refusal=MixerDeviceBindingPolicy::apply(remap,replacement, + verifiedPair,1,true); + assert(refusal.startsWith("NEEDS_REMAP")); + assert(Codec::encode(remap)==graphBefore); + assert(MixerDeviceBindingPolicy::apply(remap,replacement, + verifiedPair,2,true).isEmpty()); + assert(remap.binding.backend=="WASAPI" && remap.outputs.mainL==1); + assert(remap.roster.revision()==d.roster.revision()); + assert(remap.roster.find({1})->sends.size()==2 && + remap.roster.find({1})->sends[0].edgeId==100); + auto exact=d; + assert(MixerDeviceBindingPolicy::apply(exact,d.binding,d.outputs,2,false) + .isEmpty()); + assert(Codec::encode(exact)==graphBefore); ChannelEdit newChannel; newChannel.kind=ChannelEdit::Kind::add; newChannel.position=15;newChannel.role=ChannelRole::input; From 322bf11b12d0c2486e446323d337df9ced7fe5ac Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:47:47 +0700 Subject: [PATCH 203/219] ci: restore standard GUI workflow after verified double-click interaction FAT --- .github/workflows/ui-smoke.yml | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/.github/workflows/ui-smoke.yml b/.github/workflows/ui-smoke.yml index f4ffcee3e..6d2ff22f7 100644 --- a/.github/workflows/ui-smoke.yml +++ b/.github/workflows/ui-smoke.yml @@ -118,7 +118,7 @@ jobs: operator-ux-fat: name: Operator UX real Chromium / native-assembled GUI (5 viewports) needs: quick - if: ${{ github.event_name == 'pull_request' && (github.head_ref == 'fix/approved-operator-ux-20261107' || github.head_ref == 'fix/native-identity-double-click-20261107') }} + if: ${{ github.event_name == 'pull_request' && github.head_ref == 'fix/approved-operator-ux-20261107' }} runs-on: ubuntu-latest timeout-minutes: 15 steps: From 793ff3c920aff65e7b33cdd3d36370b07c8d0eac Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:50:36 +0700 Subject: [PATCH 204/219] feat(session): native one-use operator approval with fresh device and document signature --- src/Main.cpp | 135 +++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 130 insertions(+), 5 deletions(-) diff --git a/src/Main.cpp b/src/Main.cpp index 4c8be6bc4..38446c7f1 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -340,6 +340,31 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::String mixerSessionId_,mixerSessionStatus_="NO_SAVED_SESSION"; juce::String mixerSessionError_,lastMixerSessionFingerprint_; bool mixerSessionStartupInspected_=false; + struct PendingMixerRebind final { + juce::String nonce,signature; + juce::int64 expiresAt=0; + } pendingMixerRebind_; + // SHA binds the immutable persisted session to a specific verified + // physical device epoch, masks and output pair. Never a PCM authority. + static juce::String mixerRebindSignature( + const armix::session::MixerSessionDocument& doc, + const LiveAudioEngine::MixerBindingInspection& live) { + const auto& b=live.live; + const auto& o=live.outputs; + auto raw=armix::session::Codec::encode(doc)+ + "|device="+b.backend+"|capture="+b.capture+ + "|playback="+b.playback+"|input="+b.inputMask+ + "|output="+b.outputMask+"|rate="+juce::String(b.rate,3)+ + "|frames="+juce::String(b.frames)+ + "|inputs="+juce::String(live.callbackInputs)+ + "|epoch="+juce::String(std::to_string(live.epoch))+ + "|active="+juce::String(o.activeOutputChannels)+ + "|main="+juce::String(o.mainL)+","+juce::String(o.mainR)+ + "|monitor="+juce::String(o.monitorEnabled?1:0)+ + ","+juce::String(o.monitorL)+","+juce::String(o.monitorR); + return juce::SHA256(raw.toRawUTF8(),raw.getNumBytesAsUTF8()) + .toHexString(); + } bool nativeShowBusy_ = false; bool studioBackupBusy_ = false; std::unique_ptr chooser_; @@ -1802,9 +1827,75 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::var(ack.release())); } - // Called once immediately after startup and again only on user-directed - // restore. No implicit mapping to a different soundcard or active output. - juce::String restoreSavedMixerSession() { + // Read-only operator preview: no vendor instantiation, no graph publish, + // and no output authorization. Every source patch remains an ordinal. + void previewMixerDeviceRebind() { + auto ack=std::make_unique(); + juce::String error; + pendingMixerRebind_={}; + if(!engine_.allOutputsDisarmed()||mixerSessionWorker_.busy()|| + nativeShowBusy_||studioBackupBusy_||catalog_.busy()|| + engine_.isGraphSwitchPending()) + error="MUTE MAIN and STREAM, finish Studio IO before rebind"; + armix::session::MixerSessionDocument doc; + std::vector blobs; + if(error.isEmpty()) { + armix::session::NativeMixerSessionStore store(settingsDirectory()); + error=store.load(doc,blobs); + } + const auto live=engine_.status().getProperty("dryRoutingLab",{}); + if(error.isEmpty()&&static_cast( + live.getProperty("nativeChannelIdPcmActive",false))) + error="Live ChannelId mixer already active; refusing rebind"; + LiveAudioEngine::MixerBindingInspection inspected; + if(error.isEmpty()) + error=engine_.inspectNativeMixerSessionBinding(doc,inspected); + if(error.isEmpty()) { + const auto nonce=juce::Uuid().toDashedString().toLowerCase(); + pendingMixerRebind_={ + nonce,mixerRebindSignature(doc,inspected), + juce::Time::currentTimeMillis()+30000}; + auto encode=[](const armix::session::HardwareBinding& b) { + auto v=std::make_unique(); + v->setProperty("backend",b.backend); + v->setProperty("capture",b.capture); + v->setProperty("playback",b.playback); + v->setProperty("inputMask",b.inputMask); + v->setProperty("outputMask",b.outputMask); + v->setProperty("rate",b.rate); + v->setProperty("frames",b.frames); + return juce::var(v.release()); + }; + ack->setProperty("token",nonce); + ack->setProperty("saved",encode(doc.binding)); + ack->setProperty("current",encode(inspected.live)); + ack->setProperty("changed",inspected.changed); + ack->setProperty("inputs",inspected.callbackInputs); + ack->setProperty("savedMainL",doc.outputs.mainL); + ack->setProperty("savedMainR",doc.outputs.mainR); + ack->setProperty("currentMainL",inspected.outputs.mainL); + ack->setProperty("currentMainR",inspected.outputs.mainR); + ack->setProperty("currentMonitorEnabled",inspected.outputs.monitorEnabled); + juce::Array sources; + for(const auto& patch:doc.request.sources) { + auto v=std::make_unique(); + v->setProperty("channelId",armix::session::decimal(patch.id.value)); + v->setProperty("left",patch.inputL); + v->setProperty("right",patch.inputR); + v->setProperty("stereo",patch.stereo); + sources.add(juce::var(v.release())); + } + ack->setProperty("sources",juce::var(sources)); + } + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( + "arMixNativeSessionBindingAck",juce::var(ack.release())); + } + + // Startup and ordinary restore never authorize a different endpoint. + juce::String restoreSavedMixerSession(bool approvedRebind=false, + const juce::String& expectedStamp={}) { if(!engine_.allOutputsDisarmed() || mixerSessionWorker_.busy() || nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending()) return "MUTE output and finish Studio IO before restoring mixer"; @@ -1846,6 +1937,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return mixerSessionError_; } } + if(approvedRebind) { + LiveAudioEngine::MixerBindingInspection current; + error=engine_.inspectNativeMixerSessionBinding(doc,current); + if(error.isNotEmpty())return error; + if(expectedStamp.isEmpty() || + mixerRebindSignature(doc,current)!=expectedStamp) + return "STALE_REBIND: saved session or audio device changed"; + } // Existing live graphs cannot be replaced by startup autosave or // a stale More-button click. Never demote the true native renderer. const auto live=engine_.status().getProperty("dryRoutingLab",{}); @@ -1853,7 +1952,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; return "Live native mixer already active; refusing to replace it"; } - error=engine_.restoreNativeMixerSession(std::move(doc),states); + error=engine_.restoreNativeMixerSession( + std::move(doc),states,approvedRebind); if(error.isNotEmpty()) { mixerSessionStatus_=error.contains("NEEDS_REMAP") ?"NEEDS_REMAP":"RESTORE_REJECTED"; @@ -1861,9 +1961,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr diagnostics_.record("DYNAMIC_MIXER_RESTORE_REJECTED",error); return error; } - mixerSessionStatus_="RESTORED_MUTED"; + mixerSessionStatus_=approvedRebind?"RESTORED_REBOUND_MUTED":"RESTORED_MUTED"; mixerSessionError_.clear(); diagnostics_.record("DYNAMIC_MIXER_RESTORED", + approvedRebind? + "Operator-approved hardware mapping; ChannelId/WIRE/VST3 retained, outputs DISARMED": "Exact native ChannelId/WIRE/VST3; outputs remain DISARMED"); emitApprovedNativeSnapshot(); return {}; @@ -2717,6 +2819,29 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr mixerSessionStatus_=="DAMAGED_SESSION"?mixerSessionError_:juce::String{}); return; } + if(action=="nativeSessionInspectRebind") { + previewMixerDeviceRebind(); + return; + } + if(action=="nativeSessionRebind") { + // The one-use token is consumed even on failure. Revalidate the + // entire saved document and live device just before publication. + const auto approved=pendingMixerRebind_; + pendingMixerRebind_={}; + juce::String result; + if(!value.isString() || approved.nonce.isEmpty() || + value.toString()!=approved.nonce || + juce::Time::currentTimeMillis()>approved.expiresAt) + result="STALE_REBIND: request expired or not confirmed"; + else result=restoreSavedMixerSession(true,approved.signature); + if(result.isNotEmpty()) { + mixerSessionStatus_="REBIND_REJECTED"; + mixerSessionError_=result; + emitNotice("MIXER SESSION: "+result,true); + } + emitMixerSessionAck("REBIND",result); + return; + } if(action=="nativeSessionSave" || action=="nativeSessionRestore" || action=="nativeSessionRecover") { juce::String result; From 10d4a56d510de414189e5e4ebceb73fbec1ce4e0 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:51:09 +0700 Subject: [PATCH 205/219] feat(session-ui): preview old/current hardware pin bindings and confirm muted rebind --- web/approved-native-bridge.js | 39 ++++++++++++++++++++++++++++++++--- 1 file changed, 36 insertions(+), 3 deletions(-) diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 38ef97fb8..7b87a2371 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -1807,6 +1807,7 @@ "STUDIO / COMPLETE MIXER SESSION"); const sessionSave=item("button","tool","Save Mixer Session"); const sessionRestore=item("button","tool","Restore Saved Mixer"); + const sessionRebind=item("button","tool","Rebind Current Device…"); const sessionRecover=item("button","tool","Recover Previous Mixer"); const sessionState=item("span","more-tools-caption", "Checking native ChannelId session…"); @@ -1825,7 +1826,39 @@ }; sessionSave.addEventListener("click",()=>sessionAction("nativeSessionSave")); sessionRestore.addEventListener("click",()=>sessionAction("nativeSessionRestore")); + sessionRebind.addEventListener("click",()=>sessionAction("nativeSessionInspectRebind")); sessionRecover.addEventListener("click",()=>sessionAction("nativeSessionRecover")); + backend.addEventListener("arMixNativeSessionBindingAck",ack=>{ + if(ack?.ok!==true||typeof ack.token!=="string"){ + sessionState.textContent="REBIND REJECTED · "+ + String(ack?.error||"No native hardware readback"); + status(sessionState.textContent);return; + } + const saved=ack.saved||{},live=ack.current||{}; + const describe=b=>String(b.backend||"?")+" · "+String(b.capture||"?")+ + " → "+String(b.playback||"?")+" · IN 0x"+String(b.inputMask||"?")+ + " / OUT 0x"+String(b.outputMask||"?")+" · "+String(b.rate||"?")+" Hz"; + const sources=Array.isArray(ack.sources)?ack.sources:[]; + const pins=sources.slice(0,12).map(s=>"CH "+s.channelId+" ← "+ + "IN "+(Number(s.left)+1)+(s.stereo?"/"+(Number(s.right)+1):"")).join("\n"); + const message="REBIND SAVED MIXER TO CURRENT PHYSICAL DEVICE?\n\n"+ + "Saved: "+describe(saved)+"\n\nCurrent: "+describe(live)+ + "\nCurrent MAIN output pair (callback ordinals): "+ + (Number(ack.currentMainL)+1)+"/"+(Number(ack.currentMainR)+1)+ + "\nSaved MAIN pair: "+(Number(ack.savedMainL)+1)+"/"+ + (Number(ack.savedMainR)+1)+ + "\nInput callback pins: "+String(ack.inputs)+ + "\n\nSaved sources keep these callback ordinal assignments:"+ + (pins?"\n"+pins:"\nNo physical sources")+ + (sources.length>12?"\n…plus "+(sources.length-12)+" more sources":"")+ + "\n\nVERIFY actual ASIO/WASAPI pin wiring and the MAIN output pair."+ + "\nChannelIds, GROUP/WIRE and FX are retained. Physical output stays MUTED."+ + "\nSave Mixer Session after verifying the new binding. Continue?"; + if(window.confirm(message)){ + backend.emitEvent("arMixAction",{action:"nativeSessionRebind",value:ack.token}); + sessionState.textContent="Verifying unchanged hardware and reconstructing native FX…"; + }else sessionState.textContent="Rebind cancelled · current mixer untouched"; + }); backend.addEventListener("arMixNativeSessionAck",ack=>{ const state=String(ack?.state||"UNAVAILABLE"); sessionState.textContent=state+(ack?.error?" · "+String(ack.error):""); @@ -1833,8 +1866,8 @@ if(ack?.ok===true){ status(ack.operation==="SAVE"? "Verified native MixerSession written; output remains MUTED": - ack.operation==="RESTORE"? - "Mixer Session restored; inspect routing then explicitly enable MONITOR": + (ack.operation==="RESTORE"||ack.operation==="REBIND")? + "Mixer Session restored MUTED; verify physical pins and explicitly enable MONITOR": "Previous MixerSession generation recovered on disk; RESTORE explicitly"); controller?.subscribe(); }else{ @@ -1850,7 +1883,7 @@ }); menu.append(caption,setup,muteBtn,hardwareNote, healthTitle,mark,report,advanced, - sessionHeading,sessionSave,sessionRestore,sessionRecover,sessionState, + sessionHeading,sessionSave,sessionRestore,sessionRebind,sessionRecover,sessionState, showHeading,showSave,showBrowse,showSelect,showUpdate,showRecall,showRecover,showNote); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. From f7e64553e7098130c4071338ab4c17cf9bcfd800 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 16:51:29 +0700 Subject: [PATCH 206/219] test(session): emulate confirmation and cancellation for native hardware rebind without monitor arm --- tests/approved_native_cold_start_smoke.py | 28 +++++++++++++++++++++++ 1 file changed, 28 insertions(+) diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index 3c5c56550..79fcf48aa 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -79,6 +79,34 @@ def show_select(value): "operation":"RESTORE","ok":False,"state":"NEEDS_REMAP", "error":"NEEDS_REMAP: physical ASIO input mask changed"}) assert "NEEDS_REMAP" in page.locator(show_panel).text_content() + # Native device rebind requires an explicit preview and dialog. + # Cancelling must NOT send a rebind intent to the JUCE dispatcher. + show_click("Rebind Current Device…") + assert page.evaluate("()=>window.__events.at(-1).payload.action")==\ + "nativeSessionInspectRebind" + preview={"ok":True,"token":"test-one-time-approval", + "saved":{"backend":"ASIO","capture":"Old","playback":"Old", + "inputMask":"3","outputMask":"3","rate":48000}, + "current":{"backend":"WASAPI","capture":"New","playback":"New", + "inputMask":"5","outputMask":"3","rate":44100}, + "inputs":2,"savedMainL":0,"savedMainR":1, + "currentMainL":1,"currentMainR":0, + "sources":[{"channelId":"1","left":0,"right":-1,"stereo":False}]} + page.once("dialog",lambda dialog:dialog.dismiss()) + emit(page,"arMixNativeSessionBindingAck",preview) + assert page.evaluate("()=>window.__events.at(-1).payload.action")==\ + "nativeSessionInspectRebind" + show_click("Rebind Current Device…") + page.once("dialog",lambda dialog:dialog.accept()) + emit(page,"arMixNativeSessionBindingAck",preview) + assert page.evaluate("()=>window.__events.at(-1).payload")=={ + "action":"nativeSessionRebind","value":"test-one-time-approval"} + emit(page,"arMixNativeSessionAck",{ + "operation":"REBIND","ok":True,"state":"RESTORED_REBOUND_MUTED"}) + assert "RESTORED_REBOUND_MUTED" in page.locator(show_panel).text_content() + # Rebind path never triggers an implicit monitor/stream ARM. + assert not page.evaluate( + "()=>window.__events.some(e=>e.payload?.action==='monitor')") show_click("Recover Previous Mixer") assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeSessionRecover" emit(page,"arMixNativeSessionAck",{ From afd40cf3bbfa0e3f8cf26177aa876cd577de7e4c Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 17:03:57 +0700 Subject: [PATCH 207/219] fix(identity): native durable ChannelId appearance with ACK-backed DAW double-click editor --- CMakeLists.txt | 8 + src/Main.cpp | 37 +++ src/NativeChannelAppearanceStore.h | 214 ++++++++++++++++++ ...roved_operator_ux_native_identity_smoke.py | 153 +++++++------ tests/approved_operator_ux_smoke.py | 12 +- .../native_channel_appearance_store_test.cpp | 104 +++++++++ web/approved-native-bridge.js | 141 ++++++++---- 7 files changed, 556 insertions(+), 113 deletions(-) create mode 100644 src/NativeChannelAppearanceStore.h create mode 100644 tests/native_channel_appearance_store_test.cpp diff --git a/CMakeLists.txt b/CMakeLists.txt index bf964b1ff..ce647cf6c 100644 --- a/CMakeLists.txt +++ b/CMakeLists.txt @@ -340,6 +340,14 @@ if(BUILD_TESTING) juce::juce_audio_processors juce::juce_cryptography juce::juce_recommended_config_flags) target_compile_features(ARMixDurableMixerSessionTests PRIVATE cxx_std_20) add_test(NAME P0DynamicMixerSessionDocumentAndCrashSafeRecovery COMMAND ARMixDurableMixerSessionTests) + # Presentation-only native identity; no audio-thread access. + juce_add_console_app(ARMixChannelAppearanceTests PRODUCT_NAME "ArSonMix Channel Appearance Tests") + target_sources(ARMixChannelAppearanceTests PRIVATE + tests/native_channel_appearance_store_test.cpp src/NativeChannelAppearanceStore.h) + target_link_libraries(ARMixChannelAppearanceTests PRIVATE + juce::juce_core juce::juce_recommended_config_flags) + target_compile_features(ARMixChannelAppearanceTests PRIVATE cxx_std_20) + add_test(NAME NativeChannelIdentityDiskAckAndExactId COMMAND ARMixChannelAppearanceTests) # Eight-band native PEQ: deterministic sweep, stereo isolation, RT no-heap, # smoothing and Nyquist guards. Built with the existing Windows native lane. diff --git a/src/Main.cpp b/src/Main.cpp index 38446c7f1..4d6e25c2d 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -33,6 +33,7 @@ #include "NativeLiveShowCapture.h" #include "NativeDryShowRecall.h" #include "NativeShowSaveWorker.h" +#include "NativeChannelAppearanceStore.h" #include "NativeMixerSessionSaveWorker.h" #include #include @@ -233,6 +234,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr browser_.repaint(); if (onStartupStage_) onStartupStage_ (1); }) + .withEventListener ("arMixChannelIdentitySet", [this] (juce::var args) { + handleNativeChannelIdentitySet(args); + }) .withEventListener ("arMixConsoleSubscribe", [this] (juce::var) { // G0 real-device native producer, NEVER a synthetic ChannelId callback. consoleSubscribed_ = true; @@ -331,6 +335,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::int64 fxGraphRevision_ = 1; // control-thread monotonic graph generation PluginCatalog catalog_; DiagnosticsRecorder diagnostics_; + armix::appearance::Store channelAppearance_{settingsDirectory()}; armix::storage::NativePresetArchive presets_; std::function onStartupStage_; Browser browser_; @@ -387,6 +392,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr bool initialStateSent_ = false; bool consoleSubscribed_ = false; // Real snapshot subscription; not FAT certification juce::StringArray acceptedControlRequests_; // bounded request replay fence + juce::StringArray acceptedAppearanceRequests_; // identity request replay fence bool webViewPeerWarmed_ = false; bool webViewStartupNoticeSent_ = false; juce::uint32 webViewStartupTick_ = 0; @@ -954,6 +960,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr (void) armix::console::projectRetainedNativeChannelIdGraph (accepted, live); // Sole control-thread SessionSnapshot from the installed PCM publisher. armix::console::publishAuthoritativeMixerSession(accepted); + if(auto* obj=accepted.getDynamicObject()) + obj->setProperty("channelAppearance",channelAppearance_.snapshot(accepted.getProperty("graph",{}))); return accepted; } @@ -969,6 +977,35 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr "arMixConsoleSnapshot", approvedNativeSnapshot()); } + // UI-only native transaction. No PCM mutation; never arm an output. + void handleNativeChannelIdentitySet(const juce::var& request) + { + const auto v=request.getProperty("requestId",{}); + const auto id=v.isString()?v.toString():juce::String{}; + juce::String error; + if(id.isEmpty()||id.length()>120) + error="INVALID_CHANNEL_APPEARANCE_REQUEST_ID"; + else if(acceptedAppearanceRequests_.contains(id)) + error="DUPLICATE_CHANNEL_APPEARANCE_REQUEST_ID"; + else { + acceptedAppearanceRequests_.add(id); + if(acceptedAppearanceRequests_.size()>256) + acceptedAppearanceRequests_.remove(0); + error=channelAppearance_.apply(request,approvedNativeSnapshot()); + } + auto ack=std::make_unique(); + ack->setProperty("requestId",id); + ack->setProperty("ok",error.isEmpty()); + ack->setProperty("error",error); + if(browser_.loaded) + browser_.emitEventIfBrowserIsVisible("arMixChannelIdentityAck",juce::var(ack.release())); + if(error.isEmpty()) { + diagnostics_.record("NATIVE_CHANNEL_APPEARANCE_SAVED", + request.getProperty("channelId","").toString()); + emitApprovedNativeSnapshot(); + } else diagnostics_.record("NATIVE_CHANNEL_APPEARANCE_REJECTED",error); + } + // One native dispatcher; the source of truth is the already installed // ENGINE callback. This code executes on the JUCE message thread, not RT. void handleApprovedNativeControl(const juce::var& request) diff --git a/src/NativeChannelAppearanceStore.h b/src/NativeChannelAppearanceStore.h new file mode 100644 index 000000000..3a3a60de4 --- /dev/null +++ b/src/NativeChannelAppearanceStore.h @@ -0,0 +1,214 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#pragma once +#include +#include +#include +#include +#include +#include + +// Durable UI identity, not DSP topology. The accepted native ChannelId is the +// address; rename/color/icon never rebuild PCM or touch a realtime callback. +// Disk IO is only performed on the JUCE message thread, never on the audio +// thread. Fail closed on an invalid existing document (no silent overwrite). +namespace armix::appearance { +class Store final { +public: + explicit Store(juce::File directory) + : file_(directory.getChildFile("channel-appearance.v1.json")) + { load(); } + + struct Entry final {juce::String name,color,icon;}; + juce::String error() const {return loadError_;} + static bool decimal(const juce::var& input,std::uint64_t& value,bool zero=false) { + if(!input.isString())return false; + const auto text=input.toString().toStdString(); + if(text.empty()||text.size()>20||(text.size()>1&&text[0]=='0'))return false; + std::uint64_t next=0; + auto [end,err]=std::from_chars(text.data(),text.data()+text.size(),next); + if(err!=std::errc{}||end!=text.data()+text.size()||(!zero&&!next))return false; + value=next;return true; + } + static bool validName(const juce::String& name) { + const auto utf8=name.toStdString(); + if(name.isEmpty()||name!=name.trim()||name.length()>30||utf8.size()>96)return false; + for(auto ch:utf8)if(static_cast(ch)<32||ch==127)return false; + return true; + } + static bool validColor(const juce::String& color) { + if(color.length()!=7||color[0]!='#')return false; + for(int i=1;i<7;++i){ + auto c=color[i]; + if(!((c>='0'&&c<='9')||(c>='a'&&c<='f')||(c>='A'&&c<='F')))return false; + } + return true; + } + static bool validIcon(const juce::String& icon) { + return icon=="♩"||icon=="♫"||icon=="♬"||icon=="🎙"|| + icon=="🎸"||icon=="🎹"||icon=="🥁"||icon=="🎧"|| + icon=="▥"||icon=="◉"||icon=="◎"||icon=="⊞"; + } + + // Only the accepted control-thread graph may authorize a ChannelId edit. + // No ChannelId JS Number, no ordinal alias and no stale hardware epoch. + juce::String apply(const juce::var& request,const juce::var& accepted) { + if(loadError_.isNotEmpty())return loadError_; + const auto graph=accepted.getProperty("graph",{}); + const auto device=accepted.getProperty("device",{}); + const auto channels=graph.getProperty("channels",{}); + if(!channels.isArray())return "NO_NATIVE_CHANNEL_GRAPH"; + const auto caps=graph.getProperty("capabilities",{}); + const auto session=accepted.getProperty("mixerSession",{}); + if(session.getProperty("authority","").toString()!="CHANNEL_ID"|| + !(static_cast(caps.getProperty("callbackOwnsChannelIds",false))|| + graph.getProperty("bindingState","").toString()=="NEEDS_REMAP")) + return "NATIVE_CHANNEL_GRAPH_NOT_ACCEPTED"; + std::uint64_t channel=0,epoch=0,rev=0,roster=0,appearanceRev=0; + const auto id=request.getProperty("channelId",{}); + if(!decimal(id,channel)|| + !decimal(request.getProperty("deviceEpoch",{}),epoch,true)|| + !decimal(request.getProperty("graphRevision",{}),rev,true)|| + !decimal(request.getProperty("rosterRevision",{}),roster,true)|| + !decimal(request.getProperty("appearanceRevision",{}),appearanceRev,true)|| + epoch==0||rev==0||roster==0|| + device.getProperty("epoch","").toString()!=juce::String(std::to_string(epoch))|| + graph.getProperty("revision","").toString()!=juce::String(std::to_string(rev))|| + graph.getProperty("rosterRevision","").toString()!=juce::String(std::to_string(roster))) + return "STALE_CHANNEL_IDENTITY_OR_GRAPH"; + if(appearanceRev!=revision_)return "STALE_CHANNEL_APPEARANCE_REVISION"; + const auto nameVar=request.getProperty("name",{}); + const auto colorVar=request.getProperty("color",{}); + const auto iconVar=request.getProperty("icon",{}); + if(!nameVar.isString()||!colorVar.isString()||!iconVar.isString()) + return "INVALID_CHANNEL_APPEARANCE_FIELDS"; + const Entry next{nameVar.toString(),colorVar.toString(),iconVar.toString()}; + if(!validName(next.name)||!validColor(next.color)||!validIcon(next.icon)) + return "INVALID_CHANNEL_NAME_COLOR_OR_ICON"; + bool found=false; + const auto idText=id.toString(); + for(const auto& row:*channels.getArray()) { + const auto rowId=row.getProperty("id",{}); + if(!rowId.isString())return "INVALID_NATIVE_ROSTER"; + if(rowId.toString()==idText){found=true;continue;} + const auto it=entries_.find(rowId.toString().toStdString()); + const auto other=it==entries_.end()?row.getProperty("name","").toString():it->second.name; + if(next.name.equalsIgnoreCase(other)) + return "CHANNEL_NAME_ALREADY_IN_USE"; + } + if(!found)return "CHANNEL_NOT_IN_NATIVE_ROSTER"; + const auto key=idText.toStdString(); + const auto existing=entries_.find(key); + if(existing!=entries_.end() && existing->second.name==next.name && + existing->second.color==next.color && existing->second.icon==next.icon) + return {}; // idempotent; no flash, no unnecessary disk IO + if(entries_.size()>=512&&existing==entries_.end()) + return "CHANNEL_APPEARANCE_LIMIT"; + if(revision_==std::numeric_limits::max()) + return "CHANNEL_APPEARANCE_REVISION_EXHAUSTED"; + auto candidate=entries_;candidate[key]=next; + const auto writeError=commit(candidate,revision_+1); + if(writeError.isNotEmpty())return writeError; + entries_.swap(candidate);++revision_; + return {}; + } + + juce::var snapshot(const juce::var& graph) const { + auto root=std::make_unique(); + root->setProperty("schema","arsonmix.native.channel-appearance.v1"); + root->setProperty("revision",juce::String(std::to_string(revision_))); + root->setProperty("readOnly",loadError_.isNotEmpty()); + juce::Array rows; + const auto channels=graph.getProperty("channels",{}); + if(const auto* live=channels.getArray()){ + for(const auto& ch:*live){ + const auto id=ch.getProperty("id",{}).toString(); + const auto found=entries_.find(id.toStdString()); + if(found==entries_.end())continue; + auto row=std::make_unique(); + row->setProperty("id",id); + row->setProperty("name",found->second.name); + row->setProperty("color",found->second.color); + row->setProperty("icon",found->second.icon); + rows.add(juce::var(row.release())); + } + } + root->setProperty("entries",juce::var(rows)); + return juce::var(root.release()); + } + +private: + juce::File file_; + std::map entries_; + std::uint64_t revision_=0; + juce::String loadError_; + + static juce::var encode(const std::map& entries, + std::uint64_t revision) { + auto root=std::make_unique(); + root->setProperty("schema","arsonmix.native.channel-appearance.v1"); + root->setProperty("revision",juce::String(std::to_string(revision))); + juce::Array rows; + for(const auto& [key,entry]:entries) { + auto item=std::make_unique(); + item->setProperty("id",juce::String(key)); + item->setProperty("name",entry.name); + item->setProperty("color",entry.color); + item->setProperty("icon",entry.icon); + rows.add(juce::var(item.release())); + } + root->setProperty("entries",juce::var(rows)); + return juce::var(root.release()); + } + juce::String commit(const std::map& candidate, + std::uint64_t revision) const { + const auto directory=file_.getParentDirectory(); + if(!directory.isDirectory()&&directory.createDirectory().failed()) + return "CANNOT_CREATE_CHANNEL_APPEARANCE_DIRECTORY"; + const auto json=juce::JSON::toString(encode(candidate,revision),false); + if(json.getNumBytesAsUTF8()>128*1024) + return "CHANNEL_APPEARANCE_DOCUMENT_TOO_LARGE"; + juce::TemporaryFile temp(file_); + auto output=temp.getFile().createOutputStream(); + if(!output||!output->writeText(json,false,false,"\n")) + return "CANNOT_STAGE_CHANNEL_APPEARANCE"; + output->flush(); + if(output->getStatus().failed())return "CANNOT_FLUSH_CHANNEL_APPEARANCE"; + output.reset(); + if(!temp.overwriteTargetFileWithTemporary()) + return "CANNOT_ATOMICALLY_COMMIT_CHANNEL_APPEARANCE"; + return {}; + } + void load() { + if(!file_.exists())return; + if(!file_.existsAsFile()||file_.getSize()<1||file_.getSize()>128*1024){ + loadError_="CHANNEL_APPEARANCE_FILE_INVALID";return; + } + const auto root=juce::JSON::parse(file_.loadFileAsString()); + if(!root.isObject()||root.getProperty("schema","").toString()!="arsonmix.native.channel-appearance.v1"){ + loadError_="CHANNEL_APPEARANCE_SCHEMA_INVALID";return; + } + const auto data=root.getProperty("entries",{}); + std::uint64_t revision=0; + if(!decimal(root.getProperty("revision",{}),revision,true)||!data.isArray()|| + data.getArray()->size()>512){ + loadError_="CHANNEL_APPEARANCE_CONTENT_INVALID";return; + } + std::map candidate; + for(const auto& item:*data.getArray()) { + const auto id=item.getProperty("id",{}); + const auto name=item.getProperty("name",{}); + const auto color=item.getProperty("color",{}); + const auto icon=item.getProperty("icon",{}); + std::uint64_t n=0; + if(!decimal(id,n)||!name.isString()||!color.isString()||!icon.isString()|| + !validName(name.toString())||!validColor(color.toString())|| + !validIcon(icon.toString())|| + !candidate.emplace(id.toString().toStdString(), + Entry{name.toString(),color.toString(),icon.toString()}).second) { + loadError_="CHANNEL_APPEARANCE_ENTRY_INVALID";return; + } + } + entries_.swap(candidate);revision_=revision; + } +}; +} // namespace armix::appearance diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py index 64510bee9..9676ca389 100644 --- a/tests/approved_operator_ux_native_identity_smoke.py +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -1,8 +1,8 @@ -"""Native channel identity end-to-end: Chromium + emulated JUCE metadata only. +"""Actual compiled native Pages UI: channel identity requires disk-backed host ACK. -Source of truth for PCM/WIRE is the admitted ChannelId graph. A user-facing -alias must not create any synthetic graph intents, survive snapshot readback -and WebView reload, or rename the immutable native ChannelId. +No optimistic JS rename, no localStorage source of authority, no synthetic +PCM graph operation. C++ NativeChannelAppearanceStore CTest independently +proves durable disk/lease validation and guards corruption/restart. """ from pathlib import Path import tempfile @@ -12,11 +12,11 @@ from approved_native_wire_gain_smoke import snapshot, emit, SOURCE, RECEIVER ROOT=Path(__file__).resolve().parents[1] -sys.path.insert(0,str(ROOT/'scripts')) +sys.path.insert(0,str(ROOT/"scripts")) import build_approved_native_gui as bundle def main(): - with tempfile.TemporaryDirectory(prefix="armix-native-alias-") as temp, sync_playwright() as p: + with tempfile.TemporaryDirectory(prefix="armix-native-identity-") as temp, sync_playwright() as p: out=Path(temp)/"native" bundle.stage(out) browser=p.chromium.launch(headless=True) @@ -24,91 +24,110 @@ def main(): errors=[] def open_page(): page=context.new_page() - page.on('pageerror',lambda e:errors.append(str(e))) + page.on("pageerror",lambda e:errors.append(str(e))) page.add_init_script("""window.__nativeListeners=new Map();window.__nativeIntents=[];window.__nativeEvents=[]; window.__JUCE__={backend:{ - emitEvent(name,payload){window.__nativeEvents.push({name,payload});if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, + emitEvent(name,payload){window.__nativeEvents.push({name,payload}); + if(name==='arMixConsoleIntent')window.__nativeIntents.push(payload);}, addEventListener(name,callback){window.__nativeListeners.set(name,callback);}}};""") - page.goto((out/'index.html').as_uri()) - page.wait_for_function('()=>window.__ARMIX_NATIVE_M2__?.enabled') + page.goto((out/"index.html").as_uri()) + page.wait_for_function("()=>window.__ARMIX_NATIVE_M2__?.enabled") return page state=snapshot() + appearance={"schema":"arsonmix.native.channel-appearance.v1", + "revision":"0","readOnly":False,"entries":[]} + state["channelAppearance"]=appearance page=open_page() ready=page.evaluate("()=>window.__nativeEvents.find(e=>e.name==='arMixGuiReady')?.payload") - assert ready and ready['viewportWidth']==1366 and ready['viewportHeight']==768 - # Never show demo-only controls as clickable on a physical host. - for id in ('saveScene','recallScene','copy','paste','group','ungroup','preview','clearCue','reset','sofToggle','sofTarget'): - element=page.locator('#'+id) - assert element.is_hidden() and element.is_disabled(),id - assert page.locator('[data-native-monitor]').count()==1 - assert page.locator('#pluginsButton').is_visible() - assert page.locator('#wireNavigatorToggle').is_visible() + assert ready and ready["viewportWidth"]==1366 and ready["viewportHeight"]==768 + # No unimplemented native functionality advertised as a working action. + for id in ("saveScene","recallScene","copy","paste","group","ungroup", + "preview","clearCue","reset","sofToggle","sofTarget"): + el=page.locator("#"+id) + assert el.is_hidden() and el.is_disabled(),id + assert page.locator("#pluginsButton").is_visible() emit(page,"arMixConsoleSnapshot",state) - page.wait_for_selector('#tracks .strip[data-id="1"]') - # DAW convention: single click selects channel; only double-click - # on its header/footer opens the name/color/icon editor. - page.locator('#tracks .strip[data-id="1"] .strip-identity-top').click() - editor=page.locator('#channelIdentity') - assert editor.is_hidden(),"single-click must only select the channel" - page.locator('#tracks .strip[data-id="1"] .strip-identity-top').dblclick() - assert editor.is_visible(),"double-click on header did not open editor" - assert page.locator('#identityName').evaluate("el=>el===document.activeElement") - page.locator('#identityName').fill("Discard this") - page.locator('#identityCancel').click() - assert editor.is_hidden(),"Cancel must dismiss without modifying the channel" - assert "Discard this" not in page.locator('#tracks .strip[data-id="1"]').inner_text() - # Footer name follows the same single-select/double-edit contract. - page.locator('#tracks .strip[data-id="1"] .footer-label .name').click() - assert editor.is_hidden(),"single-click on footer name opened editor" - page.locator('#tracks .strip[data-id="1"] .footer-label .name').dblclick() - assert editor.is_visible(),"footer double-click did not open editor" - page.locator('#identityName').fill("Studio Vox") + strip=page.locator('#tracks .strip[data-id="1"]') + strip.wait_for(state="visible") + # Native DAW convention: one click selects, double-click opens editor. + strip.locator(".strip-identity-top").click() + editor=page.locator("#channelIdentity") + assert editor.is_hidden(),"single click should only select" + strip.locator(".strip-identity-top").dblclick() + assert editor.is_visible(),"double-click header should edit" + page.locator("#identityName").fill("Studio Vox") color="#c32974" page.locator(f'#identityColors [data-identity-color="{color}"]').click() icon="🎹" page.locator(f'#identityIcons [data-identity-icon="{icon}"]').click() - page.locator('#identitySave').click() - assert editor.is_hidden() - assert page.locator('#tracks .strip[data-id="1"]').inner_text().find("Studio Vox")>=0 - alias=page.evaluate("()=>JSON.parse(localStorage.getItem('arsonmix.native.channel-presentation.v1'))") - assert alias["channels"][SOURCE]["name"]=="Studio Vox",alias - assert alias["channels"][SOURCE]["color"]==color - assert alias["channels"][SOURCE]["icon"]==icon - assert page.evaluate("()=>window.__nativeIntents.length")==0,\ - "display-only edit emitted an unauthorized PCM/route intent" - # No native server alias or ChannelId mutation: same authoritative - # snapshot retains its original name and exact ID. - assert state['graph']['channels'][0]['id']==SOURCE - assert state['graph']['channels'][0]['name']=='CH03' + page.locator("#identitySave").click() + assert editor.is_visible(),"native identity edited before ACK" + assert "Studio Vox" not in strip.inner_text(),"optimistic rename without native evidence" + req=page.evaluate("""()=>window.__nativeEvents.filter(e=> + e.name==='arMixChannelIdentitySet').at(-1)?.payload""") + assert req and req["channelId"]==SOURCE,req + assert req["appearanceRevision"]=="0" and req["name"]=="Studio Vox" + assert req["color"]==color and req["icon"]==icon + assert page.locator("#identitySave").is_disabled() + assert page.evaluate("()=>window.__nativeIntents.length")==0 + + # Bad/stale native ACK: editor remains open and value stays untouched. + emit(page,"arMixChannelIdentityAck", + {"requestId":req["requestId"],"ok":False, + "error":"STALE_CHANNEL_APPEARANCE_REVISION"}) + assert editor.is_visible() + assert page.locator("#identitySave").is_enabled() + assert "Studio Vox" not in strip.inner_text() + # Retry after a fresh accepted snapshot. emit(page,"arMixConsoleSnapshot",state) - assert "Studio Vox" in page.locator('#tracks .strip[data-id="1"]').inner_text() + page.locator("#identitySave").click() + req=page.evaluate("""()=>window.__nativeEvents.filter(e=> + e.name==='arMixChannelIdentitySet').at(-1)?.payload""") + emit(page,"arMixChannelIdentityAck", + {"requestId":req["requestId"],"ok":True,"error":""}) + # ACK alone MUST NOT rename or close the editor. + assert editor.is_visible() + assert "Studio Vox" not in strip.inner_text() + appearance["revision"]="1" + appearance["entries"]=[{"id":SOURCE,"name":"Studio Vox","color":color,"icon":icon}] + emit(page,"arMixConsoleSnapshot",copy.deepcopy(state)) + page.wait_for_function("""()=>document.querySelector('#channelIdentity').hidden && + document.querySelector('#tracks .strip[data-id="1"]').textContent.includes('Studio Vox')""",timeout=5000) assert page.evaluate("()=>window.__nativeIntents.length")==0 - # New WebView document, same browser profile: alias survives. + assert page.evaluate("()=>localStorage.getItem('arsonmix.native.channel-presentation.v1')") is None + + # A second channel cannot take an existing visible name; rejected + # locally AND independently by the native store's CTest. + other=page.locator('#tracks .strip[data-id="2"]') + other.locator(".footer-label .name").click() + assert editor.is_hidden(),"footer single-click should only select" + other.locator(".footer-label .name").dblclick() + page.locator("#identityName").fill("Studio Vox") + before=page.evaluate("()=>window.__nativeEvents.filter(e=>e.name==='arMixChannelIdentitySet').length") + page.locator("#identitySave").click() + after=page.evaluate("()=>window.__nativeEvents.filter(e=>e.name==='arMixChannelIdentitySet').length") + assert before==after and editor.is_visible() + page.locator("#identityCancel").click() + assert editor.is_hidden() + # Restore the WebView from the same durable *native* snapshot, with + # no shared JS localStorage or reconstructed PCM graph. page.close() page=open_page() - emit(page,"arMixConsoleSnapshot",state) + emit(page,"arMixConsoleSnapshot",copy.deepcopy(state)) page.wait_for_selector('#tracks .strip[data-id="1"]') assert "Studio Vox" in page.locator('#tracks .strip[data-id="1"]').inner_text() - # Keyboard F2 edits the selected loaded channel; Enter on focused - # footer name is accessible when using keyboard-only navigation. page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() - assert page.locator('#channelIdentity').is_hidden() page.keyboard.press('F2') - assert page.locator('#channelIdentity').is_visible(),"F2 edit not available" - page.locator('#identityName').fill('Studio Vox') - page.locator('#identitySave').click() - assert page.locator('#channelIdentity').is_visible(),\ - "duplicate visible channel names should not silently collide" - page.locator('#identityClose').click() + assert editor.is_visible(),"F2 should open editor" + page.locator('#identityCancel').click() page.locator('#tracks .strip[data-id="2"] .footer-label .name').focus() page.keyboard.press('Enter') - assert page.locator('#channelIdentity').is_visible(),"keyboard Enter did not open editor" + assert editor.is_visible(),"Enter should open editor" page.keyboard.press('Escape') - assert page.locator('#channelIdentity').is_hidden() + assert editor.is_hidden() assert page.evaluate("()=>window.__nativeIntents.length")==0 assert not errors,errors - page.close() - context.close();browser.close() - print("PASS native identity: single-click selects; double-click header/footer edits; F2/Enter, Cancel/Escape, name/icon/color, reload, duplicate reject, exact ChannelId, zero PCM intents") + page.close();context.close();browser.close() + print("PASS native identity click/ACK/readback/reject/restart with zero PCM graph intents") if __name__=="__main__":main() diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index a86d2495f..87d7b7c31 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -70,10 +70,16 @@ def test_native_hooks_and_audio_input_default(self): self.assertIn("openNativeIdentity(t,event.target)",bridge) self.assertIn('event.key!=="F2"',bridge) self.assertIn("identityChannelFor=t=>",bridge) - self.assertIn("Channel identity saved",bridge) + self.assertIn("Channel updated and stored in native workspace",bridge) self.assertIn("channelIcons:CHANNEL_ICONS",build) - self.assertIn("const identityStoreKey=",bridge) - self.assertIn("channelPresentation.set(nativeId",bridge) + self.assertIn("appearanceFromNative(next)",bridge) + self.assertIn("arMixChannelIdentitySet",bridge) + self.assertIn("arMixChannelIdentityAck",bridge) + self.assertNotIn("arsonmix.native.channel-presentation.v1",bridge) + appearance=(ROOT/"src/NativeChannelAppearanceStore.h").read_text(encoding="utf-8") + self.assertIn("CANNOT_ATOMICALLY_COMMIT_CHANNEL_APPEARANCE",appearance) + self.assertIn("STALE_CHANNEL_APPEARANCE_REVISION",appearance) + self.assertIn("CHANNEL_NAME_ALREADY_IN_USE",appearance) self.assertIn("deviceManager_.initialise (2, 2, savedSettings, !savedRoute)",engine) self.assertIn("active.enabledInputs",bridge) self.assertIn("data-audio-asio4all-hint",bridge) diff --git a/tests/native_channel_appearance_store_test.cpp b/tests/native_channel_appearance_store_test.cpp new file mode 100644 index 000000000..c813b569d --- /dev/null +++ b/tests/native_channel_appearance_store_test.cpp @@ -0,0 +1,104 @@ +// SPDX-License-Identifier: AGPL-3.0-only +#ifdef NDEBUG + #undef NDEBUG +#endif +#include +#include +#include +#include +#include "../src/NativeChannelAppearanceStore.h" + +using armix::appearance::Store; +static juce::var object(){return juce::var(new juce::DynamicObject());} +static void set(juce::var& value,const char* k,const juce::var& v){ + value.getDynamicObject()->setProperty(k,v); +} +static juce::var nativeGraph(){ + auto root=object(),device=object(),graph=object(),caps=object(),session=object(); + set(device,"epoch","7"); + set(graph,"revision","9");set(graph,"rosterRevision","11"); + set(caps,"callbackOwnsChannelIds",true);set(graph,"capabilities",caps); + juce::Array channels; + for(const auto& [id,name]:std::vector>{ + {"9007199254740993","Vocal"},{"9007199254740995","Guitar"}, + {"18446744073709551615","MAIN"}}){ + auto row=object();set(row,"id",id);set(row,"name",name);channels.add(row); + } + set(graph,"channels",juce::var(channels));set(root,"graph",graph); + set(root,"device",device);set(session,"authority","CHANNEL_ID"); + set(root,"mixerSession",session); + return root; +} +static juce::var edit(const juce::String& id,const juce::String& name, + const juce::String& color="#c32974", + const juce::String& icon="🎹"){ + auto v=object(); + set(v,"channelId",id);set(v,"name",name); + set(v,"color",color);set(v,"icon",icon); + set(v,"deviceEpoch","7");set(v,"graphRevision","9"); + set(v,"rosterRevision","11");set(v,"appearanceRevision","0"); + return v; +} +int main(){ + const auto dir=juce::File::getSpecialLocation(juce::File::tempDirectory) + .getNonexistentChildFile("ArSonMixChannelIdentity","",false); + assert(dir.createDirectory().wasOk()); + const auto g=nativeGraph(); + const juce::String vocalId="9007199254740993"; + const juce::String guitarId="9007199254740995"; + { + Store store(dir); + assert(store.error().isEmpty()); + auto req=edit(vocalId,"Studio Vox"); + // Fail closed on non-graph identity or stale lease. + set(req,"channelId","9007199254740994"); + assert(store.apply(req,g)=="CHANNEL_NOT_IN_NATIVE_ROSTER"); + set(req,"channelId",vocalId); + set(req,"rosterRevision","10"); + assert(store.apply(req,g)=="STALE_CHANNEL_IDENTITY_OR_GRAPH"); + set(req,"rosterRevision","11"); + set(req,"icon","', + '
\n' + identity_markup + + '', + "place editor under body outside scrolling app") + html = once(html, + "function openChannelIdentity(t,anchor){", + """function positionChannelIdentity(dialog,anchor){ + // One geometry read on explicit open, not in the live meter/PCM path. + const visual=window.visualViewport; + const vx=visual?.offsetLeft??0,vy=visual?.offsetTop??0; + const vw=visual?.width||window.innerWidth,vh=visual?.height||window.innerHeight; + const gap=8; + dialog.style.maxWidth=Math.max(1,vw-2*gap)+'px'; + dialog.style.maxHeight=Math.max(1,vh-2*gap)+'px'; + const box=dialog.getBoundingClientRect(),a=anchor?.getBoundingClientRect?.(); + const preferredX=a?a.left+a.width/2-box.width/2:vx+gap; + const preferredY=a?a.top+18:vy+gap; + const x=Math.max(vx+gap,Math.min(vx+vw-box.width-gap,preferredX)); + const y=Math.max(vy+gap,Math.min(vy+vh-box.height-gap,preferredY)); + dialog.style.left=x+'px';dialog.style.top=y+'px'; +} +function openChannelIdentity(t,anchor){""", + "install measured viewport positioning") + html = once(html, + """ const parent=document.querySelector('.console-pane'),a=anchor?.getBoundingClientRect?.(),p=parent?.getBoundingClientRect?.(); + if(a&&p&&dialog.style?.setProperty){ + dialog.style.setProperty('left',Math.max(8,Math.min(p.width-302,a.left-p.left+a.width/2-148))+'px'); + dialog.style.setProperty('top',Math.max(8,Math.min(p.height-295,a.top-p.top+18))+'px'); + } + document.getElementById('identityName').focus?.();""", + """ positionChannelIdentity(dialog,anchor); + document.getElementById('identityName').focus({preventScroll:true});""", + "remove mixer-relative geometry and focus scroll") targets = ("identityClose","pluginClose","fastClose", "wireConfigClose","wireWsClose","routeChoiceClose") for target in targets: @@ -151,6 +193,12 @@ def apply_operator_ux(html: str, assets: Path) -> str: plugin_path = assets / "mixer-plugin-browser.css" chrome = chrome_path.read_text(encoding="utf-8") plugin = plugin_path.read_text(encoding="utf-8") + # Edit the existing compiled CSS owner, not a late override stylesheet. + chrome = once(chrome, + " position:absolute;z-index:115;left:28px;top:100px;width:302px;max-width:calc(100% - 24px);", + " position:fixed;z-index:115;left:8px;top:8px;width:302px;max-width:calc(100vw - 16px);" + "\n max-height:calc(100dvh - 16px);overflow-y:auto;overscroll-behavior:contain;", + "viewport-based bounded editor geometry") if "V29 adaptive 50/50 console" in chrome: raise ValueError("Operator UX cannot stack duplicate styles") # Replace the original movable-window geometry instead of layering another diff --git a/tests/approved_css_original_bundle_fixture.py b/tests/approved_css_original_bundle_fixture.py index 82385d9d8..783bf09d2 100644 --- a/tests/approved_css_original_bundle_fixture.py +++ b/tests/approved_css_original_bundle_fixture.py @@ -15,6 +15,7 @@ sys.path.insert(0, str(ROOT / "scripts")) from compile_approved_css import LINK from compose_operator_ux import apply_operator_ux +from approved_fx_rack_interaction import apply_fx_rack_interaction ORIGINAL_LINK = re.compile( r'' ) @@ -43,5 +44,5 @@ def restore_original_css_bundle(bundle: Path) -> None: shutil.copyfile(ROOT / "site" / owner / "assets" / name, assets / name) # The shipped DOM already contains the same composition. Reapply it # only to reconstruct the CSS owner bytes, using its original HTML input. - apply_operator_ux(source_html, assets) + apply_operator_ux(apply_fx_rack_interaction(source_html, assets), assets) index.write_text(original_html, encoding="utf-8") diff --git a/tests/approved_native_fx_edit_smoke.py b/tests/approved_native_fx_edit_smoke.py index fabf1404c..ebe470efd 100644 --- a/tests/approved_native_fx_edit_smoke.py +++ b/tests/approved_native_fx_edit_smoke.py @@ -30,9 +30,9 @@ def main(): emit(page,'arMixConsoleSnapshot',state) def row(channel,slot):return page.locator(f'#tracks .strip[data-id="{channel}"] .fxslot-row[data-slot="{slot}"]') def move(source,slot,destination,target_slot,after=False): - grip=row(source,slot).locator('.fx-grip').bounding_box();target=row(destination,target_slot).bounding_box() - assert grip and target - page.mouse.move(grip['x']+grip['width']/2,grip['y']+grip['height']/2);page.mouse.down() + surface=row(source,slot).locator('.fx-pick').bounding_box();target=row(destination,target_slot).bounding_box() + assert surface and target + page.mouse.move(surface['x']+surface['width']/2,surface['y']+surface['height']/2);page.mouse.down() x=target['x']+target['width']/2;y=target['y']+target['height']*(.8 if after else .2) page.mouse.move(x,y,steps=10);page.wait_for_timeout(60) ghost=page.locator('.fx-drag-ghost');assert ghost.count()==1 @@ -49,12 +49,26 @@ def accept(request): ack(page,state,request);emit(page,'arMixConsoleSnapshot',state) page.wait_for_function('()=>!window.__ARMIX_NATIVE_M2__.state().pending') # Escape cancels presentation without committing an audio edit. - grip=row(1,0).locator('.fx-grip').bounding_box();assert grip - page.mouse.move(grip['x']+5,grip['y']+5);page.mouse.down();page.mouse.move(450,50,steps=10) + assert page.locator('.fx-grip').count()==0,'retired handle must never appear' + surface=row(1,0).locator('.fx-pick').bounding_box();assert surface + page.mouse.move(surface['x']+5,surface['y']+5);page.mouse.down();page.mouse.move(450,50,steps=10) page.wait_for_timeout(40);assert page.locator('.fx-drag-ghost').count()==1 page.keyboard.press('Escape');page.mouse.up() assert page.locator('.fx-drag-ghost').count()==0 assert page.evaluate('()=>window.__nativeIntents.length')==0 + # POWER/DELETE remain dedicated click targets, not drag origins. + for action in ("slotPower","removeFx"): + rect=row(1,0).locator(f'[data-action="{action}"]').bounding_box() + assert rect + page.mouse.move(rect['x']+rect['width']/2,rect['y']+rect['height']/2) + page.mouse.down();page.mouse.move(450,50,steps=6) + assert page.locator('.fx-drag-ghost').count()==0,action + page.mouse.up() + assert page.evaluate('()=>window.__nativeIntents.length')==0,action + # A short click on the name still opens the real native editor. + row(1,0).locator('.fx-pick').click() + assert page.evaluate("()=>window.__actions.at(-1)?.action")=="routingFxEditor" + assert page.evaluate('()=>window.__nativeIntents.length')==0 # Drag lower within the same rack: exact plugin follows pointer. request=move(1,0,1,1,True) assert request['operation']=='MOVE_INSERT' and request['payload']['toSlot']==1 @@ -82,6 +96,6 @@ def accept(request): assert not errors,errors page.screenshot(path=f'native-fx-edit-{width}.png');page.close() browser.close() - print('PASS native FX pointer ghost, reorder, cross-channel move, delete, editor token and quiet MAIN; 3 sizes') + print('PASS native handle-free FX pointer ghost, reorder, cross-channel move, delete, editor token and quiet MAIN; 3 sizes') if __name__=='__main__':main() diff --git a/tests/approved_operator_ux_chromium_fat.py b/tests/approved_operator_ux_chromium_fat.py index 8d9204a44..d2ebfc8a5 100644 --- a/tests/approved_operator_ux_chromium_fat.py +++ b/tests/approved_operator_ux_chromium_fat.py @@ -127,6 +127,7 @@ def inspect_page(page, width, height, scale, label): assert moved['x']>=-2 and moved['y']>=-2 and moved['x']+moved['width']<=width+4,( "plugin escaped viewport",width,height,moved) page.screenshot(path=str(ROOT/f'operator-ux-drag-{width}x{height}-{scale}.png')) + check_identity_zero_reflow(page,width,height,scale,1) # plugin open/dragged assert_key(page,'#pluginClose') assert win.is_hidden() # Identity window and the other modeless tool share the exact square key. @@ -134,6 +135,7 @@ def inspect_page(page, width, height, scale, label): assert page.locator('#channelIdentity').is_visible() assert_key(page,'#identityClose') assert page.locator('#channelIdentity').is_hidden() + check_identity_zero_reflow(page,width,height,scale,'right-edge') # All other close keys use the SAME SVG and dimensions; hidden popups # cannot be pointer-tested here, but the CSS/DOM invariants are checked. for id in ('fastClose','wireConfigClose','wireWsClose','routeChoiceClose'): @@ -144,6 +146,94 @@ def inspect_page(page, width, height, scale, label): full_page=True) return m + +# Every significant console coordinate and scroll extent must stay unchanged. +# This intentionally tests MORE than 'editor.is_visible()' at all five scales. +IDENTITY_GEOMETRY = """() => { + const selectors=[ + 'html','body','.app','.window-title','.command-bar','.console-pane', + '.console-body','.section-rail','#viewport','#tracks','#master', + '#master .strip','#tracks .strip','#tracks .strip .strip-identity-top', + '#tracks .strip .route-section','#tracks .strip .fx-section', + '#tracks .strip .send-section','#tracks .strip .pan-section', + '#tracks .strip .switch-section','#tracks .strip .fader-section', + '#tracks .strip .bottom-section','#tracks .strip .fader', + '#tracks .strip .meter-lane','#tracks .strip .wire-node-in', + '#tracks .strip .wire-node-out','#master .fader', + '#master .meter-lane','#pluginBrowser' + ]; + const rect=e=>{const r=e.getBoundingClientRect(); + return [r.x,r.y,r.width,r.height];}; + const rects={}; + for(const selector of selectors) + rects[selector]=Array.from(document.querySelectorAll(selector)) + .filter(e=>!e.hidden&&getComputedStyle(e).display!=='none').map(rect); + const scroll={}; + for(const selector of ['html','body','.app','.console-pane', + '.console-body','#viewport','#tracks','#master']){ + const e=document.querySelector(selector); + if(e)scroll[selector]=[e.scrollTop,e.scrollLeft,e.clientWidth, + e.clientHeight,e.scrollWidth,e.scrollHeight]; + } + return {rects,scroll,viewport:[innerWidth,innerHeight, + visualViewport?.width||innerWidth,visualViewport?.height||innerHeight, + visualViewport?.offsetLeft||0,visualViewport?.offsetTop||0], + density:document.querySelector('.console-body').dataset.density, + bank:document.getElementById('bankSelect').value, + editorParent:document.getElementById('channelIdentity').parentElement.tagName}; +}""" + +def assert_still(before,after,where): + assert after['editorParent']=='BODY',(where,'editor lives inside mixer') + for key in ('scroll','viewport','density','bank'): + assert before[key]==after[key],(where,key,before[key],after[key]) + for selector,lhs in before['rects'].items(): + rhs=after['rects'][selector] + assert len(lhs)==len(rhs),(where,selector,len(lhs),len(rhs)) + for index,(a,b) in enumerate(zip(lhs,rhs)): + for axis,(x,y) in enumerate(zip(a,b)): + assert abs(x-y)<=0.5,(where,selector,index,axis,x,y) + +def check_identity_zero_reflow(page,width,height,scale,channel): + # Bank contents are driven by the current native/channel roster. The + # viewport's right edge is its last rendered strip, not a guessed ID 10. + strip=(page.locator('#tracks .strip').last if channel=='right-edge' + else page.locator(f'#tracks .strip[data-id="{channel}"]')) + assert strip.count()==1,(width,height,channel,'strip missing') + strip.locator('.strip-identity-top').click() + # Baseline after the intentional fold/selection layout has been painted. + # Folded panels are NOT 50:50, and that is unrelated to editor stability. + page.evaluate("() => new Promise(done => requestAnimationFrame(done))") + before=page.evaluate(IDENTITY_GEOMETRY) + stem=ROOT/f'operator-identity-{width}x{height}-{scale}-ch{channel}' + page.screenshot(path=str(stem)+'-before.png') + strip.locator('.strip-identity-top').dblclick() + editor=page.locator('#channelIdentity') + assert editor.is_visible(),(width,height,channel) + assert editor.evaluate("e=>getComputedStyle(e).position")=='fixed' + assert page.locator('#identityName').evaluate("e=>document.activeElement===e") + box=editor.bounding_box() + assert box and box['x']>=-0.5 and box['y']>=-0.5,box + assert box['x']+box['width']<=width+0.5,box + assert box['y']+box['height']<=height+0.5,box + assert page.locator('#identityClose').is_visible() + assert page.locator('#identitySave').is_visible() + opened=page.evaluate(IDENTITY_GEOMETRY) + assert_still(before,opened,(width,height,scale,channel,'open')) + page.screenshot(path=str(stem)+'-open.png') + if channel=='right-edge': + page.keyboard.press('Escape') + else: + page.locator('#identityCancel').click() + assert editor.is_hidden() + closed=page.evaluate(IDENTITY_GEOMETRY) + assert_still(before,closed,(width,height,scale,channel,'close')) + page.screenshot(path=str(stem)+'-closed.png') + print('IDENTITY_ZERO_REFLOW',width,height,scale,channel, + json.dumps({'before':before['scroll'],'opened':opened['scroll'], + 'closed':closed['scroll'],'editor':box},sort_keys=True), + flush=True) + def main(): import sys sys.path.insert(0,str(ROOT/'scripts')) diff --git a/tests/approved_operator_ux_native_identity_smoke.py b/tests/approved_operator_ux_native_identity_smoke.py index cb8f14dec..d3fad1e2f 100644 --- a/tests/approved_operator_ux_native_identity_smoke.py +++ b/tests/approved_operator_ux_native_identity_smoke.py @@ -10,6 +10,7 @@ import copy from playwright.sync_api import sync_playwright from approved_native_wire_gain_smoke import snapshot, emit, SOURCE, RECEIVER +from approved_operator_ux_chromium_fat import IDENTITY_GEOMETRY, assert_still ROOT=Path(__file__).resolve().parents[1] sys.path.insert(0,str(ROOT/"scripts")) @@ -51,10 +52,12 @@ def open_page(): strip.wait_for(state="visible") # Native DAW convention: one click selects, double-click opens editor. strip.locator(".strip-identity-top").click() + before_editor=page.evaluate(IDENTITY_GEOMETRY) editor=page.locator("#channelIdentity") assert editor.is_hidden(),"single click should only select" strip.locator(".strip-identity-top").dblclick() assert editor.is_visible(),"double-click header should edit" + assert_still(before_editor,page.evaluate(IDENTITY_GEOMETRY),"native double-click") page.locator("#identityName").fill("Studio Vox") color="#c32974" page.locator(f'#identityColors [data-identity-color="{color}"]').click() @@ -78,6 +81,7 @@ def open_page(): assert editor.is_visible() assert page.locator("#identitySave").is_enabled() assert "Studio Vox" not in strip.inner_text() + assert_still(before_editor,page.evaluate(IDENTITY_GEOMETRY),"native negative ACK") # Retry after a fresh accepted snapshot. emit(page,"arMixConsoleSnapshot",state) page.locator("#identitySave").click() @@ -119,14 +123,21 @@ def open_page(): page.wait_for_selector('#tracks .strip[data-id="1"]') assert "Studio Vox" in page.locator('#tracks .strip[data-id="1"]').inner_text() page.locator('#tracks .strip[data-id="2"] .strip-identity-top').click() + before_f2=page.evaluate(IDENTITY_GEOMETRY) page.keyboard.press('F2') assert editor.is_visible(),"F2 should open editor" + assert_still(before_f2,page.evaluate(IDENTITY_GEOMETRY),"native F2") page.locator('#identityCancel').click() + page.evaluate("() => new Promise(done => requestAnimationFrame(done))") + assert_still(before_f2,page.evaluate(IDENTITY_GEOMETRY),"native F2 Cancel") page.locator('#tracks .strip[data-id="2"] .footer-label .name').focus() + before_enter=page.evaluate(IDENTITY_GEOMETRY) page.keyboard.press('Enter') assert editor.is_visible(),"Enter should open editor" + assert_still(before_enter,page.evaluate(IDENTITY_GEOMETRY),"native Enter") page.keyboard.press('Escape') assert editor.is_hidden() + assert_still(before_enter,page.evaluate(IDENTITY_GEOMETRY),"native Escape") assert page.evaluate("()=>window.__nativeIntents.length")==0 # Upgrade old WebView cache exactly once; no optimistic local rename. # The emulated host starts with a clean native workspace and accepts diff --git a/tests/approved_operator_ux_smoke.py b/tests/approved_operator_ux_smoke.py index 08fed10cf..9ff66b0a6 100644 --- a/tests/approved_operator_ux_smoke.py +++ b/tests/approved_operator_ux_smoke.py @@ -32,6 +32,14 @@ def test_single_composed_gui_stays_faithful_and_editable(self): self.assertIn('id="densitySelect" class="density-select" hidden',compiled) self.assertEqual(compiled.count(CLOSE_ICON),6) self.assertIn("V29 adaptive 50/50 console",chrome) + self.assertIn("position:fixed;z-index:115;left:8px",chrome) + self.assertIn("max-height:calc(100dvh - 16px);overflow-y:auto",chrome) + self.assertEqual(compiled.count('id="channelIdentity"'),1) + self.assertLess( + compiled.index('
\n
getComputedStyle(e).cursor")=="grab" rail=page.locator('.section-rail [data-section="fx"]') assert rail.get_attribute("aria-expanded")=="true" # V29 has one comfort density: actual FX rail disclosure must remain @@ -71,7 +72,7 @@ def check_transactions(page): effect=page.locator('#fastResults .fast-effect').filter(has_text="Dynamics Processing").first assert effect.is_visible(),"Quick FX Picker did not expose Dynamics Processing" effect.click() - assert root.locator('.fx-grip[data-slot="1"]').count()==1,"Second FX not accepted by GUI" + assert root.locator('.fxslot-row:not(.is-empty)').count()>=2,"Second FX not accepted by GUI" # Independently bypass first plugin; the move must carry bypass with identity. root.locator('[data-action="slotPower"][data-slot="0"]').click() initial=model(page) @@ -82,8 +83,8 @@ def check_transactions(page): for selector in ('.fx-pick[data-slot="0"]','[data-action="slotPower"][data-slot="0"]', '[data-action="removeFx"][data-slot="0"]'): assert root.locator(selector).get_attribute("draggable") is None - # Focusable grip is the only drag actuator. Keyboard moves one real insert. - first=root.locator('.fx-grip[data-slot="0"]') + # Focusable plugin name also exposes keyboard reorder, without a handle. + first=root.locator('.fx-pick[data-slot="0"]') first.focus();first.press('Alt+ArrowDown') after=model(page) assert [x["name"] for x in after[:2]]==[ @@ -92,31 +93,31 @@ def check_transactions(page): x["id"] for x in initial[:2][::-1]],"insert identity lost" assert [x["bypassed"] for x in after[:2]]==[ x["bypassed"] for x in initial[:2][::-1]],"bypass moved separately" - root.locator('.fx-grip').first.focus() - root.locator('.fx-grip').first.press('Control+z') - assert model(page)==initial,"grip Ctrl+Z must restore order, bypass and identity" - # Real pointer Drag&Drop on dedicated grip; non-draggable rows cannot reorder. - root.locator('.fx-grip[data-slot="0"]').drag_to(root.locator('.fxslot-row[data-slot="1"]'),target_position={'x':40,'y':18}) + root.locator('.fx-pick:not(.empty)').first.focus() + root.locator('.fx-pick:not(.empty)').first.press('Control+z') + assert model(page)==initial,"plugin-name Ctrl+Z must restore order, bypass and identity" + # Real pointer Drag&Drop on row-wide pointer; non-draggable rows cannot reorder. + root.locator('.fx-pick[data-slot="0"]').drag_to(root.locator('.fxslot-row[data-slot="1"]'),target_position={'x':40,'y':18}) dragged=model(page) # Slot indices are physical positions and MUST remain 0/1 after moving. # Compare stable insert payload separately from its new position. assert [r["slot"] for r in dragged[:2]]==[0,1],("invalid DnD positions",dragged) for key in ("id","name","bypassed"): assert [r[key] for r in dragged[:2]]==[ - r[key] for r in initial[:2][::-1]],("grip DnD changed "+key,dragged) - # Cross-channel reference transfer preserves token/bypass and compacts + r[key] for r in initial[:2][::-1]],("row DnD changed "+key,dragged) + # Cross-channel pointer transfer preserves token/bypass and compacts # both chains. Native transfer has separate accepted PCM coverage. before=model(page) second=model(page,"2") other=page.locator('#tracks .strip[data-id="2"]') - root.locator('.fx-grip[data-slot="0"]').drag_to(other.locator('.fxslot-row[data-slot="0"]')) + root.locator('.fx-pick[data-slot="0"]').drag_to(other.locator('.fxslot-row[data-slot="0"]')) assert len([r for r in model(page) if r['name']!='None'])==len([r for r in before if r['name']!='None'])-1 assert len([r for r in model(page,"2") if r['name']!='None'])==len([r for r in second if r['name']!='None'])+1 - other.locator('.fx-grip').first.focus() - other.locator('.fx-grip').first.press('Control+z') + other.locator('.fx-pick:not(.empty)').first.focus() + other.locator('.fx-pick:not(.empty)').first.press('Control+z') assert model(page)==before and model(page,"2")==second,"transfer undo lost native-style identity" - root.locator('.fx-grip').first.focus() - root.locator('.fx-grip').first.press('Control+z') + root.locator('.fx-pick:not(.empty)').first.focus() + root.locator('.fx-pick:not(.empty)').first.press('Control+z') assert model(page)==initial,"preceding reorder undo lost" # The separate OFF button is never a drag handle; it flips only bypass. root.locator('[data-action="slotPower"][data-slot="0"]').click() @@ -156,6 +157,6 @@ def main(): assert not errors,(width,errors) page.close() browser.close() - print("PASS V53 dedicated grip + reversible FX reorder, visual frame and rail on 4 sizes × 3 operator states") + print("PASS V53 row-wide pointer + reversible FX reorder, visual frame and rail on 4 sizes × 3 operator states") if __name__=="__main__":main() \ No newline at end of file diff --git a/tests/single_preview_publication_contract_test.py b/tests/single_preview_publication_contract_test.py index 641a5d9d3..ed243500a 100644 --- a/tests/single_preview_publication_contract_test.py +++ b/tests/single_preview_publication_contract_test.py @@ -48,9 +48,12 @@ def require(ok,why): # the source repository or the already optimized distribution. with tempfile.TemporaryDirectory(prefix="armix-operator-contract-") as td: owned=Path(td) - owners=("mixer-chrome-material.css","mixer-plugin-browser.css") + owners=("mixer-chrome-material.css","mixer-plugin-browser.css","mixer-fx-rack.css") for name in owners: shutil.copy2(ROOT/"site/preview-v2/assets"/name,owned/name) + # Recreate the SAME handle-free FX CSS owner as the production assembler, + # then run the existing operator composer. Historic V28 assets stay locked. + apply_fx_rack_interaction((ROOT/"site/preview-v2/index.html").read_text(encoding="utf-8"),owned) expected=apply_operator_ux(expected,owned) composed_css={name:(owned/name).read_text(encoding="utf-8") for name in owners} # Stage C: the source HTML remains byte-exact, but the 18 deployed CSS files diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index e6cf7b68b..b0adf77c8 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -2993,7 +2993,7 @@ requestAnimationFrame(()=>{ if(!document.getElementById("channelIdentity")?.hidden)return; const name=document.querySelector('.strip[data-id="'+lastEditedChannelId+'"] .footer-label .name'); - name?.focus?.(); + name?.focus?.({preventScroll:true}); }); }); } From aa3709ab3cd20e35e07fe212f1e33129a392da3f Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 19:22:45 +0700 Subject: [PATCH 217/219] Resume verified mixer monitoring and add portable Save/Open --- scripts/build_approved_native_gui.py | 14 +- scripts/compose_operator_ux.py | 53 ++++ site/preview-v2/assets/mixer-open.svg | 2 + site/preview-v2/assets/mixer-save.svg | 2 + src/LiveAudioEngine.h | 48 ++-- src/LiveDryRoutingLab.h | 20 +- src/Main.cpp | 311 +++++++++------------- src/NativeMixerSessionDocument.h | 11 +- src/NativeMixerSessionSaveWorker.h | 44 ++- src/NativeMixerSessionStore.h | 78 +++++- tests/approved_native_cold_start_smoke.py | 64 +---- tests/approved_native_wire_gain_smoke.py | 25 ++ tests/native_mixer_session_store_test.cpp | 37 ++- web/approved-native-bridge.js | 120 +++------ 14 files changed, 451 insertions(+), 378 deletions(-) create mode 100644 site/preview-v2/assets/mixer-open.svg create mode 100644 site/preview-v2/assets/mixer-save.svg diff --git a/scripts/build_approved_native_gui.py b/scripts/build_approved_native_gui.py index d8984eefb..7f707daef 100644 --- a/scripts/build_approved_native_gui.py +++ b/scripts/build_approved_native_gui.py @@ -175,21 +175,21 @@ def accepted_pages_html() -> str: # Native WebView2 only: expose the original Pages IIFE model to the thin # bridge. No second renderer/state reducer, no change to public /preview/. ("restorePluginPreferences();init();\n})();", - "let verifiedM4WireSignature='',verifiedM4WireDirty=false,nativeWireGainDirty=false;\n" + "let verifiedM4WireSignature='',verifiedM4WireDirty=false;\n" "window.__ARMIX_NATIVE_SCOPE__=Object.freeze({\n" " get tracks(){return tracks;},get master(){return master;},\n" " get wireEdges(){return wireEdges;}, // native read-only UI edge identity\n" + " get wireGainDragging(){return !!sendKnobDrag;},paintWireKnob,\n" " syncNativeWireGains(rows){\n" " for(const row of rows){\n" " const edge=wireEdges.find(e=>e.id===row.id&&e.kind!=='primary');\n" - " if(edge&&Number.isFinite(row.levelDb)&&edge.levelDb!==row.levelDb){\n" - " edge.levelDb=row.levelDb;nativeWireGainDirty=true;\n" + " if(!edge||!Number.isFinite(row.levelDb))continue;\n" + " edge.levelDb=row.levelDb;\n" + " const input=document.querySelector('.wire-gain[data-wire-id=\"'+edge.id+'\"]');\n" + " if(input&&input!==sendKnobDrag?.input&&!row.pending){\n" + " input.value=String(row.levelDb);paintWireKnob(input,row.levelDb);\n" " }\n" " }\n" - " if(nativeWireGainDirty&&!wireGesture&&!faderGesture&&\n" - " !document.activeElement?.matches?.('.wire-gain,#wireWsGain')){\n" - " nativeWireGainDirty=false;refreshWireRoutingNodes();\n" - " }\n" " },\n" " syncVerifiedM4Wires(rows,ids){\n" " if(!Array.isArray(rows)||rows.length!==10||!Array.isArray(ids)||ids.length!==10)\n" diff --git a/scripts/compose_operator_ux.py b/scripts/compose_operator_ux.py index f8ca595ba..a6b8e1242 100644 --- a/scripts/compose_operator_ux.py +++ b/scripts/compose_operator_ux.py @@ -78,6 +78,8 @@ .window-title .file-name{min-width:0;overflow:hidden;text-overflow:ellipsis} .window-title .right{margin-left:auto;min-width:0;max-width:48%;overflow:hidden; text-overflow:ellipsis;white-space:nowrap;color:#90b6c8;font-size:10px;font-weight:400} +.command-bar .mixer-file-tool{display:inline-flex;align-items:center;gap:5px} +.command-bar .mixer-file-tool img{display:block;flex:none;pointer-events:none} .command-bar #densitySelect,.command-bar [for="densitySelect"],.command-bar #mode{display:none!important} /* Every console floating editor uses one square Material close key. */ :is(#pluginClose,#identityClose,#fastClose,#wireConfigClose,#wireWsClose,#routeChoiceClose){ @@ -127,6 +129,57 @@ def apply_operator_ux(html: str, assets: Path) -> str: "const density=['comfort','standard','compact'].includes(mode)?mode:'comfort';", "const density='comfort'; // V29: one permanently comfortable operator view", "single comfort mode") + html = once(html, + "sendKnobDrag={id:e.pointerId,pot,input,x:e.clientX,y:e.clientY,start:Number(input.value)||0};", + """if(input.disabled)return; + input.focus({preventScroll:true}); + sendKnobDrag={id:e.pointerId,pot,input,x:e.clientX,y:e.clientY,value:Number(input.value)||0, + start:Number(input.value)||0};""", + "focus and hold the WIRE knob") + html = once(html, + """ const distance=e.clientX-g.x-(e.clientY-g.y),next=wireGainValue(g.start+distance/(e.shiftKey?14:3)); + if(Number(g.input.value)!==next){g.input.value=String(next);handleField({target:g.input,type:'input'});}""", + """ const dx=e.clientX-g.x,dy=g.y-e.clientY;g.x=e.clientX;g.y=e.clientY; + const delta=Math.abs(dy)>=Math.abs(dx)?dy:dx; + const previous=wireGainValue(g.value); + g.value=Math.max(-60,Math.min(6,g.value+delta/(e.shiftKey?48:8))); + const next=wireGainValue(g.value); + if(previous!==next){ + g.input.value=String(next);paintWireKnob(g.input,next); + handleField({target:g.input,type:'input'}); + }""", + "precision WIRE drag without shift jumps") + html = once(html, + "let sendKnobDrag=null;", + """let sendKnobDrag=null; +function paintWireKnob(input,db){ + const pct=wireGainPercent(db),pot=input.closest('.wire-pot'); + pot?.style.setProperty('--wire-pct',pct+'%'); + pot?.style.setProperty('--wire-deg',(-135+pct*2.7).toFixed(1)+'deg'); + input.style.setProperty('--wire-pct',pct+'%'); + input.setAttribute('aria-valuetext',wireDbText(db)); +}""", + "immediate WIRE knob feedback") + html = once(html, + "if(cancel){g.input.value=String(g.start);", + "if(cancel){g.input.value=String(g.start);paintWireKnob(g.input,g.start);", + "restore canceled WIRE knob visual") + html = once(html, + " else handleField({target:g.input,type:'change'});", + """ else { + g.input.value=String(wireGainValue(g.value)); + handleField({target:g.input,type:'change'}); + }""", + "flush exact WIRE pointer release value") + html = once(html, + "sendControlSurface.addEventListener('pointercancel',e=>finishSendKnob(e,true));", + """sendControlSurface.addEventListener('pointercancel',e=>finishSendKnob(e,true)); +sendControlSurface.addEventListener('lostpointercapture',e=>finishSendKnob(e,true));""", + "cancel an interrupted WIRE pointer") + html = once(html, + " if(e.button!==0)return;\n const t=findTrack(e.target);\n if(t?.kind==='master'", + " if(e.button!==0||e.target.closest?.('.wire-pot'))return;\n const t=findTrack(e.target);\n if(t?.kind==='master'", + "keep WIRE focus while turning receiver knob") old_minimize = re.compile(r'') html, count = old_minimize.subn("", html) if count != 1: diff --git a/site/preview-v2/assets/mixer-open.svg b/site/preview-v2/assets/mixer-open.svg new file mode 100644 index 000000000..95600b59e --- /dev/null +++ b/site/preview-v2/assets/mixer-open.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/site/preview-v2/assets/mixer-save.svg b/site/preview-v2/assets/mixer-save.svg new file mode 100644 index 000000000..19479ee06 --- /dev/null +++ b/site/preview-v2/assets/mixer-save.svg @@ -0,0 +1,2 @@ + + \ No newline at end of file diff --git a/src/LiveAudioEngine.h b/src/LiveAudioEngine.h index 57d8eb6a1..5bceac060 100644 --- a/src/LiveAudioEngine.h +++ b/src/LiveAudioEngine.h @@ -1472,22 +1472,20 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback armix::session::HardwareBinding live; armix::mixer::VerifiedNativeOutputs outputs{}; armix::device::JuceActivePortSnapshot pins; - std::vector sources; int callbackInputs=0; std::uint64_t epoch=0; - bool changed=false; }; - // A read-only control-thread preview for explicit hardware rebind. + // Read-only control-thread verification of the currently opened pins. juce::String inspectNativeMixerSessionBinding( const armix::session::MixerSessionDocument& saved, MixerBindingInspection& out) { - if(!allOutputsDisarmed()||independent_.active()||!attached_|| + if(independent_.active()||!attached_|| !directFence_.permitted()||handoff_.busy()|| fxMovePhase_.load(std::memory_order_acquire)!=0|| diagnosticRoute_.load(std::memory_order_acquire)!= armix::diagnostics::Route::normal|| routeReconfiguring_.load(std::memory_order_acquire)) - return "MUTE output and verify DIRECT before device inspection"; + return "Verify DIRECT before device inspection"; auto* device=deviceManager_.getCurrentAudioDevice(); if(!device||!device->isOpen()) return "NEEDS_REMAP: current audio device unavailable"; @@ -1513,29 +1511,20 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback candidate.callbackInputs=candidate.pins.inputs.enabledCount; candidate.outputs=armix::session::MixerDeviceBindingPolicy::proposedOutputs( saved,candidate.live,candidate.pins.outputCount); - auto probe=saved; - const auto reason=armix::session::MixerDeviceBindingPolicy::apply( - probe,candidate.live,candidate.outputs,candidate.callbackInputs,true); - if(reason.isNotEmpty())return reason; - candidate.sources=std::move(probe.request.sources); - candidate.changed=! - armix::session::MixerDeviceBindingPolicy::sameBinding( - saved.binding,candidate.live) || - !armix::session::MixerDeviceBindingPolicy::sameOutputs( - saved.outputs,candidate.outputs); if(candidate.epoch!=dryRoutingLab_.epoch()) return "NEEDS_REMAP: device changed during inspection"; out=std::move(candidate); return {}; } - // STARTUP: fresh vendor processors are prepared and all hashes validated - // before the ONE native PCM publication. No saved physical ARM state. + // Prepare fresh vendor processors before publishing the replacement. + // A successful publication leaves MAIN disarmed for caller verification. juce::String restoreNativeMixerSession( armix::session::MixerSessionDocument document, const std::vector& states, - const MixerBindingInspection* approval=nullptr) { - if(!allOutputsDisarmed()||independent_.active()||!attached_|| + bool replaceActive=false,bool* sameLiveOutputs=nullptr) { + if((replaceActive?secondaryOutput_.armed():!allOutputsDisarmed())|| + independent_.active()||!attached_|| !directFence_.permitted()||handoff_.busy()|| fxMovePhase_.load(std::memory_order_acquire)!=0|| diagnosticRoute_.load(std::memory_order_acquire)!= @@ -1546,13 +1535,10 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback auto bindingError=inspectNativeMixerSessionBinding(document,inspected); if(bindingError.isNotEmpty())return bindingError; using BindingPolicy=armix::session::MixerDeviceBindingPolicy; - if(approval && (approval->epoch!=inspected.epoch || - !BindingPolicy::sameBinding(approval->live,inspected.live) || - approval->live.frames!=inspected.live.frames || - !BindingPolicy::sameOutputs(approval->outputs,inspected.outputs))) - return "STALE_REBIND: approved device changed"; + if(sameLiveOutputs) + *sameLiveOutputs=dryRoutingLab_.matchesNativeMixerOutputs(inspected.outputs); bindingError=BindingPolicy::apply(document,inspected.live,inspected.outputs, - inspected.callbackInputs,approval!=nullptr); + inspected.callbackInputs,false); if(bindingError.isNotEmpty())return bindingError; const auto ep=inspected.epoch; const auto next=dryRoutingLab_.nativeGraphRevisionForRestore(); @@ -1569,14 +1555,20 @@ class LiveAudioEngine final : private juce::AudioIODeviceCallback const auto gain=document.masterGain; const auto mute=document.masterMute; const auto mono=document.masterMono; + const bool monitoring=isMonitorEnabled(); + if(monitoring)setMonitorEnabled(false); const auto applied=dryRoutingLab_.restoreNativeMixerSession( - std::move(document),std::move(bank),inspected.pins,allOutputsDisarmed()); - if(applied.isNotEmpty())return applied; + std::move(document),std::move(bank),inspected.pins, + allOutputsDisarmed(),replaceActive); + if(applied.isNotEmpty()) { + if(monitoring&&ep==dryRoutingLab_.epoch()&&liveOutputArmFault(false).isEmpty()) + setMonitorEnabled(true); + return applied; + } acceptedWasapiBinding_=std::move(profile); acceptedMixerBinding_=std::move(inspected.live); setMasterGainLinear(gain); setMasterMuted(mute);setMasterMono(mono); - setMonitorEnabled(false); return {}; } diff --git a/src/LiveDryRoutingLab.h b/src/LiveDryRoutingLab.h index 43dbce9e3..052949ff9 100644 --- a/src/LiveDryRoutingLab.h +++ b/src/LiveDryRoutingLab.h @@ -2038,6 +2038,15 @@ class LiveDryRoutingLab final { return "No authoritative native ChannelId graph"; if(nativeAccepted_.fxOwners->externalChannel().value) return "External CH1 FX owner cannot yet be serialized independently"; + // MAIN and STREAM are muted by the caller. Wait briefly for the + // current callback to leave the vendor processors before capturing. + std::optional renderPermit; + for(int attempt=0;attempt<50;++attempt) { + renderPermit.emplace(rendering_); + if(*renderPermit)break; + juce::Thread::sleep(1); + } + if(!*renderPermit)return "Audio callback did not quiesce for mixer capture"; try { armix::session::MixerSessionDocument draft; draft.roster=nativeAccepted_.graph.roster; @@ -2109,10 +2118,10 @@ class LiveDryRoutingLab final { armix::session::MixerSessionDocument document, std::shared_ptr bank, const armix::device::JuceActivePortSnapshot& pins, - bool outputsDisarmed) { + bool outputsDisarmed,bool replaceActive=false) { using namespace armix::mixer; - if(!outputsDisarmed || channelIdPhysicalPcmActive() || !bank) - return "Restore requires a muted device without live ChannelId PCM"; + if(!outputsDisarmed || (!replaceActive && channelIdPhysicalPcmActive()) || !bank) + return "Restore requires a muted device"; const auto generation=pins.epoch; if(!matchesSessionDevice(pins) || bank->epoch()!=generation || document.request.physicalInputs!=pins.inputs.enabledCount || @@ -2162,6 +2171,11 @@ class LiveDryRoutingLab final { }catch(...) {return "Native session restore exception";} } + bool matchesNativeMixerOutputs(const armix::mixer::VerifiedNativeOutputs& outputs) const noexcept { + return channelIdPhysicalPcmActive() && + armix::session::MixerDeviceBindingPolicy::sameOutputs(nativeAccepted_.hardware,outputs); + } + std::uint64_t nativeGraphRevisionForRestore() const noexcept { const auto current=nativePublisher_.acceptedRevision(); return current==std::numeric_limits::max()?0:current+1; diff --git a/src/Main.cpp b/src/Main.cpp index db08e0179..2bb32269c 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -310,18 +310,17 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr closePluginEditor(); audioSetupWindow_.reset(); engine_.devices().removeChangeListener (this); - // Best-effort clean-exit checkpoint, after emergency physical MUTE. - // A pending worker already owns a safe immutable snapshot. Never - // block or mutate the audio callback for session disk persistence. + // Drain any earlier file work before the final muted checkpoint. + // Remember MAIN before the shutdown mute changes the hardware state. + const bool resumeMain=engine_.isMonitorEnabled(); engine_.setOutputMuted(true); engine_.disconnectSecondaryOutput(); - if(!mixerSessionWorker_.busy()) { - const auto lab=engine_.status().getProperty("dryRoutingLab",{}); - if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false))) { - const auto error=saveMixerSession(true); - if(error.isNotEmpty()) - diagnostics_.record("DYNAMIC_MIXER_EXIT_SAVE_REJECTED",error); - } + mixerSessionWorker_.finishForShutdown(); + const auto lab=engine_.status().getProperty("dryRoutingLab",{}); + if(static_cast(lab.getProperty("nativeChannelIdPcmActive",false))) { + const auto error=saveMixerSession(resumeMain); + if(error.isNotEmpty()) + diagnostics_.record("DYNAMIC_MIXER_EXIT_SAVE_REJECTED",error); } engine_.stop(); browser_.setVisible (false); @@ -346,31 +345,9 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr juce::String mixerSessionError_,lastMixerSessionFingerprint_; bool mixerSessionStartupInspected_=false; bool mixerSessionRecoveryPending_=false; - struct PendingMixerRebind final { - juce::String nonce,signature; - juce::int64 expiresAt=0; - } pendingMixerRebind_; - // SHA binds the immutable persisted session to a specific verified - // physical device epoch, masks and output pair. Never a PCM authority. - static juce::String mixerRebindSignature( - const armix::session::MixerSessionDocument& doc, - const LiveAudioEngine::MixerBindingInspection& live) { - const auto& b=live.live; - const auto& o=live.outputs; - auto raw=armix::session::Codec::encode(doc)+ - "|device="+b.backend+"|capture="+b.capture+ - "|playback="+b.playback+"|input="+b.inputMask+ - "|output="+b.outputMask+"|rate="+juce::String(b.rate,3)+ - "|frames="+juce::String(b.frames)+ - "|inputs="+juce::String(live.callbackInputs)+ - "|epoch="+juce::String(std::to_string(live.epoch))+ - "|active="+juce::String(o.activeOutputChannels)+ - "|main="+juce::String(o.mainL)+","+juce::String(o.mainR)+ - "|monitor="+juce::String(o.monitorEnabled?1:0)+ - ","+juce::String(o.monitorL)+","+juce::String(o.monitorR); - return juce::SHA256(raw.toRawUTF8(),raw.getNumBytesAsUTF8()) - .toHexString(); - } + std::unique_ptr mixerFileChooser_; + bool mixerFileDialogOpen_=false; + juce::File lastMixerFile_; bool nativeShowBusy_ = false; bool studioBackupBusy_ = false; std::unique_ptr chooser_; @@ -1898,77 +1875,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return armix::session::NativeMixerSessionStore(settingsDirectory()).load(doc,blobs); } - // Read-only operator preview: no vendor instantiation, no graph publish, - // and no output authorization. Every source patch remains an ordinal. - void previewMixerDeviceRebind() { - auto ack=std::make_unique(); - juce::String error; - pendingMixerRebind_={}; - if(!engine_.allOutputsDisarmed()||mixerSessionWorker_.busy()|| - nativeShowBusy_||studioBackupBusy_||catalog_.busy()|| - engine_.isGraphSwitchPending()) - error="MUTE MAIN and STREAM, finish Studio IO before rebind"; - armix::session::MixerSessionDocument doc; - std::vector blobs; - if(error.isEmpty())error=readMixerSessionForRecovery(doc,blobs); - const auto live=engine_.status().getProperty("dryRoutingLab",{}); - if(error.isEmpty()&&static_cast( - live.getProperty("nativeChannelIdPcmActive",false))) - error="Live ChannelId mixer already active; refusing rebind"; - LiveAudioEngine::MixerBindingInspection inspected; - if(error.isEmpty()) - error=engine_.inspectNativeMixerSessionBinding(doc,inspected); - if(error.isEmpty()) { - const auto nonce=juce::Uuid().toDashedString().toLowerCase(); - pendingMixerRebind_={ - nonce,mixerRebindSignature(doc,inspected), - juce::Time::currentTimeMillis()+30000}; - auto encode=[](const armix::session::HardwareBinding& b) { - auto v=std::make_unique(); - v->setProperty("backend",b.backend); - v->setProperty("capture",b.capture); - v->setProperty("playback",b.playback); - v->setProperty("inputMask",b.inputMask); - v->setProperty("outputMask",b.outputMask); - v->setProperty("rate",b.rate); - v->setProperty("frames",b.frames); - return juce::var(v.release()); - }; - ack->setProperty("token",nonce); - ack->setProperty("saved",encode(doc.binding)); - ack->setProperty("current",encode(inspected.live)); - ack->setProperty("changed",inspected.changed); - ack->setProperty("inputs",inspected.callbackInputs); - ack->setProperty("savedMainL",doc.outputs.mainL); - ack->setProperty("savedMainR",doc.outputs.mainR); - ack->setProperty("currentMainL",inspected.pins.outputPhysicalPort(inspected.outputs.mainL)); - ack->setProperty("currentMainR",inspected.pins.outputPhysicalPort(inspected.outputs.mainR)); - ack->setProperty("currentMonitorEnabled",inspected.outputs.monitorEnabled); - juce::Array sources; - for(const auto& patch:doc.request.sources) { - const auto next=std::find_if(inspected.sources.begin(),inspected.sources.end(), - [&](const auto& candidate){return candidate.id==patch.id;}); - auto v=std::make_unique(); - v->setProperty("channelId",armix::session::decimal(patch.id.value)); - v->setProperty("unbound",next==inspected.sources.end()); - if(next!=inspected.sources.end()) { - v->setProperty("left",inspected.pins.inputs.physicalIndex(next->inputL)); - v->setProperty("right",inspected.pins.inputs.physicalIndex(next->inputR)); - v->setProperty("stereo",next->stereo); - } - sources.add(juce::var(v.release())); - } - ack->setProperty("sources",juce::var(sources)); - } - ack->setProperty("ok",error.isEmpty()); - ack->setProperty("error",error); - if(browser_.loaded)browser_.emitEventIfBrowserIsVisible( - "arMixNativeSessionBindingAck",juce::var(ack.release())); - } - - // Startup and ordinary restore never authorize a different endpoint. - juce::String restoreSavedMixerSession(bool approvedRebind=false, - const juce::String& expectedStamp={}) { + juce::String restoreSavedMixerSession(bool startupOnSavedDevice=false) { if(!engine_.allOutputsDisarmed() || mixerSessionWorker_.busy() || nativeShowBusy_ || studioBackupBusy_ || engine_.isGraphSwitchPending()) return "MUTE output and finish Studio IO before restoring mixer"; @@ -1981,6 +1888,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::vector states; const bool retained=engine_.hasRetainedNativeSession(); auto error=readMixerSessionForRecovery(doc,states); + bool usedPrevious=false; + if(error.isNotEmpty()&&!retained&&store.recoverPrevious().isEmpty()) { + error=store.load(doc,states); + usedPrevious=error.isEmpty(); + } if(error.isNotEmpty()) { mixerSessionStatus_=retained?"RETAINED_SESSION_UNAVAILABLE":"DAMAGED_SESSION"; mixerSessionError_=error; @@ -1999,23 +1911,14 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr diagnostics_.record("DYNAMIC_MIXER_VST3_REMAP_REQUIRED",error); return error; } - LiveAudioEngine::MixerBindingInspection current; - if(approvedRebind) { - error=engine_.inspectNativeMixerSessionBinding(doc,current); - if(error.isNotEmpty())return error; - if(expectedStamp.isEmpty() || - mixerRebindSignature(doc,current)!=expectedStamp) - return "STALE_REBIND: saved session or audio device changed"; - } - // Existing live graphs cannot be replaced by startup autosave or - // a stale More-button click. Never demote the true native renderer. + const bool resume=startupOnSavedDevice && !usedPrevious && !retained && + doc.resumeMain.value_or(true); const auto live=engine_.status().getProperty("dryRoutingLab",{}); if(static_cast(live.getProperty("nativeChannelIdPcmActive",false))) { mixerSessionStatus_="LIVE_MIXER_UNCHANGED"; return "Live native mixer already active; refusing to replace it"; } - error=engine_.restoreNativeMixerSession( - std::move(doc),states,approvedRebind?¤t:nullptr); + error=engine_.restoreNativeMixerSession(std::move(doc),states); if(error.isNotEmpty()) { mixerSessionStatus_=error.contains("NEEDS_REMAP") ?"NEEDS_REMAP":"RESTORE_REJECTED"; @@ -2024,29 +1927,35 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return error; } mixerSessionRecoveryPending_=false; - mixerSessionStatus_=approvedRebind?"RESTORED_REBOUND_MUTED":"RESTORED_MUTED"; + if(resume && engine_.liveOutputArmFault(false).isEmpty()) + engine_.setMonitorEnabled(true); + mixerSessionStatus_=engine_.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; mixerSessionError_.clear(); - diagnostics_.record("DYNAMIC_MIXER_RESTORED", - approvedRebind? - "Operator-approved hardware mapping; ChannelId/WIRE/VST3 retained, outputs DISARMED": - "Exact native ChannelId/WIRE/VST3; outputs remain DISARMED"); + diagnostics_.record("DYNAMIC_MIXER_RESTORED",mixerSessionStatus_); + if(usedPrevious)emitNotice("Last verified mixer checkpoint restored with MAIN muted.",true); emitApprovedNativeSnapshot(); return {}; } - // Explicit user SAVE and bounded checkpoint autosave share the same - // transaction. Native owner state only; no browser WIRE or demo scene. - juce::String saveMixerSession(bool automatic=false) { - if(mixerSessionRecoveryPending_) - return "Recover the verified saved session before replacing its disk generation"; + juce::String saveMixerSession(bool resumeMain, const juce::File& exportFile={}) { + const bool automatic=exportFile==juce::File{}; + if(automatic&&mixerSessionRecoveryPending_) + return "The retained mixer checkpoint is awaiting a verified device"; if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_|| - catalog_.busy()||engine_.isGraphSwitchPending()|| - !engine_.allOutputsDisarmed()) - return "Mixer session save requires MUTED output and idle Studio IO"; + catalog_.busy()||engine_.isGraphSwitchPending()) + return "Mixer is busy. Try again after the current operation."; + const bool monitoring=engine_.isMonitorEnabled(); + if(engine_.secondaryArmed())return "Stop STREAM before saving the mixer"; + const auto epoch=engine_.dryRoutingLabEpoch(); + if(monitoring)engine_.setMonitorEnabled(false); armix::session::MixerSessionDocument doc; std::vector states; auto error=engine_.captureNativeMixerSession(doc,states); + if(monitoring && epoch==engine_.dryRoutingLabEpoch() && + engine_.liveOutputArmFault(false).isEmpty()) + engine_.setMonitorEnabled(true); if(error.isNotEmpty())return error; + if(automatic)doc.resumeMain=resumeMain; doc.id=mixerSessionId_.isNotEmpty()?mixerSessionId_: juce::Uuid().toDashedString().toLowerCase(); // Use the verified installed vendor identity; never load using a @@ -2069,25 +1978,97 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr std::move(states), [safe,pendingId,fingerprint,automatic](juce::String failure){ if(safe==nullptr)return; + if(!automatic) { + safe->emitMixerSessionAck("SAVE",failure); + return; + } if(failure.isEmpty()) { safe->mixerSessionId_=pendingId; safe->lastMixerSessionFingerprint_=fingerprint; safe->mixerSessionStatus_="SAVED_VERIFIED_MUTED"; safe->mixerSessionError_.clear(); safe->diagnostics_.record("DYNAMIC_MIXER_SAVED", - automatic?"AUTO_CHECKPOINT":"OPERATOR_SAVE"); + "AUTO_CHECKPOINT"); }else{ safe->mixerSessionStatus_="SAVE_REJECTED"; safe->mixerSessionError_=failure; safe->diagnostics_.record("DYNAMIC_MIXER_SAVE_REJECTED",failure); - if(!automatic)safe->emitNotice("Mixer session not saved: "+failure,true); } - if(!automatic)safe->emitMixerSessionAck("SAVE",failure); - }))return "Mixer session IO worker unavailable"; - mixerSessionStatus_="SAVING"; + },exportFile))return "Mixer session IO worker unavailable"; + if(automatic)mixerSessionStatus_="SAVING"; return {}; } + void openMixerFile(const juce::File& file) { + const auto chosenEpoch=engine_.dryRoutingLabEpoch(); + auto safe=juce::Component::SafePointer(this); + if(!mixerSessionWorker_.load(file,[safe,chosenEpoch,file](juce::String error, + armix::session::MixerSessionDocument doc, + std::vector states) { + if(safe==nullptr)return; + auto& engine=safe->engine_; + if(error.isEmpty() && (safe->nativeShowBusy_||safe->studioBackupBusy_|| + safe->catalog_.busy()||engine.isGraphSwitchPending()|| + chosenEpoch!=engine.dryRoutingLabEpoch())) + error="Mixer or audio device changed while opening the file"; + if(error.isEmpty()&&engine.secondaryArmed()) + error="Stop STREAM before opening a mixer"; + if(error.isEmpty())error=safe->resolveMixerSessionCatalog(doc,false); + if(error.isEmpty()) { + const auto id=doc.id; + bool sameOutputs=false; + const bool monitoring=engine.isMonitorEnabled(); + error=engine.restoreNativeMixerSession(std::move(doc),states,true,&sameOutputs); + if(monitoring&&sameOutputs&&error.isEmpty()&& + chosenEpoch==engine.dryRoutingLabEpoch()&&engine.liveOutputArmFault(false).isEmpty()) + engine.setMonitorEnabled(true); + if(error.isEmpty()) { + safe->closePluginEditor(); + safe->stopOrbit(); + safe->mixerSessionId_=id; + safe->mixerSessionRecoveryPending_=false; + safe->lastMixerSessionFingerprint_.clear(); + safe->mixerSessionStatus_=engine.isMonitorEnabled()?"RESTORED_MONITORING":"RESTORED_MUTED"; + safe->mixerSessionError_.clear(); + safe->lastMixerFile_=file; + safe->emitApprovedNativeSnapshot(); + } + } + safe->emitMixerSessionAck("OPEN",error); + }))emitMixerSessionAck("OPEN","Mixer file operation already in progress"); + } + + void chooseMixerFile(bool save) { + if(mixerFileDialogOpen_)return; + const auto operation=save?"SAVE":"OPEN"; + if(mixerSessionWorker_.busy()||nativeShowBusy_||studioBackupBusy_) + return emitMixerSessionAck(operation,"Mixer file operation already in progress"); + auto start=lastMixerFile_; + if(start==juce::File{}) { + start=juce::File::getSpecialLocation(juce::File::userDocumentsDirectory); + if(save)start=start.getChildFile("Mixer.smix"); + } + mixerFileDialogOpen_=true; + mixerFileChooser_=std::make_unique( + save?"Save mixer":"Open mixer",start,"*.smix",true); + using BrowserFlags=juce::FileBrowserComponent; + mixerFileChooser_->launchAsync(BrowserFlags::canSelectFiles | + (save?(BrowserFlags::saveMode|BrowserFlags::warnAboutOverwriting):BrowserFlags::openMode), + [safe=juce::Component::SafePointer(this),save,operation] + (const juce::FileChooser& picker) { + if(safe==nullptr)return; + safe->mixerFileDialogOpen_=false; + auto file=picker.getResult(); + if(file==juce::File{})return; + if(!save)return safe->openMixerFile(file); + if(!file.hasFileExtension(".smix")) + return safe->emitMixerSessionAck(operation,"Use the .smix file extension"); + safe->lastMixerFile_=file; + const auto error=safe->saveMixerSession(false,file); + if(error.isNotEmpty())safe->emitMixerSessionAck(operation,error); + }); + } + void onAction (const juce::var& args) { const auto action = args.getProperty ("action", {}).toString(); @@ -2871,58 +2852,8 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr return; } - if(action=="nativeSessionInspect") { - emitMixerSessionAck("INSPECT", - mixerSessionStatus_=="DAMAGED_SESSION"?mixerSessionError_:juce::String{}); - return; - } - if(action=="nativeSessionInspectRebind") { - previewMixerDeviceRebind(); - return; - } - if(action=="nativeSessionRebind") { - // The one-use token is consumed even on failure. Revalidate the - // entire saved document and live device just before publication. - const auto approved=pendingMixerRebind_; - pendingMixerRebind_={}; - juce::String result; - if(!value.isString() || approved.nonce.isEmpty() || - value.toString()!=approved.nonce || - juce::Time::currentTimeMillis()>approved.expiresAt) - result="STALE_REBIND: request expired or not confirmed"; - else result=restoreSavedMixerSession(true,approved.signature); - if(result.isNotEmpty()) { - mixerSessionStatus_="REBIND_REJECTED"; - mixerSessionError_=result; - emitNotice("MIXER SESSION: "+result,true); - } - emitMixerSessionAck("REBIND",result); - return; - } - if(action=="nativeSessionSave" || action=="nativeSessionRestore" || - action=="nativeSessionRecover") { - juce::String result; - if(action=="nativeSessionSave")result=saveMixerSession(false); - else if(action=="nativeSessionRestore") - result=restoreSavedMixerSession(); - else { - if(!engine_.allOutputsDisarmed()||mixerSessionWorker_.busy()|| - nativeShowBusy_||studioBackupBusy_) - result="MUTE output and finish IO before last-good recovery"; - else { - armix::session::NativeMixerSessionStore store(settingsDirectory()); - result=store.recoverPrevious(); - if(result.isEmpty()) { - mixerSessionStatus_="RECOVERED_ON_DISK_MUTED"; - mixerSessionError_.clear(); - diagnostics_.record("DYNAMIC_MIXER_LAST_GOOD_RECOVERED", - "Disk pointer restored; manual load still required"); - } - } - } - if(result.isNotEmpty())emitNotice("MIXER SESSION: "+result,true); - emitMixerSessionAck(action=="nativeSessionSave"?"SAVE": - action=="nativeSessionRestore"?"RESTORE":"RECOVER",result); + if(action=="nativeMixerFileSave"||action=="nativeMixerFileOpen") { + chooseMixerFile(action=="nativeMixerFileSave"); return; } if (action == "routingDryShowSave") @@ -3900,7 +3831,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr mixerSessionStartupInspected_=true; if(armix::session::NativeMixerSessionStore(settingsDirectory()).exists()){ mixerSessionRecoveryPending_=true; - const auto error=restoreSavedMixerSession(); + const auto error=restoreSavedMixerSession(saved!=nullptr && startupError_.isEmpty()); if(error.isNotEmpty()) emitNotice("Saved mixer retained; "+error,true); } @@ -3934,7 +3865,7 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr engine_.allOutputsDisarmed() && !mixerSessionWorker_.busy() && !nativeShowBusy_ && !studioBackupBusy_ && !catalog_.busy() && !engine_.isGraphSwitchPending() && !engine_.hasTemporaryDiagnosticDevice()) - (void)saveMixerSession(true); + (void)saveMixerSession(false); if (engine_.finalizeGraphSwitch()) { ++fxGraphRevision_; diff --git a/src/NativeMixerSessionDocument.h b/src/NativeMixerSessionDocument.h index a189fc1bd..a38f02a94 100644 --- a/src/NativeMixerSessionDocument.h +++ b/src/NativeMixerSessionDocument.h @@ -1,5 +1,6 @@ // SPDX-License-Identifier: AGPL-3.0-only #pragma once +#include #include "../engine/core/UnifiedLegacyProductionAdmission.h" #include "NativeShowStore.h" #include @@ -39,6 +40,8 @@ struct MixerSessionDocument final { std::vector rackBypassed; float masterGain=1.f; bool masterMute=false,masterMono=false; + // Internal checkpoint preference, distinct from the hardware monitor pair. + std::optional resumeMain; std::uint64_t acceptedRevision=0; juce::int64 savedMs=0; }; @@ -100,7 +103,7 @@ struct MixerDeviceBindingPolicy final { if(sameBinding(document.binding,live) && sameOutputs(document.outputs,outputs)) return {}; if(!operatorApproved) - return "NEEDS_REMAP: different device, pin mask, outputs or rate; confirm rebind"; + return "NEEDS_REMAP: select the saved audio device and pin layout in Audio I/O"; if(oldPins!=newPins) { auto& sources=document.request.sources; @@ -211,6 +214,7 @@ class Codec final { set(root,"id",d.id); set(root,"acceptedRevision",decimal(d.acceptedRevision)); set(root,"savedMs",decimal(static_cast(d.savedMs))); + if(d.resumeMain.has_value())set(root,"resumeMain",*d.resumeMain); set(root,"legacyIds",ids(d.legacyIds)); auto bind=object(); set(bind,"backend",d.binding.backend); @@ -291,6 +295,11 @@ class Codec final { if(!root.isObject()||get(root,"schema").toString()!="arsonmix.mixer-session.v1") return false; MixerSessionDocument doc; + if(root.getDynamicObject()->hasProperty("resumeMain")) { + bool resume=false; + if(!strictBool(get(root,"resumeMain"),resume))return false; + doc.resumeMain=resume; + } if(!textField(get(root,"id"),doc.id,48)|| !armix::shows::detail::uuid(doc.id)|| !parseDecimal(get(root,"acceptedRevision"),doc.acceptedRevision)|| diff --git a/src/NativeMixerSessionSaveWorker.h b/src/NativeMixerSessionSaveWorker.h index 6c4494dd9..6e39dd5e0 100644 --- a/src/NativeMixerSessionSaveWorker.h +++ b/src/NativeMixerSessionSaveWorker.h @@ -15,6 +15,8 @@ namespace armix::session { class NativeMixerSessionSaveWorker final : private juce::Thread { public: using Completion=std::function; + using ReadCompletion=std::function)>; NativeMixerSessionSaveWorker():juce::Thread("ArSonMix MixerSession IO"){} ~NativeMixerSessionSaveWorker() override { alive_->store(false,std::memory_order_release); @@ -22,43 +24,67 @@ class NativeMixerSessionSaveWorker final : private juce::Thread { stopThread(-1); } bool busy() const noexcept {return busy_.load(std::memory_order_acquire);} + void finishForShutdown() { + waitForThreadToExit(-1); + busy_.store(false,std::memory_order_release); + done_={};readDone_={};states_.clear(); + } bool save(juce::File studio,MixerSessionDocument document, std::vector binary, - Completion completion) { + Completion completion,juce::File exportFile={}) { if(busy_.exchange(true,std::memory_order_acq_rel))return false; studio_=std::move(studio); + exportFile_=std::move(exportFile); doc_=std::move(document); states_=std::move(binary); done_=std::move(completion); + return start(); + } + bool load(juce::File file,ReadCompletion completion) { + if(busy_.exchange(true,std::memory_order_acq_rel))return false; + exportFile_=std::move(file); + readDone_=std::move(completion); + return start(); + } +private: + bool start() { + ++serial_; if(!startThread()){ busy_.store(false,std::memory_order_release); - done_={};states_.clear(); + done_={};readDone_={};states_.clear(); return false; } return true; } -private: void run() override { juce::String error; try { NativeMixerSessionStore store(studio_); - error=store.commit(doc_,states_); + if(readDone_)error=NativeMixerSessionStore::readFile(exportFile_,doc_,states_); + else error=exportFile_==juce::File{}?store.commit(doc_,states_): + NativeMixerSessionStore::writeFile(exportFile_,doc_,states_); }catch(...) {error="Mixer session IO worker exception";} // Release potentially large VST3 binary buffers before callback. - states_.clear(); + if(!readDone_)states_.clear(); auto alive=alive_; - juce::MessageManager::callAsync([this,alive,error]() mutable { - if(!alive->load(std::memory_order_acquire))return; + const auto serial=serial_; + juce::MessageManager::callAsync([this,alive,error,serial]() mutable { + if(!alive->load(std::memory_order_acquire)||serial!=serial_)return; busy_.store(false,std::memory_order_release); auto callback=std::move(done_); done_={}; - if(callback)callback(std::move(error)); + auto readCallback=std::move(readDone_); + readDone_={}; + if(readCallback)readCallback(std::move(error),std::move(doc_),std::move(states_)); + else if(callback)callback(std::move(error)); }); } - juce::File studio_; + juce::File studio_,exportFile_; MixerSessionDocument doc_; std::vector states_; Completion done_; + ReadCompletion readDone_; + unsigned serial_=0; std::atomic busy_{false}; std::shared_ptr> alive_= std::make_shared>(true); diff --git a/src/NativeMixerSessionStore.h b/src/NativeMixerSessionStore.h index 587ca40b5..da614918e 100644 --- a/src/NativeMixerSessionStore.h +++ b/src/NativeMixerSessionStore.h @@ -89,6 +89,82 @@ class NativeMixerSessionStore final { return writePointer(head,id); } + // A single portable JSON file, with content-addressed plug-in state. + static juce::String writeFile(const juce::File& file,MixerSessionDocument doc, + const std::vector& states) { + doc.resumeMain.reset(); + const auto json=Codec::encode(doc); + MixerSessionDocument verified; + if(!Codec::decode(json,verified))return "Cannot encode mixer file"; + auto root=juce::JSON::parse(json); + auto blobs=juce::var(new juce::DynamicObject()); + std::set hashes,referenced; + for(const auto& insert:doc.inserts)referenced.insert(insert.sha256); + juce::int64 total=0; + for(const auto& state:states) { + const auto size=static_cast(state.bytes.getSize()); + total+=size; + if(!safeHash(state.sha256)||!hashes.insert(state.sha256).second|| + size>maxState||total>maxTotal|| + juce::SHA256(state.bytes).toHexString()!=state.sha256) + return "Invalid mixer plug-in state"; + blobs.getDynamicObject()->setProperty(state.sha256, + juce::Base64::toBase64(state.bytes.getData(),state.bytes.getSize())); + } + if(hashes!=referenced||hashes.size()>maxStates) + return "Incomplete mixer plug-in state"; + root.getDynamicObject()->setProperty("pluginState",blobs); + juce::TemporaryFile staging(file); + if(!staging.getFile().replaceWithText(juce::JSON::toString(root,false)) || + !staging.overwriteTargetFileWithTemporary()) + return "Could not write mixer file"; + return {}; + } + + static juce::String readFile(const juce::File& file,MixerSessionDocument& out, + std::vector& states) { + constexpr auto maxFile=maxJson+(maxTotal*4/3)+maxStates*80; + const auto size=file.getSize(); + if(!file.hasFileExtension(".smix")||!file.existsAsFile()||size<1||size>maxFile) + return "Mixer file is missing, invalid or too large"; + juce::FileInputStream input(file); + juce::MemoryBlock contents; + if(!input.openedOk()||input.readIntoMemoryBlock(contents,maxFile+1)>maxFile) + return "Could not read mixer file"; + auto root=juce::JSON::parse(contents.toString()); + if(!root.isObject())return "Invalid mixer JSON"; + const auto blobs=root.getProperty("pluginState",{}); + if(!blobs.isObject())return "Mixer plug-in state is missing"; + root.getDynamicObject()->removeProperty("pluginState"); + root.getDynamicObject()->removeProperty("resumeMain"); + MixerSessionDocument doc; + if(!Codec::decode(juce::JSON::toString(root,false),doc)) + return "Invalid mixer session"; + std::set referenced; + for(const auto& insert:doc.inserts)referenced.insert(insert.sha256); + const auto& properties=blobs.getDynamicObject()->getProperties(); + if(referenced.size()>maxStates||static_cast(referenced.size())!=properties.size()) + return "Incomplete mixer plug-in state"; + std::vector verified; + juce::int64 total=0; + for(const auto& hash:referenced) { + const auto state=blobs.getProperty(hash,{}); + if(!safeHash(hash)||!state.isString()||state.toString().length()>((maxState+2)/3)*4) + return "Invalid mixer plug-in state"; + juce::MemoryOutputStream decoded; + if(!juce::Base64::convertFromBase64(decoded,state.toString())) + return "Invalid mixer plug-in state encoding"; + const auto bytes=static_cast(decoded.getDataSize()); + total+=bytes; + if(bytes>maxState||total>maxTotal||juce::SHA256(decoded.getMemoryBlock()).toHexString()!=hash) + return "Mixer plug-in state failed verification"; + verified.push_back({hash,decoded.getMemoryBlock()}); + } + out=std::move(doc); + states=std::move(verified); + return {}; + } + // Read normal HEAD only: no silent fallback to an older performance. juce::String load(MixerSessionDocument& out, std::vector& states) const { @@ -110,7 +186,7 @@ class NativeMixerSessionStore final { MixerSessionDocument current; std::vector currentStates; if(load(current,currentStates).isEmpty()) - return "Saved disk generation is verified. Use Restore Saved Mixer or Rebind Current Device for audio recovery."; + return "Saved mixer generation is already verified"; const auto pointer=readPointer(root_.getChildFile("PREVIOUS")); if(pointer.isEmpty())return "Last-good mixer pointer missing"; MixerSessionDocument verified; diff --git a/tests/approved_native_cold_start_smoke.py b/tests/approved_native_cold_start_smoke.py index ebfb715e5..1c02fbcbb 100644 --- a/tests/approved_native_cold_start_smoke.py +++ b/tests/approved_native_cold_start_smoke.py @@ -66,58 +66,18 @@ def show_select(value): const available=name=>buttons.find(b=>b.textContent===name)?.disabled===false; return {recall:available('Recall Show'),recover:available('Recover Last Good')}; }""",[show_panel,value]) - # The full dynamic ChannelId session is not the fixed ShowV2 - # and always passes through the real JUCE backend authority. - show_click("Save Mixer Session") - assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeSessionSave" - emit(page,"arMixNativeSessionAck",{ - "operation":"SAVE","ok":True,"state":"SAVED_VERIFIED_MUTED"}) - assert "SAVED_VERIFIED_MUTED" in page.locator(show_panel).text_content() - show_click("Restore Saved Mixer") - assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeSessionRestore" - emit(page,"arMixNativeSessionAck",{ - "operation":"RESTORE","ok":False,"state":"NEEDS_REMAP", - "error":"NEEDS_REMAP: physical ASIO input mask changed"}) - assert "NEEDS_REMAP" in page.locator(show_panel).text_content() - # Native device rebind requires an explicit preview and dialog. - # Cancelling must NOT send a rebind intent to the JUCE dispatcher. - show_click("Rebind Current Device…") - assert page.evaluate("()=>window.__events.at(-1).payload.action")==\ - "nativeSessionInspectRebind" - preview={"ok":True,"token":"test-one-time-approval", - "saved":{"backend":"ASIO","capture":"Old","playback":"Old", - "inputMask":"3","outputMask":"3","rate":48000}, - "current":{"backend":"WASAPI","capture":"New","playback":"New", - "inputMask":"5","outputMask":"3","rate":44100}, - "inputs":2,"savedMainL":0,"savedMainR":1, - "currentMainL":1,"currentMainR":0, - "sources":[{"channelId":"1","unbound":True}]} - preview_messages=[] - def dismiss_preview(dialog): - preview_messages.append(dialog.message) - dialog.dismiss() - page.once("dialog",dismiss_preview) - emit(page,"arMixNativeSessionBindingAck",preview) - assert "CH 1 ← UNBOUND · select IN after rebind" in preview_messages[0] - assert page.evaluate("()=>window.__events.at(-1).payload.action")==\ - "nativeSessionInspectRebind" - show_click("Rebind Current Device…") - page.once("dialog",lambda dialog:dialog.accept()) - emit(page,"arMixNativeSessionBindingAck",preview) - assert page.evaluate("()=>window.__events.at(-1).payload")=={ - "action":"nativeSessionRebind","value":"test-one-time-approval"} - emit(page,"arMixNativeSessionAck",{ - "operation":"REBIND","ok":True,"state":"RESTORED_REBOUND_MUTED"}) - assert "RESTORED_REBOUND_MUTED" in page.locator(show_panel).text_content() - # Rebind path never triggers an implicit monitor/stream ARM. - assert not page.evaluate( - "()=>window.__events.some(e=>e.payload?.action==='monitor')") - show_click("Recover Previous Mixer") - assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeSessionRecover" - emit(page,"arMixNativeSessionAck",{ - "operation":"RECOVER","ok":True,"state":"RECOVERED_ON_DISK_MUTED"}) - assert "RECOVERED_ON_DISK_MUTED" in page.locator(show_panel).text_content() - # None of these three operations authorizes physical MONITOR. + toolbar=page.locator(".command-bar") + for caption,icon in [("Save","mixer-save.svg"),("Open","mixer-open.svg")]: + button=toolbar.get_by_role("button",name=caption,exact=True) + assert button.locator("img").get_attribute("src")=="assets/"+icon + assert button.locator("img").evaluate("el=>el.complete && el.naturalWidth>0") + button.click() + assert page.evaluate("()=>window.__events.at(-1).payload.action")=="nativeMixerFile"+caption + for name in ["Save Mixer Session","Restore Saved Mixer", + "Rebind Current Device…","Recover Previous Mixer"]: + assert page.get_by_role("button",name=name,exact=True).count()==0 + emit(page,"arMixNativeSessionAck",{"operation":"OPEN","ok":False,"error":"Invalid mixer JSON"}) + assert page.get_by_text("Invalid mixer JSON",exact=True).count()>=1 assert not page.evaluate("()=>window.__events.some(e=>e.payload?.action==='monitor')") show_click("Browse Shows") assert page.evaluate("()=>window.__events.at(-1).payload.action")=="routingDryShowList" diff --git a/tests/approved_native_wire_gain_smoke.py b/tests/approved_native_wire_gain_smoke.py index 221aa544f..23880055c 100644 --- a/tests/approved_native_wire_gain_smoke.py +++ b/tests/approved_native_wire_gain_smoke.py @@ -103,6 +103,31 @@ def main(): emit(page, "arMixConsoleSnapshot", state) assert page.evaluate("()=>window.__heldStrip===document.querySelector('#tracks .strip[data-id=\"2\"]')"), "scalar edit rebuilt strip" assert float(page.locator('#tracks .strip[data-id="2"] .wire-gain').input_value()) == -60 + # Drag the actual receiving knob with native ACKs mid-gesture. + pot = knob.locator("..").bounding_box() + assert pot + x, y = pot["x"]+pot["width"]/2, pot["y"]+pot["height"]/2 + page.mouse.move(x,y) + page.mouse.down() + page.mouse.move(x,y-32,steps=5) + page.wait_for_function("()=>window.__nativeIntents.length===3") + coarse = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert float(knob.input_value()) == -56 + page.keyboard.down("Shift") + page.mouse.move(x,y-56,steps=4) + page.keyboard.up("Shift") + assert float(knob.input_value()) == -55.5 + state["graph"]["edges"][1]["gainLinear"] = coarse["payload"]["gainLinear"] + ack(page,state,coarse) + emit(page,"arMixConsoleSnapshot",state) + assert float(knob.input_value()) == -55.5 + page.mouse.up() + page.wait_for_function("()=>window.__nativeIntents.length===4") + final = page.evaluate("()=>window.__nativeIntents.at(-1)") + assert abs(final["payload"]["gainLinear"] - 10**(-55.5/20)) < 1e-8 + state["graph"]["edges"][1]["gainLinear"] = final["payload"]["gainLinear"] + ack(page,state,final) + emit(page,"arMixConsoleSnapshot",state) # OUT to the same INPUT is the existing exclusive native transaction. page.locator('#tracks .strip[data-id="1"] select[data-field="output"]').select_option(label="CH04") route = page.evaluate("()=>window.__nativeIntents.at(-1)") diff --git a/tests/native_mixer_session_store_test.cpp b/tests/native_mixer_session_store_test.cpp index ffe17915e..724d32219 100644 --- a/tests/native_mixer_session_store_test.cpp +++ b/tests/native_mixer_session_store_test.cpp @@ -126,7 +126,8 @@ static void nativeDeviceRecovery() { LiveDryRoutingLab mixer; mixer.prepareDevice(&device); const auto restore=[&](const MixerSessionDocument& doc, - const std::vector& states,bool disarmed) { + const std::vector& states,bool disarmed, + bool replaceActive=false) { armix::device::JuceActivePortSnapshot pins; armix::device::JuceActivePortSnapshot::Fault fault; assert(armix::device::JuceActivePortSnapshot::capture(&device,mixer.epoch(),pins,fault)); @@ -134,7 +135,7 @@ static void nativeDeviceRecovery() { const auto preparation=NativeMixerSessionFxRestore::prepare(doc,states,formats, device.rate,doc.request.maxFrames,pins.epoch,mixer.nativeGraphRevisionForRestore(),bank); if(preparation.isNotEmpty())return preparation; - return mixer.restoreNativeMixerSession(doc,std::move(bank),pins,disarmed); + return mixer.restoreNativeMixerSession(doc,std::move(bank),pins,disarmed,replaceActive); }; assert(!mixer.ready() && mixer.revision()==0); // no compatibility PCM publisher assert(restore(verified,{},true).isNotEmpty()); @@ -162,6 +163,19 @@ static void nativeDeviceRecovery() { process(false); assert(outL.back()>.05f && outR.back()>.025f); + // Portable Open may replace a live session only on an explicit muted + // publication. Invalid FX must leave the accepted graph and PCM intact. + const auto liveRevision=mixer.controlRevision(); + assert(restore(verified,blobs,true).isNotEmpty()); + assert(restore(verified,{},true,true).isNotEmpty()); + assert(mixer.controlRevision()==liveRevision); + process(false); + assert(outL.back()>.05f && outR.back()>.025f); + assert(restore(verified,blobs,true,true).isEmpty()); + assert(mixer.controlRevision()>liveRevision); + process(false); + assert(outL.back()>.05f && outR.back()>.025f); + // Reopen repeatedly. The field failure had retained channels, FX and // WIRE, but no live legacy lease for the new 48 kHz/480 frame epoch. for(int attempt=0;attempt<3;++attempt) { @@ -353,6 +367,25 @@ int main(){ std::vector readback; assert(store.load(loaded,readback).isEmpty()); assert(readback.size()==1&&readback[0].bytes==binary.bytes); + // Legacy JSON lacks a preference. Both explicit settings survive checkpoint + // round trips, and portable files cannot request MAIN authorization. + assert(!loaded.resumeMain.has_value()); + d.resumeMain=true; + MixerSessionDocument roundTrip; + assert(Codec::decode(Codec::encode(d),roundTrip)&&roundTrip.resumeMain==true); + d.resumeMain=false; + assert(Codec::decode(Codec::encode(d),roundTrip)&&roundTrip.resumeMain==false); + const auto portable=studio.getChildFile("Live.smix"); + assert(NativeMixerSessionStore::writeFile(portable,d,{binary}).isEmpty()); + assert(NativeMixerSessionStore::readFile(portable,roundTrip,readback).isEmpty()); + assert(!roundTrip.resumeMain.has_value()); + assert(roundTrip.request.sources.size()==d.request.sources.size()); + assert(readback.size()==1&&readback[0].bytes==binary.bytes); + auto tampered=juce::JSON::parse(portable.loadFileAsString()); + tampered.getProperty("pluginState",{}).getDynamicObject()->setProperty(binary.sha256,"AAAA"); + assert(portable.replaceWithText(juce::JSON::toString(tampered))); + assert(NativeMixerSessionStore::readFile(portable,roundTrip,readback).isNotEmpty()); + assert(readback.size()==1&&readback[0].bytes==binary.bytes); const auto firstId=studio.getChildFile("MixerSession").getChildFile("HEAD") .loadFileAsString().trim(); assert(armix::shows::detail::uuid(firstId)); diff --git a/web/approved-native-bridge.js b/web/approved-native-bridge.js index 6a4561b44..4920ac149 100644 --- a/web/approved-native-bridge.js +++ b/web/approved-native-bridge.js @@ -485,7 +485,7 @@ return true; } scope?.syncNativeWireGains?.(next.graph.edges.filter(e=>e.enabled&&e.primaryOutput===false) - .map(e=>({id:uiByWireId.get(e.edgeId),levelDb:Math.round(Math.max(-60,Math.min(6, + .map(e=>({id:uiByWireId.get(e.edgeId),pending:pendingWireGains.has(e.edgeId),levelDb:Math.round(Math.max(-60,Math.min(6, e.gainLinear>0?20*Math.log10(e.gainLinear):-60))*10)/10}))); // Immutable graph topology is identical: update actual scalar controls // only. Never detach the active HTML select or the captured fader pointer. @@ -1324,7 +1324,8 @@ function syncMonitorButton(d) { const monitorButton=document.querySelector?.("[data-native-monitor]"); if(monitorButton){ - monitorButton.textContent=d?.outputArmed?"MONITOR OFF":"MONITOR ON"; + monitorButton.textContent=d?.outputArmed?"Monitor On":"Monitor Off"; + monitorButton.setAttribute("aria-pressed",String(!!d?.outputArmed)); monitorButton.title=d?.outputArmed? "Mute actual MAIN output immediately":"Listen through verified MAIN hardware output"; monitorButton.disabled=!d?.outputArmed && !deviceReady(); @@ -1915,111 +1916,59 @@ } }); - // One durable ChannelId MixerSession, separate from the limited legacy - // ShowV2. These buttons NEVER stage browser-only mixer/FX state. - const sessionHeading=item("span","more-tools-caption", - "STUDIO / COMPLETE MIXER SESSION"); - const sessionSave=item("button","tool","Save Mixer Session"); - const sessionRestore=item("button","tool","Restore Saved Mixer"); - const sessionRebind=item("button","tool","Rebind Current Device…"); - const sessionRecover=item("button","tool","Recover Previous Mixer"); - const sessionState=item("span","more-tools-caption", - "Checking native ChannelId session…"); - sessionState.style.whiteSpace="normal"; - sessionState.dataset.nativeSessionState="true"; - const sessionAction=(action)=>{ - if(hardware?.device?.outputArmed!==false || - hardware?.raw?.monitor===true){ - status("Mixer session: first MUTE physical output and STREAM"); - return; - } - backend.emitEvent("arMixAction",{action}); - sessionState.textContent=action==="nativeSessionSave"? - "Capturing native ChannelIds, WIRE, FX and vendor state…": - "Verifying saved native session and hardware identity…"; - }; - sessionSave.addEventListener("click",()=>sessionAction("nativeSessionSave")); - sessionRestore.addEventListener("click",()=>sessionAction("nativeSessionRestore")); - sessionRebind.addEventListener("click",()=>sessionAction("nativeSessionInspectRebind")); - sessionRecover.addEventListener("click",()=>sessionAction("nativeSessionRecover")); - backend.addEventListener("arMixNativeSessionBindingAck",ack=>{ - if(ack?.ok!==true||typeof ack.token!=="string"){ - sessionState.textContent="REBIND REJECTED · "+ - String(ack?.error||"No native hardware readback"); - status(sessionState.textContent);return; - } - const saved=ack.saved||{},live=ack.current||{}; - const describe=b=>String(b.backend||"?")+" · "+String(b.capture||"?")+ - " → "+String(b.playback||"?")+" · IN 0x"+String(b.inputMask||"?")+ - " / OUT 0x"+String(b.outputMask||"?")+" · "+String(b.rate||"?")+" Hz"; - const sources=Array.isArray(ack.sources)?ack.sources:[]; - const pins=sources.slice(0,12).map(s=>"CH "+s.channelId+" ← "+ - (s.unbound?"UNBOUND · select IN after rebind": - "IN "+(Number(s.left)+1)+(s.stereo?"/"+(Number(s.right)+1):""))).join("\n"); - const message="REBIND MIXER TO CURRENT PHYSICAL DEVICE?\n\n"+ - "Saved: "+describe(saved)+"\n\nCurrent: "+describe(live)+ - "\nCurrent MAIN physical output pins: "+ - (Number(ack.currentMainL)+1)+"/"+(Number(ack.currentMainR)+1)+ - "\nSaved MAIN pair (callback ordinals): "+(Number(ack.savedMainL)+1)+"/"+ - (Number(ack.savedMainR)+1)+ - "\nInput callback pins: "+String(ack.inputs)+ - "\n\nProposed physical input assignments:"+ - (pins?"\n"+pins:"\nNo physical sources")+ - (sources.length>12?"\n…plus "+(sources.length-12)+" more sources":"")+ - "\n\nVERIFY actual ASIO/WASAPI pin wiring and the MAIN output pair."+ - "\nChannelIds, GROUP/WIRE and FX are retained. Physical output stays MUTED."+ - "\nSave Mixer Session after verifying the new binding. Continue?"; - if(window.confirm(message)){ - backend.emitEvent("arMixAction",{action:"nativeSessionRebind",value:ack.token}); - sessionState.textContent="Verifying unchanged hardware and reconstructing native FX…"; - }else sessionState.textContent="Rebind cancelled · current mixer untouched"; - }); backend.addEventListener("arMixNativeSessionAck",ack=>{ - const state=String(ack?.state||"UNAVAILABLE"); - sessionState.textContent=state+(ack?.error?" · "+String(ack.error):""); - if(ack?.operation==="INSPECT")return; - if(ack?.ok===true){ - status(ack.operation==="SAVE"? - "Verified native MixerSession written; output remains MUTED": - (ack.operation==="RESTORE"||ack.operation==="REBIND")? - "Mixer Session restored MUTED; verify physical pins and explicitly enable MONITOR": - "Previous MixerSession generation recovered on disk; RESTORE explicitly"); - controller?.subscribe(); - }else{ - status("MIXER SESSION: "+String(ack?.error||"No native ACK")); - nativeToast(String(ack?.error||"Mixer operation rejected")); + const save=ack?.operation==="SAVE"; + if(!save&&ack?.operation!=="OPEN")return; + if(ack.ok!==true){ + const error=String(ack.error||"Mixer file operation failed"); + status(error);nativeToast(error); + return; } - }); - backend.addEventListener("arMixStatus",state=>{ - const next=state?.mixerSessionStatus; - if(typeof next!=="string"||!next)return; - const label=next+(state.mixerSessionError?" · "+String(state.mixerSessionError):""); - if(sessionState.textContent!==label)sessionState.textContent=label; + const message=save?"Mixer saved as .smix":"Mixer opened"; + status(message);nativeToast(message); + if(!save)controller?.subscribe(); }); menu.append(caption,setup,muteBtn,hardwareNote, healthTitle,mark,report,advanced, - sessionHeading,sessionSave,sessionRestore,sessionRebind,sessionRecover,sessionState, showHeading,showSave,showBrowse,showSelect,showUpdate,showRecall,showRecover,showNote); // Single discoverable AUDIO I/O button next to ordinary mixer tools. // The existing More entry remains a shortcut to THIS SAME panel. const toolbar=document.querySelector(".command-bar"); if(toolbar && !toolbar.querySelector("[data-native-io]")){ + const firstTool=toolbar.firstElementChild; + for(const [caption,action,icon] of [ + ["Save","nativeMixerFileSave","mixer-save.svg"], + ["Open","nativeMixerFileOpen","mixer-open.svg"] + ]){ + const button=item("button","tool mixer-file-tool",caption); + button.type="button"; + button.title=caption+" mixer (.smix)"; + const image=document.createElement("img"); + image.src="assets/"+icon; + image.alt=""; + image.width=image.height=16; + button.prepend(image); + button.addEventListener("click",()=>backend.emitEvent("arMixAction",{action})); + toolbar.insertBefore(button,firstTool); + } const io=item("button","tool","Audio I/O"); io.dataset.nativeIo="true"; io.title="Select ASIO/WASAPI driver and capture/playback device"; io.addEventListener("click",openNativeAudioIO); toolbar.insertBefore(io,document.getElementById("moreTools")); - const monitor=item("button","tool","MONITOR ON"); + const monitor=item("button","tool","Monitor Off"); monitor.dataset.nativeMonitor="true"; monitor.addEventListener("click",()=>{ const armed=hardware?.device?.outputArmed===true; - if(!armed && (!deviceReady()||legacy()?.routeAccepted!==true || + if(!armed && (!deviceReady()|| + (mixerSession()?.authority!=="CHANNEL_ID"&&legacy()?.routeAccepted!==true)|| virtualCableFeedbackPair())){ status("MONITOR OFF · select real input and safe playback device"); return; } const ep=safeNativeCounter(hardware?.device?.epoch), - rev=safeNativeCounter(legacy()?.routingRevision); + rev=safeNativeCounter(mixerSession()?.authority==="CHANNEL_ID"? + mixerSession()?.routeRevision:legacy()?.routingRevision); if(!armed&&(ep===null||rev===null))return; backend.emitEvent("arMixAction",{action:"monitor",value:!armed, requestId:"manual-monitor-"+(++m4RequestSerial), @@ -2213,7 +2162,7 @@ // Never destroy an active pointer capture. Once the user releases, // restore only the last independently accepted native controls. if(flags.acceptedGraphConnected && (scope.activeFaderId??-1)<0){ - if(!document.activeElement?.matches?.(".strip select")) + if(!scope.wireGainDragging && !document.activeElement?.matches?.(".strip select,.wire-gain")) scope.render?.(); controller.subscribe(); if(state.current)paintNativeMeters(state.current); @@ -2500,6 +2449,7 @@ const edge=scope?.wireEdges?.find(e=>e.id===Number(el.dataset.wireId)&&e.destId===t.id); if(!edge||!requestWireGain({sourceId:edge.sourceId,edgeId:edge.id,levelDb:Number(el.value)})) status("WIRE gain unavailable · accepted parallel send required"); + else scope.paintWireKnob?.(el,Number(el.value)); return true; } if(field==="input"){ From 9efa9a2d15eba731de79f884c8557c14eda8c377 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 19:26:39 +0700 Subject: [PATCH 218/219] Resume exact mixer binding when Windows uses its verified default --- src/Main.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/Main.cpp b/src/Main.cpp index 2bb32269c..c31dcdf05 100644 --- a/src/Main.cpp +++ b/src/Main.cpp @@ -3831,9 +3831,11 @@ class ConsoleWindow final : public juce::DocumentWindow, private juce::Timer, pr mixerSessionStartupInspected_=true; if(armix::session::NativeMixerSessionStore(settingsDirectory()).exists()){ mixerSessionRecoveryPending_=true; - const auto error=restoreSavedMixerSession(saved!=nullptr && startupError_.isEmpty()); + const auto error=restoreSavedMixerSession(startupError_.isEmpty()); if(error.isNotEmpty()) emitNotice("Saved mixer retained; "+error,true); + else if(saved==nullptr) + deviceSettingsDirty_=true; } } if (onStartupStage_) onStartupStage_ (2); From 93b85fcd335937c7465b2ca16b4278c57cf9e9a7 Mon Sep 17 00:00:00 2001 From: Ari Sulistiono Date: Sat, 7 Nov 2026 19:39:35 +0700 Subject: [PATCH 219/219] Exercise channel appearance readback against the accepted graph --- tests/native_channel_appearance_store_test.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) diff --git a/tests/native_channel_appearance_store_test.cpp b/tests/native_channel_appearance_store_test.cpp index 217061bc6..4011f2e5e 100644 --- a/tests/native_channel_appearance_store_test.cpp +++ b/tests/native_channel_appearance_store_test.cpp @@ -44,6 +44,9 @@ int main(){ .getNonexistentChildFile("ArSonMixChannelIdentity","",false); assert(dir.createDirectory().wasOk()); const auto g=nativeGraph(); + // Match the production transport: apply takes the accepted envelope, + // while snapshot projects appearances against its nested channel graph. + const auto graph=g.getProperty("graph",{}); // Raw UTF-8 bytes are a compiler-charset-independent ground truth. const auto keyboard=juce::String::fromUTF8("\xF0\x9F\x8E\xB9"); assert(Store::validIcon(keyboard)); @@ -71,7 +74,7 @@ int main(){ assert(store.apply(req,g)=="INVALID_CHANNEL_NAME_COLOR_OR_ICON"); set(req,"icon",keyboard); assert(store.apply(req,g).isEmpty()); - auto snap=store.snapshot(g); + auto snap=store.snapshot(graph); assert(snap.getProperty("revision","").toString()=="1"); const auto stored=snap.getProperty("entries",{}); const auto* rows=stored.getArray(); @@ -85,18 +88,18 @@ int main(){ assert(store.apply(stale,g)=="CHANNEL_NAME_ALREADY_IN_USE"); set(stale,"name","Guitar New"); assert(store.apply(stale,g).isEmpty()); - assert(store.snapshot(g).getProperty("revision","").toString()=="2"); + assert(store.snapshot(graph).getProperty("revision","").toString()=="2"); } { Store reboot(dir); // No WebView/localStorage or device required. assert(reboot.error().isEmpty()); - const auto snap=reboot.snapshot(g); + const auto snap=reboot.snapshot(graph); const auto entries=snap.getProperty("entries",{}); assert(entries.isArray() && entries.getArray()->size()==2); auto req=edit(vocalId,"Studio Vox"); set(req,"appearanceRevision","2"); assert(reboot.apply(req,g).isEmpty()); // idempotent, no extra disk write - assert(reboot.snapshot(g).getProperty("revision","").toString()=="2"); + assert(reboot.snapshot(graph).getProperty("revision","").toString()=="2"); set(req,"name","Studio Vox 2"); set(req,"deviceEpoch","8"); assert(reboot.apply(req,g)=="STALE_CHANNEL_IDENTITY_OR_GRAPH");