Jelajahi Sumber

Address remote-control review and harden parser boundaries

guike8 3 minggu lalu
induk
melakukan
65539a0be0

+ 4 - 1
.github/workflows/tests.yml

@@ -126,9 +126,12 @@ jobs:
           cmake -S . -B build -G Ninja -DCMAKE_BUILD_TYPE=Release -DFETCHCONTENT_SOURCE_DIR_JUCE="$RUNNER_TEMP/juce" \
             -DCMAKE_C_COMPILER_LAUNCHER=ccache -DCMAKE_CXX_COMPILER_LAUNCHER=ccache -DCMAKE_OBJC_COMPILER_LAUNCHER=ccache -DCMAKE_OBJCXX_COMPILER_LAUNCHER=ccache \
             -DLYNX_LTO=OFF
-          cmake --build build --target LYNX -- -k 0
+          cmake --build build --target LYNX lynx_remote_project_tests -- -k 0
           ccache --show-stats || true
 
+      - name: Remote project document regressions
+        run: ctest --test-dir build --output-on-failure -R '^lynx_remote_project_tests$'
+
       - uses: actions/cache/save@v4
         if: always() && github.ref == 'refs/heads/main'
         with:

+ 36 - 11
docs/REMOTE_CONTROL.md

@@ -52,9 +52,10 @@ Q = HMAC(token, "lynx-control/1\nclient\n" + C + "\n" + S)
 There is no final newline in the signed message. Compare proofs in constant
 time. A client must verify `P` before sending `Q` or an operation. Handshake frames
 are limited to 1 KiB and depth 8 before JSON parsing. Operation frames are limited
-to 1 MiB and depth 64. The listener limits handshake time and validates nesting
-before the recursive parser. It does not accept older or client-specific
-protocols.
+to 1 MiB and depth 64. The listener limits handshake time and validates canonical
+UTF-8 and nesting before conversion or recursive parsing. Malformed, overlong,
+surrogate and out-of-range encodings are rejected. It does not accept older or
+client-specific protocols.
 
 ## Requests, results and edit guards
 
@@ -106,6 +107,16 @@ no credential.
   requires stopped playback/recording. A vendor GUI may change opaque state
   without a native revision; use document/device hashes in addition to revisions.
 
+Every `pattern.notes` object contains `start`, `length`, `channel`, `key`,
+`velocity`, `pan`, `muted`, `finePitch`, `slide`, `porta`, `release`, `modX`,
+`modY`, `colour`, `group`, `chance`, `velocityRange`, `chanceGroup` and
+`chanceOne`. `pattern.replace_notes` requires all these fields, including
+default values, and rejects unsupported fields. Read the complete notes before
+replacing them so an edit retains expression it does not intend to change.
+`chance` is a probability in `0..1`, `velocityRange` is in `-1..1`,
+`chanceGroup` is a nonnegative integer, and `chanceOne` is a boolean. A true
+`chanceOne` flag is retained even when its chance group is currently zero.
+
 ## Read a complete project document
 
 `project.read` exposes every field of LYNX's native versioned project format,
@@ -193,6 +204,15 @@ the document API. Separate typed requests are separate undo steps. Document
 transactions change project data, not settings, filesystem contents, plugin
 scans, saving or rendering.
 
+Document fields are explicitly allowlisted, including nested objects and
+collections. Replacing a parent object, collection or the root does not bypass
+the field policy. Project title, author, genre and comments are editable;
+`info.url`, `info.showOnOpen`, creation time and accumulated work time are
+read-only. Every changed object must contain only reviewed fields, including
+members that were left unchanged; wholly unchanged subtrees are preserved.
+New native save-format fields therefore require an API policy review before
+their containing object can be edited.
+
 Document edits can reuse only asset references already declared in the project,
 with the exact existing spelling. They cannot introduce new sample/zone paths,
 native engine data/DLL paths, effect sources, stand-in files, plugin loader IDs
@@ -210,14 +230,19 @@ image paths, HTML NoteBook page/launch addresses, and decoded native sample/wave
 resource references must retain a resource already declared in that same role.
 A sample reference cannot become a new page-launch address. VFX Script payloads
 may only preserve/reuse an exact pre-existing payload; document edits cannot add
-or change script code, including inside Patcher. Clearing/removing an existing
-hosted device's nonempty saved state in place is also refused. Use explicit
-catalog replacement when a fresh device instance is intended.
-
-The known native formats above are checked before a commit. Other opaque device
-state is not a portable parameter schema and cannot be universally inspected for
-embedded filenames. Restoring third-party state calls the corresponding device
-inside LYNX; that device may perform its own filesystem or network I/O. Remote
+or change script code, including inside Patcher. Hosted `plugin.state` and
+`substituteFor.state` are read-only at the existing device identity, including
+inside parallel branches, nested Patcher nodes and bus heads. Document edits
+cannot supply new nonempty blobs or copy them into another device slot. Channel
+UIDs preserve state when channels are reordered; nested devices and effects
+without UIDs retain their container-slot identity. Use typed parameter operations
+or the plugin editor to change a hosted device, and explicit catalog replacement
+when a fresh device instance is intended.
+
+The known native formats above are checked before a commit. Opaque hosted device
+state is not a portable parameter schema and remains read-only in `project.edit`.
+Restoring existing state through native history or the plugin editor calls the
+corresponding device inside LYNX; that device may perform its own filesystem or network I/O. Remote
 Control is not a sandbox for plugins or state blobs. Use only trusted clients and
 trusted device state even when explicit path fields are restricted.
 

+ 5 - 0
scripts/build-local.sh

@@ -202,6 +202,9 @@ fi
 # all of it (7 times per cold build), and each one ran its own single-threaded LTO link, one after the other. With zig
 # the lines below only queue the tools (build-local/.bin/cxx): each is linked as build-local/.bin/<tool>/lynx_tests
 # (the tests' name, so the cached core objects are reused) and they are built in parallel before the tests run.
+# These JUCE-free regression suites also run through the upstream core CI path.
+$CXX $FLAGS $CORE $WAVPACK tests/RemotePlaylistEditsTests.cpp -o build-local/lynx_remote_playlist_tests
+$CXX $FLAGS $CORE $WAVPACK tests/RemoteInstrumentEditsTests.cpp -o build-local/lynx_remote_instrument_tests
 TOOLS_QUEUE=
 case "$CXX" in
     *zig*)
@@ -278,4 +281,6 @@ if [[ -n "${tools_pid:-}" ]]; then
         exit 1
     fi
 fi
+./build-local/lynx_remote_playlist_tests || tests_rc=$?
+./build-local/lynx_remote_instrument_tests || tests_rc=$?
 exit $tests_rc

+ 12 - 2
src/Main.cpp

@@ -2957,6 +2957,12 @@ private:
                     if (i % 8 == 0) adapter.resetForExport();
                 }
                 audio.join();
+                // Contended audio callbacks may all have bypassed while state was held.
+                // Exercise a successful callback after release before checking coverage.
+                adapter.setParameter (0, 0.5f);
+                (void) adapter.parameterValue (0);
+                reset();
+                render();
                 require (stateOk && probe.blocks > 0 && probe.resets > 0 && probe.captures > 0 && probe.restores > 0,
                          "mock did not exercise processing, resets and hosted state access");
                 require (probe.parameterReads > 0 && probe.parameterWrites > 0,
@@ -2983,6 +2989,8 @@ private:
             catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
         }();
 
+        const auto hostedStateContentionResult = lynx::pluginStateContentionSelfTest();
+
         // recording from the PC keyboard: a one-beat note lands in the pattern, in a single undo step
         // (Blend on: this checks that the take joins the pattern's notes; a new install starts with Blend off)
         const auto notesBefore = offline.getSong().patterns[0].notes.size();
@@ -3688,7 +3696,8 @@ private:
                         && sessionResult == "OK" && liveResult.startsWith ("OK")
                         && wavpack != "ERROR" && effectsOk && driverPanel == "OK" && deviceChange.startsWith ("OK") && metronomeOk && artResult == "OK" && effectParamsResult == "OK"
                         && sidechainResult == "OK" && lanesResult == "OK"
-                        && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK");
+                        && remoteHistoryResult.startsWith ("OK") && hostedStateLockResult.startsWith ("OK")
+                        && hostedStateContentionResult.startsWith ("OK");
 
         juce::String report;
         report << "connections=" << offline.getNumGraphConnections() << "\n"
@@ -3711,6 +3720,7 @@ private:
                << "mixer_basics=" << mixerBasics << "\n"
                << "remote_history=" << remoteHistoryResult << "\n"
                << "hosted_state_lock=" << hostedStateLockResult << "\n"
+               << "hosted_state_contention=" << hostedStateContentionResult << "\n"
                << "fonts=" << fontsResult << "\n"
                << "recording=" << (recordOk && recordUndoOk ? "OK" : "ERROR") << "\n"
                << "cancel_recording=" << (cancelRecordOk ? "OK" : "ERROR") << "\n"
@@ -5447,7 +5457,7 @@ private:
                 s2 = s1;
                 s1 = s0;
             }
-            return std::sqrt (s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2) * 2.0 / (double) juce::jmax<std::size_t> (1, x.size());
+            return std::sqrt (s1 * s1 + s2 * s2 - 2.0 * std::cos (w) * s1 * s2) * 2.0 / (double) std::max<std::size_t> (1, x.size());
         };
         if (! vst2)
             ok = false;

+ 8 - 0
src/core/MidiControls.h

@@ -132,6 +132,14 @@ public:
         return isPitchBend (param) ? (float) q / 16383.0f : (float) q / 127.0f;
     }
 
+    // Audio thread: a host queue dropped a block; replay requested controls on the next flush (not defaults for
+    // controls that were never touched). This also preserves a sustain-off lost in that discarded block.
+    void resend() noexcept
+    {
+        sent.fill (-1);
+        dirty.store (true, std::memory_order_release);
+    }
+
     // Audio thread: calls emit(bytes, size) for each controller whose value changed since the last call.
     template <typename Emit>
     void flush (int midiChannel, Emit&& emit) noexcept

+ 472 - 40
src/engine/PluginHost.cpp

@@ -2,10 +2,12 @@
 #include "platform/Paths.h"
 
 #include <algorithm>
+#include <bit>
 #include <chrono>
 #include <cstdlib>
 #include <cstring>
 #include <thread>
+#include <type_traits>
 
 #include "core/Preferences.h"
 #include "core/PluginScanPolicy.h"
@@ -231,9 +233,8 @@ struct BlockCall
 std::uint32_t runBlock (BlockCall call, std::atomic<bool>& crashed, const std::string& name) noexcept
 {
     const KeepFloatMode keep;
-    // State capture/restoration uses this same per-instance lock. Keep it outside
-    // the crash guard so a guarded vendor fault returns before the lock unwinds.
-    const juce::ScopedLock lock (call.plugin->getCallbackLock());
+    // The adapter holds the instance's callback try-lock for its whole render.
+    // Keep the lock outside the crash guard so a guarded vendor fault unwinds it.
     if (crashed.load (std::memory_order_relaxed)) return alreadyCrashed;
     const auto code = crashguard::run (call);
     if (code != 0) recordCrashOnce (crashed, name, code);
@@ -242,7 +243,7 @@ std::uint32_t runBlock (BlockCall call, std::atomic<bool>& crashed, const std::s
 
 std::uint32_t runReset (juce::AudioPluginInstance& plugin, std::atomic<bool>& crashed, const std::string& name) noexcept
 {
-    const juce::ScopedLock lock (plugin.getCallbackLock());
+    // Called with the instance's callback lock already held (try-lock on the audio thread).
     if (crashed.load (std::memory_order_relaxed)) return alreadyCrashed;
     const auto code = crashguard::run ([&] { plugin.reset(); });
     if (code != 0) recordCrashOnce (crashed, name, code);
@@ -264,8 +265,89 @@ std::vector<PluginCrash> pluginCrashes()
     return list;
 }
 
+HostedParameterChanges::HostedParameterChanges (int n)
+    : count (std::max (0, n)), values (std::make_unique<Value[]> ((std::size_t) count))
+{
+    static_assert (std::atomic<float>::is_always_lock_free && std::atomic<std::uint64_t>::is_always_lock_free);
+}
+
+void HostedParameterChanges::defer (int index, float value) noexcept
+{
+    if (! contains (index)) return;
+    const auto epoch = restoreEpoch.load (std::memory_order_acquire);
+    values[index].deferred.store (((std::uint64_t) epoch << 32) | std::bit_cast<std::uint32_t> (value), std::memory_order_release);
+    pending.store (true, std::memory_order_release);
+}
+
+void HostedParameterChanges::clear (int index) noexcept
+{
+    if (contains (index)) values[index].deferred.exchange (0, std::memory_order_acq_rel);
+}
+
+float HostedParameterChanges::latest (int index) const noexcept
+{
+    if (! contains (index)) return -1.0f;
+    const auto deferred = values[index].deferred.load (std::memory_order_acquire);
+    return deferred != 0 && (std::uint32_t) (deferred >> 32) == restoreEpoch.load (std::memory_order_acquire)
+               ? std::bit_cast<float> ((std::uint32_t) deferred) : values[index].cached.load (std::memory_order_relaxed);
+}
+
+void HostedParameterChanges::observed (int index, float value) noexcept
+{
+    if (contains (index)) values[index].cached.store (value, std::memory_order_relaxed);
+}
+
+bool HostedParameterChanges::take (int index, float& value) noexcept
+{
+    if (! contains (index)) return false;
+    const auto deferred = values[index].deferred.exchange (0, std::memory_order_acq_rel);
+    if (deferred == 0 || (std::uint32_t) (deferred >> 32) != restoreEpoch.load (std::memory_order_acquire)) return false;
+    value = std::bit_cast<float> ((std::uint32_t) deferred);
+    return true;
+}
+
 namespace
 {
+// All vendor calls here run under the instance lock. Only the audio-side attempt is nonblocking; UI state access
+// may wait for a block already in flight, but the next audio block never waits for it in return.
+void applyParameter (juce::AudioPluginInstance& plugin, HostedParameterChanges& changes, int index, float value)
+{
+    setPluginParameter (plugin, index, value);
+    const auto& params = plugin.getParameters();
+    if (index >= 0 && index < params.size()) changes.observed (index, params[index]->getValue());
+}
+
+std::uint32_t flushParameters (juce::AudioPluginInstance& plugin, HostedParameterChanges& changes,
+                               std::atomic<bool>& crashed, const std::string& name) noexcept
+{
+    if (! changes.takePending()) return 0;
+    const auto code = crashguard::run ([&] {
+        for (int index = 0; index < changes.size(); ++index)
+        {
+            float value;
+            if (changes.take (index, value)) applyParameter (plugin, changes, index, value);
+        }
+    });
+    if (code != 0) recordCrashOnce (crashed, name, code);
+    return code;
+}
+
+void audioParameter (juce::AudioPluginInstance& plugin, HostedParameterChanges& changes,
+                     std::atomic<bool>& crashed, const std::string& name, int index, float value) noexcept
+{
+    if (! changes.contains (index)) return;
+    const juce::CriticalSection::ScopedTryLockType lock (plugin.getCallbackLock());
+    if (! lock.isLocked())
+    {
+        changes.defer (index, value);
+        return;
+    }
+    if (crashed.load (std::memory_order_relaxed)) return;
+    changes.clear (index); // a later successful automation value supersedes the queued one
+    if (const auto code = crashguard::run ([&] { applyParameter (plugin, changes, index, value); }); code != 0)
+        recordCrashOnce (crashed, name, code);
+}
+
 std::optional<std::string> guardedState (juce::AudioPluginInstance& plugin, std::atomic<bool>& crashed, const std::string& name)
 {
     if (crashed.load())
@@ -281,7 +363,7 @@ std::optional<std::string> guardedState (juce::AudioPluginInstance& plugin, std:
     return state.toBase64Encoding().toStdString();
 }
 
-bool guardedRestore (juce::AudioPluginInstance& plugin, std::atomic<bool>& crashed, const std::string& name,
+bool guardedRestore (juce::AudioPluginInstance& plugin, HostedParameterChanges& changes, std::atomic<bool>& crashed, const std::string& name,
                      const std::string& encoded)
 {
     if (crashed.load()) return false;
@@ -289,7 +371,14 @@ bool guardedRestore (juce::AudioPluginInstance& plugin, std::atomic<bool>& crash
     if (encoded.empty() || ! state.fromBase64Encoding (juce::String::fromUTF8 (encoded.c_str()))) return false;
     const juce::ScopedLock lock (plugin.getCallbackLock());
     if (crashed.load (std::memory_order_relaxed)) return false;
-    if (const auto code = crashguard::run ([&] { plugin.setStateInformation (state.getData(), (int) state.getSize()); }); code != 0)
+    // This acquisition is the restore boundary. Requests made before it cannot overwrite the restored state;
+    // requests arriving while the vendor restores see the new epoch and remain pending for the next block.
+    changes.beginRestore();
+    if (const auto code = crashguard::run ([&] {
+            plugin.setStateInformation (state.getData(), (int) state.getSize());
+            const auto& params = plugin.getParameters();
+            for (int i = 0; i < params.size(); ++i) changes.observed (i, params[i]->getValue());
+        }); code != 0)
     {
         recordCrashOnce (crashed, name, code);
         return false;
@@ -297,7 +386,8 @@ bool guardedRestore (juce::AudioPluginInstance& plugin, std::atomic<bool>& crash
     return true;
 }
 
-void guardedUiParameter (juce::AudioPluginInstance& plugin, std::atomic<bool>& crashed, const std::string& name, int index, float value)
+void guardedUiParameter (juce::AudioPluginInstance& plugin, HostedParameterChanges& changes,
+                         std::atomic<bool>& crashed, const std::string& name, int index, float value)
 {
     const juce::ScopedLock lock (plugin.getCallbackLock());
     if (crashed.load())
@@ -305,7 +395,11 @@ void guardedUiParameter (juce::AudioPluginInstance& plugin, std::atomic<bool>& c
     if (const auto code = crashguard::run ([&] {
             const auto& params = plugin.getParameters();
             if (index >= 0 && index < params.size())
+            {
+                changes.clear (index);
                 params[index]->setValueNotifyingHost (value);
+                changes.observed (index, params[index]->getValue());
+            }
         });
         code != 0)
     {
@@ -317,11 +411,12 @@ void guardedUiParameter (juce::AudioPluginInstance& plugin, std::atomic<bool>& c
 PluginInstrument::PluginInstrument (std::unique_ptr<juce::AudioPluginInstance> instance, int maxBlockSize, int fixedBlock, HostedOptions o)
     : options (o),
       plugin (std::move (instance)),
+      parameterChanges (plugin->getParameters().size()),
       blockSize (maxBlockSize),
       name (plugin->getName().toStdString())
 {
     buffer.setSize (bufferChannels (*plugin), blockSize);
-    midi.ensureSize (8192); // the audio thread only adds events within this capacity
+    midi.ensureSize (32768); // 8 KiB normal queue, with room for all 16x128 recovery note-offs without allocation
     outs = pluginOutputs (*plugin);
     routeOffset = std::make_unique<std::atomic<int>[]> (outs.size() + 1);
     routeActive = std::make_unique<std::atomic<bool>[]> (outs.size() + 1);
@@ -342,7 +437,7 @@ PluginInstrument::PluginInstrument (std::unique_ptr<juce::AudioPluginInstance> i
         // (every output channel goes through the fixed blocks: the other outputs keep their place too)
         const auto channels = juce::jlimit (2, 64, plugin->getTotalNumOutputChannels()); // (64: render()'s pointer array)
         fixed = std::make_unique<FixedBlock> (juce::jmin (fixedBlock, blockSize), channels);
-        pending.ensureSize (8192);
+        pending.ensureSize (32768);
         scratch.assign ((std::size_t) blockSize * (std::size_t) channels, 0.0f);
     }
     plugin->setPlayHead (&timelinePlayHead (options.sendLoopPosition));
@@ -359,7 +454,7 @@ PluginInstrument::PluginInstrument (std::unique_ptr<juce::AudioPluginInstance> i
 
 void PluginInstrument::releaseHeldKeys() noexcept
 {
-    heldKeys.releaseAll ([this] (int ch, int key) { midi.addEvent (juce::MidiMessage::noteOff (ch + 1, key), 0); });
+    heldKeys.releaseAll ([this] (int ch, int key) { queueMidi (juce::MidiMessage::noteOff (ch + 1, key)); });
     sentKeys.played = {}; // (their note offs went out with these)
 }
 
@@ -391,6 +486,7 @@ void PluginInstrument::resetForExport()
 {
     // FL's "Reset plugin when FL Studio resets" (on by default): an export starts without what the plugin still holds
     // (tails, notes)
+    const juce::ScopedLock lock (plugin->getCallbackLock()); // offline/UI path, never the live audio callback
     if (! hasCrashed() && options.resetOnFlush)
         if (const auto code = runReset (*plugin, crashed, name); code != 0)
             failed (code);
@@ -437,31 +533,31 @@ std::optional<std::string> PluginInstrument::captureState()
 
 bool PluginInstrument::restoreState (const std::string& state)
 {
-    return guardedRestore (*plugin, crashed, name, state);
+    return guardedRestore (*plugin, parameterChanges, crashed, name, state);
 }
 
 void PluginInstrument::setParameterFromUi (int index, float value)
 {
     if (midiControls.set (index, value)) // a MIDI CC / aftertouch / bend "parameter": sent with the next block
         return;
-    guardedUiParameter (*plugin, crashed, name, index, value);
+    guardedUiParameter (*plugin, parameterChanges, crashed, name, index, value);
 }
 
 void PluginInstrument::noteOnMidi (int key, float velocity, int midiChannel) noexcept
 {
-    midi.addEvent (juce::MidiMessage::noteOn (juce::jlimit (0, 15, midiChannel) + 1, juce::jlimit (0, 127, key), juce::jlimit (0.0f, 1.0f, velocity)), 0);
+    queueMidi (juce::MidiMessage::noteOn (juce::jlimit (0, 15, midiChannel) + 1, juce::jlimit (0, 127, key), juce::jlimit (0.0f, 1.0f, velocity)));
     hold (juce::jlimit (0, 15, midiChannel), key, true);
 }
 
 void PluginInstrument::noteOffMidi (int key, int midiChannel) noexcept
 {
-    midi.addEvent (juce::MidiMessage::noteOff (juce::jlimit (0, 15, midiChannel) + 1, juce::jlimit (0, 127, key)), 0);
+    queueMidi (juce::MidiMessage::noteOff (juce::jlimit (0, 15, midiChannel) + 1, juce::jlimit (0, 127, key)));
     hold (juce::jlimit (0, 15, midiChannel), key, false);
 }
 
 void PluginInstrument::flushMidiControls() noexcept
 {
-    midiControls.flush (0, [this] (const std::uint8_t* bytes, int size) { midi.addEvent (bytes, size, 0); });
+    midiControls.flush (0, [this] (const std::uint8_t* bytes, int size) { queueMidi (bytes, size); });
 }
 
 void PluginInstrument::addBend (int offset) noexcept
@@ -472,7 +568,10 @@ void PluginInstrument::addBend (int offset) noexcept
     if (value == sentBend)
         return;
     sentBend = value;
-    (bendInto != nullptr ? *bendInto : midi).addEvent (juce::MidiMessage::pitchWheel (1, value), offset);
+    if (bendInto == nullptr || bendInto == &midi)
+        queueMidi (juce::MidiMessage::pitchWheel (1, value), offset);
+    else
+        bendInto->addEvent (juce::MidiMessage::pitchWheel (1, value), offset);
 }
 
 void PluginInstrument::bendBlock (juce::MidiBuffer& into, int base, int count) noexcept
@@ -521,11 +620,11 @@ void PluginInstrument::noteOn (int key, float velocity) noexcept
         glide.taken = true;
     }
     addBend (0);
-    midi.addEvent (juce::MidiMessage::noteOn (1, k, juce::jlimit (0.0f, 1.0f, velocity)), 0);
+    queueMidi (juce::MidiMessage::noteOn (1, k, juce::jlimit (0.0f, 1.0f, velocity)));
     hold (0, k, true);
     // FL's "Send MOD X as polyphonic aftertouch": the note's Mod X right after its note on
     if (options.modXAftertouch)
-        midi.addEvent (juce::MidiMessage::aftertouchChange (1, k, juce::jlimit (0, 127, juce::roundToInt (nextModX * 127.0f))), 0);
+        queueMidi (juce::MidiMessage::aftertouchChange (1, k, juce::jlimit (0, 127, juce::roundToInt (nextModX * 127.0f))));
     nextModX = 0.5f;
 }
 
@@ -534,9 +633,9 @@ void PluginInstrument::noteOff (int key) noexcept
     const auto k = sentKeys.off (juce::jlimit (0, 127, key)); // (the key its note on went out on, issue #63)
     // FL's "Send note release velocity" (on by default): the note's release velocity, else 0
     if (options.releaseVelocity)
-        midi.addEvent (juce::MidiMessage::noteOff (1, k, juce::jlimit (0.0f, 1.0f, nextRelease)), 0);
+        queueMidi (juce::MidiMessage::noteOff (1, k, juce::jlimit (0.0f, 1.0f, nextRelease)));
     else
-        midi.addEvent (juce::MidiMessage::noteOff (1, k), 0);
+        queueMidi (juce::MidiMessage::noteOff (1, k));
     nextRelease = 0.5f;
     hold (0, k, false);
 }
@@ -547,39 +646,88 @@ void PluginInstrument::allNotesOff() noexcept
     // host passes a controller only as the parameter the plugin maps it to, and drops it otherwise), so a jump while
     // playing left SynthMaster's notes sounding under the chased ones: doubled notes, a sequence out of time
     releaseHeldKeys();
-    midi.addEvent (juce::MidiMessage::allNotesOff (1), 0);
-    midi.addEvent (juce::MidiMessage::allSoundOff (1), 0);
+    queueMidi (juce::MidiMessage::allNotesOff (1));
+    queueMidi (juce::MidiMessage::allSoundOff (1));
 }
 
-// A Patcher parameter output (round 171b): the parameter's value as the plugin reports it, guarded like the audio calls
-static float hostedParameterValue (juce::AudioPluginInstance& plugin, const std::atomic<bool>& crashed, int index) noexcept
+void PluginInstrument::queueMidi (const void* bytes, int size, int offset) noexcept
+{
+    // Bound retained work even if a vendor's state call lasts indefinitely. JUCE's event header is smaller than
+    // this conservative allowance; an accepted event therefore fits the constructor's preallocated storage.
+    const auto budget = recoveryMidi ? 32768 : 8192;
+    constexpr int headerAllowance = 16;
+    if (midiOverflow || size <= 0) return;
+    if (size > budget - headerAllowance || midi.data.size() > budget - size - headerAllowance)
+    {
+        if (recoveryMidi) return; // mandatory recovery note-offs take priority over optional controls in this block
+        midiOverflow = true;
+        midi.clear();
+        return;
+    }
+    midi.addEvent (bytes, size, offset);
+}
+
+void PluginInstrument::rememberMidi (const juce::MidiBuffer& messages) noexcept
+{
+    for (const auto event : messages)
+    {
+        if (event.numBytes < 3) continue;
+        const auto status = event.data[0] & 0xf0, channel = event.data[0] & 0x0f;
+        if (status == 0x90 || status == 0x80)
+            deliveredKeys.set (channel, event.data[1], status == 0x90 && event.data[2] != 0);
+    }
+}
+
+void PluginInstrument::recoverMidi() noexcept
+{
+    if (! midiOverflow) return;
+    // Missed note-ons are not replayed as a burst. Release only notes actually delivered before the gap. Even the
+    // worst case (all 16x128 keys) fits the separate 32 KiB preallocation, without trusting CC123 in VST3 hosts.
+    midi.clear();
+    pending.clear();
+    if (fixed != nullptr) fixed->clear();
+    // Keep the delivered mask until the offs reach the vendor. A partial fixed block may overflow again before
+    // it processes, in which case its replacement recovery still has to release the same sounding keys.
+    for (int ch = 0; ch < 16; ++ch)
+        for (int key = 0; key < 128; ++key)
+            if (deliveredKeys.held (ch, key)) midi.addEvent (juce::MidiMessage::noteOff (ch + 1, key), 0);
+    midiOverflow = false;
+    recoveryMidi = true;
+    sentBend = -1; // dropped controls are resent from the current pitch rather than treated as delivered
+    bendRangeSent = false;
+    midiControls.resend();
+    flushMidiControls();
+}
+
+// Patcher control cables also run on the audio thread: during state access use the queued/last observed value.
+static float hostedParameterValue (juce::AudioPluginInstance& plugin, HostedParameterChanges& changes,
+                                  const std::atomic<bool>& crashed, int index) noexcept
 {
-    const juce::ScopedLock lock (plugin.getCallbackLock());
     if (crashed.load (std::memory_order_relaxed) || index < 0)
         return -1.0f;
+    const juce::CriticalSection::ScopedTryLockType lock (plugin.getCallbackLock());
+    if (! lock.isLocked()) return changes.latest (index);
+    if (crashed.load (std::memory_order_relaxed)) return -1.0f;
     float value = -1.0f;
     crashguard::run ([&] {
         const auto& params = plugin.getParameters();
         if (index < params.size())
             value = params[index]->getValue();
     });
+    changes.observed (index, value);
     return value;
 }
 
 float PluginInstrument::parameterValue (int index) const noexcept
 {
-    return hostedParameterValue (*plugin, crashed, index);
+    return hostedParameterValue (*plugin, parameterChanges, crashed, index);
 }
 
 void PluginInstrument::setParameter (int index, float value) noexcept
 {
     if (crashed.load (std::memory_order_relaxed) || midiControls.set (index, value))
         return;
-    // Automation/Patcher controls can run while a remote snapshot captures this instance's state.
-    const juce::ScopedLock lock (plugin->getCallbackLock());
-    if (crashed.load (std::memory_order_relaxed)) return;
-    if (const auto code = crashguard::run ([&] { setPluginParameter (*plugin, index, value); }); code != 0)
-        failed (code);
+    audioParameter (*plugin, parameterChanges, crashed, name, index, value);
 }
 
 void PluginInstrument::render (float* left, float* right, int n, float gl, float gr) noexcept
@@ -592,13 +740,28 @@ void PluginInstrument::render (float* left, float* right, int n, float gl, float
         midi.clear();
         return; // silent
     }
+    const juce::CriticalSection::ScopedTryLockType lock (plugin->getCallbackLock());
+    if (! lock.isLocked())
+    {
+        if (fixed != nullptr) fixed->clear(); // elapsed time must not replay a buffered pre-gap block on resumption
+        blockClock.start (hostTimeline().chunk.load (std::memory_order_relaxed));
+        blockClock.advance (n);
+        return; // state access owns this instance: silence, with MIDI, reset and parameter changes still pending
+    }
+    if (crashed.load (std::memory_order_relaxed)) { midi.clear(); return; }
+    recoverMidi();
     if (resetPending.exchange (false, std::memory_order_relaxed))
+    {
         if (const auto code = runReset (*plugin, crashed, name); code != 0)
         {
             failed (code);
             midi.clear();
             return;
         }
+        else
+            deliveredKeys.bits = {};
+    }
+    if (flushParameters (*plugin, parameterChanges, crashed, name) != 0) { midi.clear(); return; }
     // FL's "Send pitch bend range": the pitch-bend-sensitivity RPN (0, 0) once, before the first notes
     if (options.sendBendRange && ! bendRangeSent)
     {
@@ -607,7 +770,7 @@ void PluginInstrument::render (float* left, float* right, int n, float gl, float
         for (const auto& m : { juce::MidiMessage::controllerEvent (1, 101, 0), juce::MidiMessage::controllerEvent (1, 100, 0),
                                juce::MidiMessage::controllerEvent (1, 6, range), juce::MidiMessage::controllerEvent (1, 38, 0),
                                juce::MidiMessage::controllerEvent (1, 101, 127), juce::MidiMessage::controllerEvent (1, 100, 127) })
-            midi.addEvent (m, 0); // (the first render comes before any note: the plugin is new)
+            queueMidi (m); // (the first render comes before any note: the plugin is new)
     }
     flushMidiControls();
     // issue #63: the VST3 host picks up each note on's tuning while this thread runs the plugin's blocks
@@ -622,16 +785,24 @@ void PluginInstrument::render (float* left, float* right, int n, float gl, float
     if (fixed != nullptr)
     {
         bendBlock (midi, 0, n);
+        if (pending.data.size() > 32768 - midi.data.size())
+        {
+            midiOverflow = true;
+            recoverMidi(); // a series of tiny renders cannot grow the fixed block's pending MIDI either
+        }
         // events of this chunk start where the block being collected stands now
         const auto at = fixed->position();
         for (const auto event : midi)
             pending.addEvent (event.data, event.numBytes, at);
         midi.clear();
+        recoveryMidi = false;
 
         auto process = [this] (float* const* ch, int count) {
             juce::AudioBuffer<float> view (buffer.getArrayOfWritePointers(), buffer.getNumChannels(), count);
             view.clear();
             if (! crashed.load (std::memory_order_relaxed))
+            {
+                rememberMidi (pending);
                 if (const auto code = runBlock (BlockCall { plugin.get(), &view, &pending }, crashed, name); code != 0)
                 {
                     failed (code);
@@ -639,6 +810,7 @@ void PluginInstrument::render (float* left, float* right, int n, float gl, float
                 }
                 else
                     collectMidiOutput (pending);
+            }
             pending.clear();
             const auto channels = (int) (scratch.size() / (std::size_t) blockSize);
             for (int c = 0; c < channels; ++c)
@@ -668,6 +840,7 @@ void PluginInstrument::render (float* left, float* right, int n, float gl, float
         view.clear();
         bendBlock (midi, 0, count);
         setHostBlockOffset (chunkOffset + done);
+        rememberMidi (midi);
         if (const auto code = runBlock (BlockCall { plugin.get(), &view, &midi }, crashed, name); code != 0)
         {
             midi.clear();
@@ -676,6 +849,7 @@ void PluginInstrument::render (float* left, float* right, int n, float gl, float
         }
         collectMidiOutput (midi);
         midi.clear();
+        recoveryMidi = false;
 
         mixOutputs (view.getArrayOfReadPointers(), view.getNumChannels(), done, count, gl, gr, left, right);
         done += count;
@@ -770,6 +944,7 @@ const float* PluginInstrument::auxOutputData (int k, int side) const noexcept
 
 PluginEffect::PluginEffect (std::unique_ptr<juce::AudioPluginInstance> instance, int maxBlockSize, int fixedBlock, HostedOptions o)
     : plugin (std::move (instance)),
+      parameterChanges (plugin->getParameters().size()),
       blockSize (maxBlockSize),
       name (plugin->getName().toStdString())
 {
@@ -798,6 +973,7 @@ void PluginEffect::resetForExport()
 {
     // FL's "Reset plugin when FL Studio resets" (on by default): an export starts without what the plugin still holds
     // (tails, notes)
+    const juce::ScopedLock lock (plugin->getCallbackLock()); // offline/UI path, never the live audio callback
     if (! hasCrashed() && options.resetOnFlush)
         if (const auto code = runReset (*plugin, crashed, name); code != 0)
             failed (code);
@@ -823,7 +999,7 @@ std::optional<std::string> PluginEffect::captureState()
 
 bool PluginEffect::restoreState (const std::string& state)
 {
-    return guardedRestore (*plugin, crashed, name, state);
+    return guardedRestore (*plugin, parameterChanges, crashed, name, state);
 }
 
 void PluginEffect::flushMidiControls() noexcept
@@ -835,23 +1011,19 @@ void PluginEffect::setParameterFromUi (int index, float value)
 {
     if (midiControls.set (index, value))
         return;
-    guardedUiParameter (*plugin, crashed, name, index, value);
+    guardedUiParameter (*plugin, parameterChanges, crashed, name, index, value);
 }
 
 float PluginEffect::parameterValue (int index) const noexcept
 {
-    return hostedParameterValue (*plugin, crashed, index);
+    return hostedParameterValue (*plugin, parameterChanges, crashed, index);
 }
 
 void PluginEffect::setParameter (int index, float value) noexcept
 {
     if (crashed.load (std::memory_order_relaxed) || midiControls.set (index, value))
         return;
-    // Automation/Patcher controls can run while a remote snapshot captures this instance's state.
-    const juce::ScopedLock lock (plugin->getCallbackLock());
-    if (crashed.load (std::memory_order_relaxed)) return;
-    if (const auto code = crashguard::run ([&] { setPluginParameter (*plugin, index, value); }); code != 0)
-        failed (code);
+    audioParameter (*plugin, parameterChanges, crashed, name, index, value);
 }
 
 void PluginEffect::findSideChannel() noexcept
@@ -1055,6 +1227,258 @@ juce::String pluginSidechainSelfTest()
     return "OK";
 }
 
+juce::String pluginStateContentionSelfTest()
+{
+    struct Probe final : juce::AudioPluginInstance
+    {
+        struct Parameter final : juce::HostedAudioProcessorParameter
+        {
+            explicit Parameter (Probe& p) : owner (p) {}
+            float getValue() const override { owner.checkAccess(); return value.load(); }
+            void setValue (float v) override { owner.checkAccess(); value.store (v); ++owner.writes; }
+            float getDefaultValue() const override { return 0.0f; }
+            juce::String getName (int) const override { return "Value"; }
+            juce::String getLabel() const override { return {}; }
+            juce::String getParameterID() const override { return "value"; }
+            float getValueForText (const juce::String& text) const override { return text.getFloatValue(); }
+            Probe& owner;
+            std::atomic<float> value { 0.0f };
+        };
+        Probe() : AudioPluginInstance (BusesProperties().withInput ("Input", juce::AudioChannelSet::stereo(), true)
+                                                       .withOutput ("Output", juce::AudioChannelSet::stereo(), true))
+        {
+            for (int i = 0; i < 2; ++i) addHostedParameter (std::make_unique<Parameter> (*this));
+        }
+        const juce::String getName() const override { return "State contention probe"; }
+        void fillInPluginDescription (juce::PluginDescription& d) const override { d.name = getName(); }
+        void prepareToPlay (double, int) override {}
+        void releaseResources() override {}
+        void processBlock (juce::AudioBuffer<float>& audio, juce::MidiBuffer& messages) override
+        {
+            checkAccess();
+            ++blocks;
+            for (const auto event : messages)
+            {
+                if (event.numBytes < 3) continue;
+                const auto status = event.data[0] & 0xf0, ch = event.data[0] & 0x0f;
+                if (status == 0x90 && event.data[2] != 0)
+                {
+                    ++noteOns;
+                    if (event.data[1] >= 64 && event.data[1] < 96) ++missedNoteOns;
+                    sounding.set (ch, event.data[1], true);
+                }
+                else if (status == 0x80 || status == 0x90) { ++noteOffs; sounding.set (ch, event.data[1], false); }
+                else if (status == 0xb0 && event.data[1] == 64) sustain.store (event.data[2]);
+            }
+            for (int ch = 0; ch < audio.getNumChannels(); ++ch)
+                std::fill_n (audio.getWritePointer (ch), audio.getNumSamples(), output.load());
+        }
+        void reset() override
+        {
+            checkAccess();
+            ++resets;
+            for (auto* p : getParameters()) static_cast<Parameter*> (p)->value.store (0.0f);
+            sounding.bits = {};
+        }
+        double getTailLengthSeconds() const override { return 0.0; }
+        bool acceptsMidi() const override { return true; }
+        bool producesMidi() const override { return false; }
+        bool hasEditor() const override { return false; }
+        juce::AudioProcessorEditor* createEditor() override { return nullptr; }
+        int getNumPrograms() override { return 1; }
+        int getCurrentProgram() override { return 0; }
+        void setCurrentProgram (int) override {}
+        const juce::String getProgramName (int) override { return {}; }
+        void changeProgramName (int, const juce::String&) override {}
+        void getStateInformation (juce::MemoryBlock& state) override { stateAccess (1); state.replaceAll ("state", 5); }
+        void setStateInformation (const void*, int) override
+        {
+            stateAccess (2);
+            static_cast<Parameter*> (getParameters()[0])->value.store (0.35f);
+            static_cast<Parameter*> (getParameters()[1])->value.store (0.45f);
+        }
+        void checkAccess() const { if (stateActive.load()) overlap.store (true); }
+        void stateAccess (int mode)
+        {
+            if (holdMode.load() != mode) return;
+            stateActive.store (true);
+            entered.signal();
+            if (! release.wait (5000)) timedOut.store (true);
+            stateActive.store (false);
+        }
+        std::atomic<int> blocks { 0 }, resets { 0 }, writes { 0 }, holdMode { 0 };
+        std::atomic<int> noteOns { 0 }, noteOffs { 0 }, missedNoteOns { 0 };
+        std::atomic<int> sustain { 0 };
+        HostedKeys sounding;
+        std::atomic<float> output { 0.5f };
+        std::atomic<bool> stateActive { false }, timedOut { false };
+        mutable std::atomic<bool> overlap { false };
+        juce::WaitableEvent entered { true }, release { true };
+    };
+    int checks = 0;
+    const auto require = [&] (bool condition, const char* message) {
+        ++checks;
+        if (! condition) throw std::runtime_error (message);
+    };
+    const auto exercise = [&] (auto& adapter, Probe& probe, const auto& render, const auto& reset,
+                              const auto& outputUnchanged, const auto& outputResumed, const auto& noOldOutput) {
+        adapter.setParameterFromUi (0, 0.2f);
+        adapter.setParameterFromUi (1, 0.3f);
+        const auto saved = adapter.captureState();
+        require (saved.has_value(), "could not capture contention fixture");
+        const auto whileHeld = [&] (int mode, const auto& audioCall) {
+            probe.entered.reset();
+            probe.release.reset();
+            probe.holdMode.store (mode);
+            bool stateOk = false;
+            std::thread state ([&] { stateOk = mode == 1 ? adapter.captureState().has_value() : adapter.restoreState (*saved); });
+            const juce::ScopeGuard joinState { [&] { probe.release.signal(); if (state.joinable()) state.join(); probe.holdMode.store (0); } };
+            require (probe.entered.wait (2000), "state fixture did not acquire the instance lock");
+            juce::WaitableEvent finished { true };
+            std::thread audio ([&] { audioCall(); finished.signal(); });
+            const juce::ScopeGuard joinAudio { [&] { probe.release.signal(); if (audio.joinable()) audio.join(); } };
+            // The state gate stays closed until after this observation. A blocking callback cannot pass, regardless
+            // of scheduling; the timeout only bounds a failed test, not a timing/performance assertion.
+            const auto completedWhileHeld = finished.wait (1000);
+            probe.release.signal();
+            audio.join();
+            state.join();
+            probe.holdMode.store (0);
+            require (completedWhileHeld, "audio waited for hosted state access");
+            require (stateOk && ! probe.timedOut.load(), "state fixture failed or its gate timed out");
+            require (! probe.overlap.load(), "audio entered the plugin during hosted state access");
+        };
+
+        float read = -1.0f;
+        whileHeld (1, [&] { read = adapter.parameterValue (0); render(); });
+        require (read == 0.2f, "contended parameter read lost the last observed value");
+        require (probe.blocks.load() == 0 && outputUnchanged(), "contended render changed the dry/silent output");
+        const auto writesBefore = probe.writes.load();
+        whileHeld (2, [&] {
+            adapter.setParameter (0, 0.4f);
+            adapter.setParameter (0, 0.8f);
+            adapter.setParameter (1, 0.6f);
+            read = adapter.parameterValue (0);
+            reset();
+            render();
+        });
+        require (read == 0.8f && probe.writes.load() == writesBefore && probe.resets.load() == 0,
+                 "contended automation/reset entered the vendor or lost the latest request");
+        render();
+        render(); // fixed buffers have one block of latency
+        require (adapter.parameterValue (0) == 0.8f && adapter.parameterValue (1) == 0.6f,
+                 "deferred parameter values were not applied after the pending reset");
+        require (probe.resets.load() == 1 && probe.writes.load() == writesBefore + 2,
+                 "deferred reset or coalesced automation was lost or applied twice");
+        require (probe.blocks.load() > 0 && outputResumed(), "processing failed to resume after state access");
+        whileHeld (1, [&] { adapter.setParameter (0, 0.1f); });
+        adapter.setParameterFromUi (0, 0.9f);
+        render();
+        require (adapter.parameterValue (0) == 0.9f, "queued automation overwrote a later UI change");
+        whileHeld (1, [&] { adapter.setParameter (0, 0.2f); });
+        adapter.setParameter (0, 0.7f);
+        render();
+        require (adapter.parameterValue (0) == 0.7f, "queued automation overwrote a later audio change");
+        whileHeld (1, [&] { adapter.setParameter (0, 0.1f); });
+        require (adapter.restoreState (*saved), "restore ordering fixture failed");
+        render();
+        require (adapter.parameterValue (0) == 0.35f, "automation queued before restore overwrote restored state");
+        whileHeld (1, [&] { read = adapter.parameterValue (0); });
+        require (read == 0.35f, "restored parameter cache was not refreshed");
+        if constexpr (std::is_same_v<std::remove_cvref_t<decltype (adapter)>, PluginInstrument>)
+        {
+            adapter.noteOnMidi (60, 0.7f, 0);
+            render(); render();
+            whileHeld (1, [&] { adapter.noteOffMidi (60, 0); render(); });
+            render(); render();
+            require (! probe.sounding.any(), "a short contention gap lost a note-off");
+            adapter.noteOnMidi (60, 0.7f, 0);
+            render(); render();
+            const auto onsBefore = probe.noteOns.load(), offsBefore = probe.noteOffs.load();
+            const auto* storage = adapter.midi.data.begin();
+            whileHeld (1, [&] {
+                for (int block = 0; block < 1024; ++block)
+                {
+                    for (int key = 0; key < 32; ++key)
+                    {
+                        adapter.noteOnMidi (key + 64, 0.7f, 0);
+                        adapter.noteOffMidi (key + 64, 0);
+                    }
+                    render();
+                }
+            });
+            require (adapter.midiOverflow && adapter.midi.data.size() <= 8192 && adapter.midi.data.begin() == storage,
+                     "sustained state contention grew or reallocated the MIDI queue");
+            if (adapter.fixed != nullptr)
+            {
+                const auto* pendingStorage = adapter.pending.data.begin();
+                float oneLeft = 0.0f, oneRight = 0.0f;
+                // Queue recovery into a partial fixed block, then overflow it twice before any vendor call.
+                adapter.render (&oneLeft, &oneRight, 1, 1.0f, 1.0f);
+                for (int piece = 0; piece < 64; ++piece)
+                {
+                    for (int pair = 0; pair < 64; ++pair)
+                    {
+                        adapter.noteOnMidi (pair % 32, 0.7f, 0);
+                        adapter.noteOffMidi (pair % 32, 0);
+                    }
+                    adapter.render (&oneLeft, &oneRight, 1, 1.0f, 1.0f);
+                }
+                require (adapter.pending.data.size() <= 32768 && adapter.pending.data.begin() == pendingStorage,
+                         "tiny fixed renders reallocated their pending MIDI queue");
+                render(); render(); // overflow restarted the fixed clock; now deliver the retained recovery offs
+            }
+            else
+            {
+                render(); render();
+                require (probe.noteOns.load() == onsBefore, "overflow replayed missed note-ons");
+            }
+            require (probe.missedNoteOns.load() == 0 && probe.noteOffs.load() > offsBefore && ! probe.sounding.any(),
+                     "overflow replayed missed note-ons or left a delivered key sounding");
+            adapter.setParameter (midictl::ccBase + 64, 1.0f);
+            render(); render();
+            require (probe.sustain.load() == 127, "pedal recovery fixture did not enable sustain");
+            const std::uint8_t filler[] { 0xb0, 99, 0 };
+            for (int i = 0; i < 909; ++i) adapter.midiMessage (filler, 3);
+            require (! adapter.midiOverflow, "pedal recovery fixture overflowed before the control flush");
+            adapter.setParameter (midictl::ccBase + 64, 0.0f);
+            render(); render();
+            require (probe.sustain.load() == 0, "queue overflow permanently lost a sustain-off control");
+        }
+        probe.output.store (0.0f);
+        whileHeld (1, [&] { render(); });
+        render();
+        require (noOldOutput(), "a pre-gap fixed audio block replayed after contention");
+        require (! adapter.hasCrashed(), "lock contention was reported as a plugin crash");
+    };
+    try
+    {
+        for (const auto fixed : { 0, 64 })
+        {
+            std::array<float, 128> left {}, right {};
+            const auto unchanged = [&] { return left.back() == 0.25f && right.back() == 0.25f; };
+            auto instrument = std::make_unique<Probe>();
+            auto* voiceProbe = instrument.get();
+            PluginInstrument voice (std::move (instrument), 128, fixed);
+            exercise (voice, *voiceProbe, [&] {
+                left.fill (0.25f); right.fill (0.25f);
+                voice.render (left.data(), right.data(), (int) left.size(), 1.0f, 1.0f);
+            }, [&] { voice.panic(); }, unchanged, [&] { return left.back() == 0.75f && right.back() == 0.75f; },
+            [&] { return left.front() == 0.25f && right.front() == 0.25f; });
+            auto effect = std::make_unique<Probe>();
+            auto* effectProbe = effect.get();
+            PluginEffect fx (std::move (effect), 128, fixed);
+            exercise (fx, *effectProbe, [&] {
+                left.fill (0.25f); right.fill (0.25f);
+                fx.process (left.data(), right.data(), (int) left.size(), {}, 120.0);
+            }, [&] { fx.transportReset(); }, unchanged, [&] { return left.back() == 0.5f && right.back() == 0.5f; },
+            [&] { return left.front() == 0.0f && right.front() == 0.0f; });
+        }
+        return "OK (" + juce::String (checks) + " checks)";
+    }
+    catch (const std::exception& e) { return "ERROR " + juce::String::fromUTF8 (e.what()); }
+}
+
 void PluginEffect::process (float* left, float* right, int n, const EffectParams&, double) noexcept
 {
     // this block's sidechain (null = silence); cleared so a slot whose side input is removed hears silence again
@@ -1075,12 +1499,20 @@ void PluginEffect::process (float* left, float* right, int n, const EffectParams
     const std::unique_lock<std::mutex> layout (layoutLock, std::try_to_lock);
     if (! layout.owns_lock())
         return;
+    const juce::CriticalSection::ScopedTryLockType lock (plugin->getCallbackLock());
+    if (! lock.isLocked())
+    {
+        if (fixed != nullptr) fixed->clear();
+        return; // state access owns this instance: dry bypass; keep reset and parameter changes for the next block
+    }
+    if (crashed.load (std::memory_order_relaxed)) return;
     if (resetPending.exchange (false, std::memory_order_relaxed))
         if (const auto code = runReset (*plugin, crashed, name); code != 0)
         {
             failed (code);
             return;
         }
+    if (flushParameters (*plugin, parameterChanges, crashed, name) != 0) return;
     flushMidiControls();
 
     if (fixed != nullptr)

+ 42 - 3
src/engine/PluginHost.h

@@ -48,6 +48,34 @@ struct PluginCrash
 int pluginCrashCount() noexcept;
 std::vector<PluginCrash> pluginCrashes();
 
+// The audio thread cannot wait for hosted state access. Keep the last contended automation value per parameter,
+// in storage allocated when the instance is created, and apply it before the next available processing block.
+class HostedParameterChanges
+{
+public:
+    explicit HostedParameterChanges (int count);
+    bool contains (int index) const noexcept { return index >= 0 && index < count; }
+    void defer (int index, float value) noexcept;
+    void clear (int index) noexcept;
+    float latest (int index) const noexcept;
+    void observed (int index, float value) noexcept;
+    void beginRestore() noexcept { restoreEpoch.fetch_add (1, std::memory_order_acq_rel); }
+    bool takePending() noexcept { return pending.exchange (false, std::memory_order_acq_rel); }
+    bool take (int index, float& value) noexcept;
+    int size() const noexcept { return count; }
+
+private:
+    struct Value
+    {
+        std::atomic<std::uint64_t> deferred { 0 }; // restore epoch and float bits, published as one value
+        std::atomic<float> cached { -1.0f };
+    };
+    const int count;
+    std::unique_ptr<Value[]> values;
+    std::atomic<bool> pending { false };
+    std::atomic<std::uint32_t> restoreEpoch { 1 };
+};
+
 // A hosted plugin's audio outputs as FL's wrapper lists them in Processing › Connections (round 188d, issue #114):
 // one per output bus (bus 0 = the main output); a plugin with one bus of more than two channels (a bridged plugin)
 // in stereo pairs. `channel` = its first channel in the plugin's buffer.
@@ -106,7 +134,7 @@ public:
     std::optional<std::string> captureState();
     // State restoration is serialized with this instance's processing by its callback lock.
     bool restoreState (const std::string& state);
-    // Sets a parameter from the UI / controllers (setValueNotifyingHost), guarded like the audio calls.
+    // UI/controllers may wait for this instance's current block; audio-side calls only try the lock.
     void setParameterFromUi (int index, float value);
     void setRenderMode (bool offline);
     void resetForExport(); // UI thread, before an export (the audio is not running through it)
@@ -115,7 +143,7 @@ public:
     float midiControlValue (int index) const noexcept { return midiControls.value (index); }
     void noteOnMidi (int key, float velocity, int midiChannel) noexcept override;
     void noteOffMidi (int key, int midiChannel) noexcept override;
-    void midiMessage (const std::uint8_t* bytes, int size) noexcept override { midi.addEvent (bytes, size, 0); }
+    void midiMessage (const std::uint8_t* bytes, int size) noexcept override { queueMidi (bytes, size); }
     void pitchBend (float) noexcept override {} // (the plugin takes the raw MIDI pitch bend, midiMessage)
     int takeMidiOutput (MidiOutNote* out, int max) noexcept override;
     // Issue #14: the channel's PITCH knob, fine tune and main pitch reach the plugin as MIDI pitch bend (scaled by the
@@ -138,6 +166,7 @@ public:
 
 private:
     void mixOutputs (const float* const* channels, int numChannels, int at, int count, float gl, float gr, float* left, float* right) noexcept;
+    friend juce::String pluginStateContentionSelfTest();
     std::vector<PluginOutputInfo> outs;
     std::unique_ptr<std::atomic<int>[]> routeOffset;   // [output]
     std::unique_ptr<std::atomic<bool>[]> routeActive;  // [output]
@@ -170,9 +199,16 @@ private:
     HostedKeys heldKeys; // per MIDI channel: the notes on (their note offs on stop / jump, round 169c)
     void hold (int channel, int key, bool on) noexcept { heldKeys.set (channel, key, on); }
     void releaseHeldKeys() noexcept; // a note off for each held key
+    void queueMidi (const void* bytes, int size, int offset = 0) noexcept;
+    void queueMidi (const juce::MidiMessage& message, int offset = 0) noexcept { queueMidi (message.getRawData(), message.getRawDataSize(), offset); }
+    void rememberMidi (const juce::MidiBuffer& messages) noexcept;
+    void recoverMidi() noexcept;
+    HostedKeys deliveredKeys; // note-ons actually sent, so an overflow can release them without replaying missed notes
+    bool midiOverflow = false, recoveryMidi = false;
     HostBlockClock blockClock; // where each plugin block starts in the renderer's chunk (the play head's position)
 
     std::unique_ptr<juce::AudioPluginInstance> plugin;
+    mutable HostedParameterChanges parameterChanges;
     juce::AudioBuffer<float> buffer;
     juce::MidiBuffer midi;
     midictl::State midiControls;
@@ -217,7 +253,7 @@ public:
     std::optional<std::string> captureState();
     // State restoration is serialized with this instance's processing by its callback lock.
     bool restoreState (const std::string& state);
-    // Sets a parameter from the UI / controllers (setValueNotifyingHost), guarded like the audio calls.
+    // UI/controllers may wait for this instance's current block; audio-side calls only try the lock.
     void setParameterFromUi (int index, float value);
     void setRenderMode (bool offline);
     void resetForExport(); // UI thread, before an export (the audio is not running through it)
@@ -237,11 +273,13 @@ public:
     float midiControlValue (int index) const noexcept { return midiControls.value (index); }
 
 private:
+    friend juce::String pluginStateContentionSelfTest();
     void failed (std::uint32_t code) noexcept;
     void flushMidiControls() noexcept;
     void findSideChannel() noexcept;
 
     std::unique_ptr<juce::AudioPluginInstance> plugin;
+    mutable HostedParameterChanges parameterChanges;
     juce::AudioBuffer<float> buffer;
     juce::MidiBuffer midi;
     midictl::State midiControls;
@@ -266,6 +304,7 @@ bool hasSideBus (const juce::AudioPluginInstance& plugin);
 // --selftest: a stand-in plugin with a stereo sidechain bus (it outputs its side input) inside PluginEffect, plain and
 // with fixed blocks: the slot's sidechain reaches the bus, and silence once the slot has none. "OK" or what failed.
 juce::String pluginSidechainSelfTest();
+juce::String pluginStateContentionSelfTest();
 
 // Plugin formats, known-plugin list (saved in AppData) and instance creation.
 // UI thread, except the scan functions (any thread; one scan at a time) and the background scan.

+ 13 - 48
src/engine/RemoteControl.cpp

@@ -16,6 +16,7 @@
 #include "engine/RemoteError.h"
 #include "engine/RemoteFileSecurity.h"
 #include "engine/RemoteProjectControl.h"
+#include "engine/RemoteNotes.h"
 #include "platform/Paths.h"
 #include <deque>
 
@@ -24,6 +25,7 @@
 #include <cmath>
 #include <stdexcept>
 #include <string>
+#include <string_view>
 #include <juce_events/juce_events.h>
 
 #if JUCE_MAC || JUCE_LINUX || JUCE_BSD
@@ -41,7 +43,6 @@ namespace
 constexpr std::size_t maxMessage = 1024 * 1024;
 constexpr std::size_t maxHandshake = 1024;
 constexpr const char* protocol = "lynx-control/1";
-constexpr juce::int64 maxTick = 1000000000;
 using Field = std::pair<const char*, juce::var>;
 
 juce::var object (std::initializer_list<Field> fields)
@@ -97,45 +98,6 @@ int indexFor (const juce::var& args, std::size_t size)
 using remote_files::randomToken;
 using remote_files::writeDiscovery;
 
-juce::var noteValue (const Note& n)
-{
-    return object ({ { "start", (juce::int64) n.start }, { "length", (juce::int64) n.length },
-                     { "channel", n.channel }, { "key", n.key }, { "velocity", n.velocity },
-                     { "pan", n.pan }, { "muted", n.muted }, { "finePitch", n.finePitch },
-                     { "slide", n.slide }, { "porta", n.porta }, { "release", n.release },
-                     { "modX", n.modX }, { "modY", n.modY }, { "colour", n.colour }, { "group", n.group } });
-}
-
-Note parseNote (const juce::var& value, std::size_t channels)
-{
-    if (value.getDynamicObject() == nullptr)
-        invalid ("Every note must be an object");
-    for (const auto* field : { "start", "length", "channel", "key", "velocity", "pan", "muted", "finePitch",
-                              "slide", "porta", "release", "modX", "modY", "colour", "group" })
-        if (! value.hasProperty (field))
-            invalid (juce::String ("Every replacement note must include ") + field + "; read the complete notes first");
-    if (channels == 0)
-        invalid ("Cannot add a note without a channel");
-    Note n;
-    n.start = integer (value, "start", 0, maxTick);
-    n.length = integer (value, "length", 1, maxTick);
-    if (n.start > maxTick - n.length)
-        invalid ("Note end is outside its allowed range");
-    n.channel = (int) integer (value, "channel", 0, (juce::int64) channels - 1);
-    n.key = (int) integer (value, "key", 0, 127);
-    n.velocity = (float) number (value, "velocity", 0, 1);
-    if (value.hasProperty ("pan")) n.pan = (float) number (value, "pan", -1, 1);
-    if (value.hasProperty ("muted")) n.muted = boolean (value, "muted");
-    if (value.hasProperty ("finePitch")) n.finePitch = (float) number (value, "finePitch", -120, 120);
-    if (value.hasProperty ("slide")) n.slide = boolean (value, "slide");
-    if (value.hasProperty ("porta")) n.porta = boolean (value, "porta");
-    if (value.hasProperty ("release")) n.release = (float) number (value, "release", 0, 1);
-    if (value.hasProperty ("modX")) n.modX = (float) number (value, "modX", 0, 1);
-    if (value.hasProperty ("modY")) n.modY = (float) number (value, "modY", 0, 1);
-    if (value.hasProperty ("colour")) n.colour = (int) integer (value, "colour", 0, 15);
-    if (value.hasProperty ("group")) n.group = (int) integer (value, "group", 0, 2147483647);
-    return n;
-}
 } // namespace
 
 struct RemoteControl::Impl final : juce::Thread
@@ -268,7 +230,7 @@ struct RemoteControl::Impl final : juce::Thread
                 const auto limit = args.hasProperty ("limit") ? integer (args, "limit", 1, 256) : 256;
                 juce::Array<juce::var> notes;
                 for (auto i = offset; i < total && i - offset < limit; ++i)
-                    notes.add (noteValue (source[(std::size_t) i]));
+                    notes.add (remote_notes::toValue (source[(std::size_t) i]));
                 auto result = object ({ { "index", index }, { "notes", notes }, { "offset", offset }, { "totalNotes", total },
                                         { "revision", (juce::int64) engine.getSongStamp() } });
                 if (offset < total && total - offset > limit) result.getDynamicObject()->setProperty ("nextOffset", offset + limit);
@@ -380,7 +342,7 @@ struct RemoteControl::Impl final : juce::Thread
                 std::vector<Note> notes;
                 notes.reserve ((std::size_t) input->size());
                 for (const auto& value : *input)
-                    notes.push_back (parseNote (value, s.channels.size()));
+                    notes.push_back (remote_notes::fromValue (value, s.channels.size()));
                 const auto count = (int) notes.size();
                 engine.editSongRemoteTransaction ([index, notes = std::move (notes)] (Song& song) {
                     auto& pattern = song.patterns[(std::size_t) index];
@@ -455,11 +417,13 @@ struct RemoteControl::Impl final : juce::Thread
         catch (...) {}
     }
 
-    juce::var request (const juce::String& json)
+    juce::var request (std::string_view bytes)
     {
-        const auto utf8 = json.toRawUTF8();
-        if (! remote_json::withinNestingLimit (std::string_view (utf8, json.getNumBytesAsUTF8())))
-            return failure ("JSON nesting exceeds the control request limit");
+        // Validate the wire bytes before JUCE's permissive UTF-8 conversion can
+        // reinterpret an overlong encoding as a structural JSON delimiter.
+        if (! remote_json::withinNestingLimit (bytes))
+            return failure ("Request is invalid UTF-8 or exceeds the JSON nesting limit");
+        const auto json = juce::String::fromUTF8 (bytes.data(), (int) bytes.size());
         juce::var input;
         if (juce::JSON::parse (json, input).failed() || input.getDynamicObject() == nullptr)
             return failure ("Invalid JSON request");
@@ -502,7 +466,8 @@ struct RemoteControl::Impl final : juce::Thread
         const auto longOperation = work->op == "plugin.parameters_set" || work->op == "effect.load"
                                 || work->op == "history.undo" || work->op == "history.redo"
                                 || work->op == "channel.create" || work->op == "instrument.replace"
-                                || work->op == "project.read" || work->op == "project.edit" || work->op == "device.state";
+                                || work->op == "project.read" || work->op == "project.edit" || work->op == "device.state"
+                                || work->op == "playlist.edit";
         const auto deadline = juce::Time::getMillisecondCounterHiRes() + (longOperation ? 60000.0 : 5000.0);
         while (state->active && ! threadShouldExit() && juce::Time::getMillisecondCounterHiRes() < deadline)
             if (work->finished.wait (50))
@@ -614,7 +579,7 @@ struct RemoteControl::Impl final : juce::Thread
         }
         std::string line;
         auto response = readLine (socket, pending, line, maxMessage, juce::Time::getMillisecondCounterHiRes() + 2000.0)
-            ? request (juce::String::fromUTF8 (line.data(), (int) line.size()))
+            ? request (line)
             : failure ("Authenticated request exceeded its byte or time limit");
         if (juce::JSON::toString (response, true).getNumBytesAsUTF8() > maxMessage)
             response = failure ("Response exceeds 1 MiB; request a smaller collection");

+ 48 - 5
src/engine/RemoteJsonLimits.h

@@ -5,21 +5,64 @@
 
 namespace lynx::remote_json
 {
+inline bool canonicalUtf8 (std::string_view text) noexcept
+{
+    // JUCE's release parser can interpret overlong UTF-8 as ASCII quotes,
+    // escapes or brackets. Validate the original bytes before counting syntax.
+    for (std::size_t i = 0; i < text.size(); ++i)
+    {
+        const auto first = static_cast<unsigned char> (text[i]);
+        if (first == 0) return false; // JUCE strings terminate here; JSON uses \u0000 instead.
+        if (first < 0x80) continue;
+        std::size_t extra = 0;
+        unsigned char secondMin = 0x80, secondMax = 0xbf;
+        if (first >= 0xc2 && first <= 0xdf) extra = 1;
+        else if (first >= 0xe0 && first <= 0xef)
+        {
+            extra = 2;
+            if (first == 0xe0) secondMin = 0xa0; // no overlong encoding below U+0800
+            if (first == 0xed) secondMax = 0x9f; // no UTF-16 surrogate code points
+        }
+        else if (first >= 0xf0 && first <= 0xf4)
+        {
+            extra = 3;
+            if (first == 0xf0) secondMin = 0x90; // no overlong encoding below U+10000
+            if (first == 0xf4) secondMax = 0x8f; // at most U+10FFFF
+        }
+        else return false;
+        if (text.size() - i <= extra) return false;
+        const auto second = static_cast<unsigned char> (text[i + 1]);
+        if (second < secondMin || second > secondMax) return false;
+        for (std::size_t j = 2; j <= extra; ++j)
+        {
+            const auto continuation = static_cast<unsigned char> (text[i + j]);
+            if (continuation < 0x80 || continuation > 0xbf) return false;
+        }
+        i += extra;
+    }
+    return true;
+}
+
 // Run before JUCE's recursive JSON parser, including before authentication. The
-// byte limit alone does not bound parser stack usage. Syntax remains JUCE's job.
+// byte limit alone does not bound parser stack usage. Apart from canonical UTF-8
+// and raw NUL rejection, syntax remains JUCE's job.
 inline bool withinNestingLimit (std::string_view json, std::size_t limit = 64) noexcept
 {
+    if (! canonicalUtf8 (json)) return false;
     std::size_t depth = 0;
-    bool quoted = false, escaped = false;
+    char quote = 0;
+    bool escaped = false;
     for (const auto c : json)
     {
-        if (quoted)
+        if (quote != 0)
         {
             if (escaped) escaped = false;
             else if (c == '\\') escaped = true;
-            else if (c == '"') quoted = false;
+            else if (c == quote) quote = 0;
         }
-        else if (c == '"') quoted = true;
+        // JUCE also accepts single-quoted strings. A quote inside a string
+        // opened by the other delimiter must not hide structural nesting.
+        else if (c == '"' || c == '\'') quote = c;
         else if (c == '{' || c == '[')
         {
             if (++depth > limit) return false;

+ 103 - 0
src/engine/RemoteNotes.h

@@ -0,0 +1,103 @@
+#pragma once
+
+#include "core/Song.h"
+#include <juce_core/juce_core.h>
+#include <array>
+#include <cmath>
+#include <initializer_list>
+#include <limits>
+#include <stdexcept>
+#include <utility>
+
+namespace lynx::remote_notes
+{
+namespace detail
+{
+constexpr std::array fields { "start", "length", "channel", "key", "velocity", "pan", "muted", "finePitch",
+                              "slide", "porta", "release", "modX", "modY", "colour", "group", "chance",
+                              "velocityRange", "chanceGroup", "chanceOne" };
+constexpr juce::int64 maxTick = 1000000000;
+
+[[noreturn]] inline void invalid (const juce::String& why) { throw std::runtime_error (why.toStdString()); }
+
+inline double number (const juce::var& value, const char* field, double low, double high)
+{
+    const auto& input = value[field];
+    if (! (input.isInt() || input.isInt64() || input.isDouble()))
+        invalid (juce::String (field) + " must be a number");
+    const auto result = (double) input;
+    if (! std::isfinite (result) || result < low || result > high)
+        invalid (juce::String (field) + " is outside its allowed range");
+    return result;
+}
+
+inline juce::int64 integer (const juce::var& value, const char* field, juce::int64 low, juce::int64 high)
+{
+    const auto result = number (value, field, (double) low, (double) high);
+    if (std::floor (result) != result)
+        invalid (juce::String (field) + " must be an integer");
+    return (juce::int64) result;
+}
+
+inline bool boolean (const juce::var& value, const char* field)
+{
+    if (! value[field].isBool())
+        invalid (juce::String (field) + " must be true or false");
+    return (bool) value[field];
+}
+} // namespace detail
+
+// The read and complete-replacement operations share one codec so an unchanged
+// read/write cycle cannot reset expression fields to their model defaults.
+inline juce::var toValue (const Note& n)
+{
+    auto* result = new juce::DynamicObject();
+    for (const auto& [name, value] : std::initializer_list<std::pair<const char*, juce::var>> {
+             { "start", (juce::int64) n.start }, { "length", (juce::int64) n.length },
+             { "channel", n.channel }, { "key", n.key }, { "velocity", (double) n.velocity },
+             { "pan", (double) n.pan }, { "muted", n.muted }, { "finePitch", (double) n.finePitch },
+             { "slide", n.slide }, { "porta", n.porta }, { "release", (double) n.release },
+             { "modX", (double) n.modX }, { "modY", (double) n.modY }, { "colour", n.colour }, { "group", n.group },
+             { "chance", (double) n.chance }, { "velocityRange", (double) n.velocityRange },
+             { "chanceGroup", n.chanceGroup }, { "chanceOne", n.chanceOne } })
+        result->setProperty (name, value);
+    return result;
+}
+
+inline Note fromValue (const juce::var& value, std::size_t channels)
+{
+    const auto* object = value.getDynamicObject();
+    if (object == nullptr)
+        detail::invalid ("Every note must be an object");
+    for (const auto* field : detail::fields)
+        if (! value.hasProperty (field))
+            detail::invalid (juce::String ("Every replacement note must include ") + field + "; read the complete notes first");
+    if (object->getProperties().size() != (int) detail::fields.size())
+        detail::invalid ("Replacement note contains an unsupported field");
+    if (channels == 0)
+        detail::invalid ("Cannot add a note without a channel");
+    Note n;
+    n.start = detail::integer (value, "start", 0, detail::maxTick);
+    n.length = detail::integer (value, "length", 1, detail::maxTick);
+    if (n.start > detail::maxTick - n.length)
+        detail::invalid ("Note end is outside its allowed range");
+    n.channel = (int) detail::integer (value, "channel", 0, (juce::int64) channels - 1);
+    n.key = (int) detail::integer (value, "key", 0, 127);
+    n.velocity = (float) detail::number (value, "velocity", 0, 1);
+    n.pan = (float) detail::number (value, "pan", -1, 1);
+    n.muted = detail::boolean (value, "muted");
+    n.finePitch = (float) detail::number (value, "finePitch", -120, 120);
+    n.slide = detail::boolean (value, "slide");
+    n.porta = detail::boolean (value, "porta");
+    n.release = (float) detail::number (value, "release", 0, 1);
+    n.modX = (float) detail::number (value, "modX", 0, 1);
+    n.modY = (float) detail::number (value, "modY", 0, 1);
+    n.colour = (int) detail::integer (value, "colour", 0, 15);
+    n.group = (int) detail::integer (value, "group", 0, std::numeric_limits<int>::max());
+    n.chance = (float) detail::number (value, "chance", 0, 1);
+    n.velocityRange = (float) detail::number (value, "velocityRange", -1, 1);
+    n.chanceGroup = (int) detail::integer (value, "chanceGroup", 0, std::numeric_limits<int>::max());
+    n.chanceOne = detail::boolean (value, "chanceOne");
+    return n;
+}
+} // namespace lynx::remote_notes

+ 211 - 35
src/engine/RemoteProjectDocument.cpp

@@ -16,56 +16,231 @@
 #include "core/WaveTraveller.h"
 #include <set>
 #include <tuple>
+#include <map>
 
 namespace lynx
 {
 namespace
 {
-void hostedStateClears (const juce::var& before, const juce::var& after)
+enum class DocumentShape
 {
-    // Clearing a vendor blob does not have a portable in-place reset meaning. Use the
-    // explicit catalog replacement operations for defaults, rather than silently keeping
-    // a running device's old state. This walk also covers branches, Patchers and bus heads.
-    std::map<juce::String, int> oldEmpty, newEmpty;
-    std::set<juce::String> saved;
-    const auto collect = [] (const juce::var& root, std::map<juce::String, int>& empty, std::set<juce::String>* nonempty) {
-        std::function<void (const juce::var&)> visit;
-        visit = [&] (const juce::var& value) {
+    data, readOnly, root, info, channel, plugin, origin, arp, misc, layer, synth, sampler, precomputed,
+    keyLabels, mixer, effect, branch, link, patcher, node, busHead, standIn, pattern, events, automation,
+    modulator, vca, video, videoTrack, videoClip, adr, adrSettings, cue, take, grid, scene, gridClip, arrangement
+};
+struct DocumentField
+{
+    DocumentShape shape = DocumentShape::data;
+    bool array = false;
+};
+using DocumentFields = std::map<juce::String, DocumentField>;
+const DocumentFields& editableDocumentFields (DocumentShape shape)
+{
+    // This is an API capability list, independent of the native file loader. Every changed
+    // object must contain only reviewed fields, even if an unreviewed member is unchanged;
+    // an entirely unchanged subtree is preserved. Parent/array replacement follows the same
+    // rule. New save-format fields therefore require review before their containing object
+    // is edited. Positional musical data is still validated by
+    // the exact native round trip and the reference/bounds checks below.
+    static const auto schemas = [] {
+        using S = DocumentShape;
+        std::map<S, DocumentFields> result;
+        const auto add = [&] (S owner, const char* names, S child = S::data, bool array = false) {
+            for (const auto& name : juce::StringArray::fromTokens (names, " ", ""))
+                result[owner].emplace (name, DocumentField { child, array });
+        };
+        add (S::root, "bpm beatsPerBar swing chanceSeed channelGroups masterPitch substitutesBypassed cleanMixer performanceMode "
+             "autoCrossfades compCrossfadeMs playTruncatedNotes fastDeclick panLaw autoPdc compensateAutomations timeSettings "
+             "scaleHighlight dataFolder currentPattern playlist patternBlocks blocks playlistTracks playlistTrackHeights "
+             "playlistTrackColours playlistTrackGroups playlistCompTracks playlistTrackLocks playlistTrackLanes "
+             "playlistTrackModes playlistTrackPerformance playlistTrackIcons currentArrangement mode loop arrangementUids midiLinks initialValues");
+        add (S::root, "format version savedBy projectId nextUid session clipFadesPerClip", S::readOnly);
+        add (S::root, "info", S::info);
+        add (S::root, "channels", S::channel, true);
+        add (S::root, "patterns", S::pattern, true);
+        add (S::root, "automations", S::automation, true);
+        add (S::root, "modulators", S::modulator, true);
+        add (S::root, "vcas", S::vca, true);
+        add (S::root, "mixer", S::mixer, true);
+        add (S::root, "video", S::video);
+        add (S::root, "adr", S::adr);
+        add (S::root, "clipGrid", S::grid);
+        add (S::root, "arrangements", S::arrangement, true);
+        add (S::info, "title author genre comments");
+        add (S::info, "url showOnOpen created workSeconds", S::readOnly);
+        add (S::channel, "name instrument volume pan muted ghostHidden soloLock sample controllerState pluginState modelParams zones "
+             "mixer maxPolyphony colour group swingMix arp cut keyRegion receiveFrom icon flWrapperFlags loopStarter uid");
+        add (S::channel, "plugin", S::plugin);
+        add (S::channel, "flOrigin", S::origin);
+        add (S::channel, "keyLabels", S::keyLabels);
+        add (S::channel, "arpFl", S::arp);
+        add (S::channel, "misc", S::misc);
+        add (S::channel, "layer", S::layer);
+        add (S::channel, "synthSettings", S::synth);
+        add (S::channel, "samplerSettings", S::sampler);
+        add (S::channel, "patcher", S::patcher);
+        add (S::channel, "standIns", S::standIn, true);
+        add (S::plugin, "id name state foreign fixedBuffers separateProcess threaded maxSizeBuffers allowSmartDisable hostMaxBuffer "
+             "midiInPort midiOutPort notifyRender latencyMs releaseVelocity sendBendRange bendRange modXAftertouch "
+             "allNotesOffOnStop resetOnFlush sendLoopPosition allowHostKeys hostKeysFirst bitSize detached outputs");
+        add (S::origin, "plugin state print");
+        add (S::arp, "chord chordSustain slide octaveRepeat");
+        add (S::misc, "shift gate fullPorta mono porta portaTime echo velocityTracking keyTracking pitchRange mainPitch rootNote addToKey fineTune");
+        add (S::layer, "children random crossfade sequential fade");
+        add (S::synth, "osc spectrum spectrumPhase spectrumDecay spectrumTarget adsr filter ladder chorus stereoTremolo vibratoCents "
+             "mono porta portaTime am ring keyTrack bands sweep sweepTime fm filterEnv pitchEnv lfo");
+        add (S::sampler, "pitch attack decay sustain release stretchBeats keepPitch stretchMethod flStretchMode flStretchPitch stretchPitch "
+             "warp region startOffset slices reverse cut porta portaTime filter gainDb useLoopPoints flVelocityLaw declickMode "
+             "flVolumeEnvelope flChannel filterEnv pitchEnv lfo");
+        add (S::sampler, "precomputed", S::precomputed);
+        add (S::precomputed, "removeDc normalize reversePolarity fadeStereo swapStereo pingPong fadeIn fadeOut crossfade trim "
+             "boost eq ringMix ringFreq stereoDelay cutoff resonance reverb reverbType pogo clip");
+        add (S::mixer, "name volume pan muted solo soloSources threaded separator folded dock toMaster masterLevel colour stereo "
+             "invertPhase swap input inputMono monitor recordSafe recordTo recordSource recordDryToo latencyMs latencyBypass "
+             "compensateMaster icon output outputMode eq eqBypassed sends lostSends");
+        add (S::mixer, "effects", S::effect, true);
+        add (S::mixer, "standIns", S::standIn, true);
+        add (S::effect, "kind on params sendSpan mix smartDisable row sidechain sidechain2 sendTransient sendSustain state sample preset abOther abB");
+        add (S::effect, "plugin substituteFor", S::plugin);
+        add (S::effect, "flOrigin", S::origin);
+        add (S::effect, "patcher", S::patcher);
+        add (S::effect, "branches", S::branch, true);
+        add (S::effect, "links", S::link, true);
+        add (S::branch, "gain");
+        add (S::branch, "chain", S::effect, true);
+        add (S::link, "branch source target param curve");
+        add (S::patcher, "wires io published outputTracks fromMidiPorts toMidiPorts fromNotesHidden surface surfaceAt");
+        add (S::patcher, "nodes", S::node, true);
+        add (S::node, "label x y paramIns paramOuts");
+        add (S::node, "channel", S::channel);
+        add (S::node, "effect", S::effect);
+        add (S::node, "busHeads", S::busHead, true);
+        add (S::busHead, "bus gain");
+        add (S::busHead, "head", S::effect);
+        add (S::standIn, "pattern loop path hash length plugin by");
+        add (S::pattern, "name uid length colour loopOn loopStarterGenre loopMode channelLoops markers notes");
+        add (S::pattern, "events", S::events, true);
+        add (S::events, "target events");
+        add (S::automation, "name uid target points source curve lfo lfoFl");
+        add (S::modulator, "name shape sync beats hz phase unipolar seed routes");
+        add (S::vca, "name colour level muted members parent");
+        add (S::video, "rate startTimecode rateFromVideo timecodeRuler burnIn");
+        add (S::video, "tracks", S::videoTrack, true);
+        add (S::videoTrack, "name muted height colour");
+        add (S::videoTrack, "clips", S::videoClip, true);
+        add (S::videoClip, "path start offset length duration uid");
+        add (S::adr, "current");
+        add (S::adr, "settings", S::adrSettings);
+        add (S::adr, "cues", S::cue, true);
+        add (S::adrSettings, "preRoll postRoll beeps beepFrequency streamer streamerLength streamerColour punch cycle guideInsert headphoneOutput recordInsert takeTrack");
+        add (S::cue, "id in out character line notes status selected comp compClips");
+        add (S::cue, "takes", S::take, true);
+        add (S::take, "number name clip rating circled note aligned");
+        add (S::grid, "quant backOnStop followActions");
+        add (S::grid, "scenes", S::scene, true);
+        add (S::grid, "clips", S::gridClip, true);
+        add (S::scene, "name colour tempo beatsPerBar");
+        add (S::gridClip, "scene name colour mode quant legato loop noStop follow clip");
+        add (S::arrangement, "name clips blocks loop markers");
+        return result;
+    }();
+    static const DocumentFields none;
+    const auto found = schemas.find (shape);
+    return found == schemas.end() ? none : found->second;
+}
+
+void editableDocument (const juce::var& before, const juce::var& after, DocumentField field = { DocumentShape::root })
+{
+    using S = DocumentShape;
+    if (remote_json::equal (before, after)) return;
+    if (field.shape == S::readOnly)
+        remote_json::invalid ("Project field is read-only through document edits");
+    if (field.array)
+    {
+        if (after.isVoid()) return;
+        const auto* list = after.getArray();
+        if (list == nullptr) remote_json::invalid ("Editable project collection must remain an array");
+        const auto* old = before.getArray();
+        for (int i = 0; i < list->size(); ++i)
+            editableDocument (old != nullptr && i < old->size() ? (*old)[i] : juce::var(), (*list)[i], { field.shape });
+        return;
+    }
+    if (field.shape == S::data)
+    {
+        if (after.getDynamicObject() != nullptr)
+            remote_json::invalid ("Project field does not allow editable object members");
+        if (const auto* list = after.getArray())
+            for (const auto& item : *list) editableDocument ({}, item, { S::data });
+        return;
+    }
+    if (! after.isVoid() && after.getDynamicObject() == nullptr)
+        remote_json::invalid ("Editable project object must remain an object");
+    const auto* old = before.getDynamicObject();
+    const auto* next = after.getDynamicObject();
+    if (field.shape == S::keyLabels)
+    {
+        if (next != nullptr)
+            for (const auto& property : next->getProperties())
+            {
+                const auto key = property.name.toString();
+                if (key != juce::String (key.getIntValue()) || key.getIntValue() < 0 || key.getIntValue() > 127 || ! property.value.isString())
+                    remote_json::invalid ("Editable key labels must name MIDI keys 0..127 and contain text");
+            }
+        return;
+    }
+    const auto& fields = editableDocumentFields (field.shape);
+    const auto check = [&] (const juce::Identifier& key) {
+        const auto found = fields.find (key.toString());
+        if (found == fields.end()) remote_json::invalid ("Project field is not on the editable document allowlist");
+        editableDocument (old != nullptr ? old->getProperty (key) : juce::var(),
+                          next != nullptr ? next->getProperty (key) : juce::var(), found->second);
+    };
+    if (next != nullptr) for (const auto& property : next->getProperties()) check (property.name);
+    if (old != nullptr) for (const auto& property : old->getProperties())
+        if (next == nullptr || ! next->hasProperty (property.name)) check (property.name);
+}
+
+void hostedStatePolicy (const juce::var& before, const juce::var& after)
+{
+    using Device = std::tuple<juce::String, juce::String, juce::String>;
+    std::map<juce::String, Device> known;
+    const auto visit = [] (const juce::var& root, const auto& device) {
+        std::function<void (const juce::var&, const juce::String&)> walk;
+        walk = [&] (const juce::var& value, const juce::String& path) {
             if (const auto* object = value.getDynamicObject())
             {
-                if (value["id"].isString())
+                for (const auto& property : object->getProperties())
                 {
-                    const auto key = value["id"].toString();
-                    if (value["state"].toString().isEmpty()) ++empty[key];
-                    else if (nonempty != nullptr) nonempty->insert (key);
+                    const auto key = property.name.toString();
+                    const auto childPath = path + "/" + key;
+                    if ((key == "plugin" || key == "substituteFor") && property.value.getDynamicObject() != nullptr)
+                        device (childPath, Device { property.value["id"].toString(), property.value["foreign"].toString(), property.value["state"].toString() });
+                    else walk (property.value, childPath);
                 }
-                for (const auto& property : object->getProperties()) visit (property.value);
             }
             else if (const auto* array = value.getArray())
-                for (const auto& item : *array) visit (item);
+                for (int i = 0; i < array->size(); ++i)
+                {
+                    const auto& item = (*array)[i];
+                    // Channel UIDs keep a device stable when top-level channels are reordered.
+                    // Unidentified nested devices/effects remain bound to their exact container slot.
+                    const auto key = item["uid"].isString() ? "uid:" + item["uid"].toString() : juce::String (i);
+                    walk (item, path + "/" + key);
+                }
         };
-        visit (root);
+        walk (root, {});
     };
-    collect (before, oldEmpty, &saved);
-    collect (after, newEmpty, nullptr);
-    for (const auto& key : saved)
-        if (newEmpty[key] > oldEmpty[key])
-            remote_json::invalid ("Project edits cannot clear hosted device state; use a catalog replacement operation to reset it");
-    std::function<void (const juce::var&, const juce::var&)> compare;
-    compare = [&] (const juce::var& old, const juce::var& next) {
-        if (const auto* object = old.getDynamicObject())
+    visit (before, [&] (const auto& path, const Device& device) { known.emplace (path, device); });
+    visit (after, [&] (const auto& path, const Device& device) {
+        const auto old = known.find (path);
+        if (old == known.end() || std::get<0> (old->second) != std::get<0> (device) || std::get<1> (old->second) != std::get<1> (device))
         {
-            if (next.getDynamicObject() == nullptr) return;
-            if (old["id"].isString() && old["state"].isString() && old["state"].toString().isNotEmpty()
-                && next["id"] == old["id"] && next["state"].toString().isEmpty())
-                remote_json::invalid ("Project edits cannot clear hosted device state; use a catalog replacement operation to reset it");
-            for (const auto& property : object->getProperties()) compare (property.value, next[property.name]);
+            if (std::get<2> (device).isNotEmpty())
+                remote_json::invalid ("Hosted plugin state is read-only; use a catalog replacement operation to create or reset a device");
         }
-        else if (const auto* array = old.getArray())
-            if (const auto* other = next.getArray())
-                for (int i = 0; i < std::min (array->size(), other->size()); ++i) compare ((*array)[i], (*other)[i]);
-    };
-    compare (before, after);
+        else if (std::get<2> (old->second) != std::get<2> (device))
+            remote_json::invalid ("Hosted plugin state is read-only; use native parameter operations or the plugin editor");
+    });
 }
 
 void references (Song& song)
@@ -293,10 +468,11 @@ Song stage (const Song& source, const juce::var& patch)
         remote_json::invalid ("Cannot decode the native project document");
     const auto candidate = remote_json::apply (before, patch);
     if (candidate.getDynamicObject() == nullptr) remote_json::invalid ("Project root must remain an object");
-    hostedStateClears (before, candidate);
+    hostedStatePolicy (before, candidate);
     for (const auto* key : { "format", "version", "projectId", "nextUid", "session" })
         if (before.hasProperty (key) != candidate.hasProperty (key) || ! remote_json::equal (before[key], candidate[key]))
             remote_json::invalid ("Project format, lineage and collaboration identity are read-only");
+    editableDocument (before, candidate);
     const auto json = juce::JSON::toString (candidate, true, 17);
     if (json.getNumBytesAsUTF8() > maxBytes) remote_json::invalid ("Edited project exceeds the 64 MiB remote API limit");
     juce::String error;

+ 5 - 4
src/ui/RemoteControlSettings.cpp

@@ -1,5 +1,6 @@
 #include "ui/RemoteControlSettings.h"
 #include "platform/Paths.h"
+#include "ui/I18n.h"
 #include <optional>
 
 namespace lynx::remoteui
@@ -25,9 +26,9 @@ bool active() { return running; }
 juce::String status()
 {
     if (detail.isNotEmpty()) return detail;
-    return running ? "Remote control active — local clients can read and edit this project."
-                   : enabled() ? "Remote control could not start. Disable and re-enable to retry."
-                               : "Remote control is off.";
+    return juce::String::fromUTF8 (running ? TR_NOOP ("Remote control active — local clients can read and edit this project.")
+                   : enabled() ? TR_NOOP ("Remote control could not start. Disable and re-enable to retry.")
+                               : TR_NOOP ("Remote control is off."));
 }
 void setEnabled (bool on)
 {
@@ -39,7 +40,7 @@ void setEnabled (bool on)
             requested = false;
             if (change) change (false);
         }
-        detail = "The remote control setting could not be saved.";
+        detail = juce::String::fromUTF8 (TR_NOOP ("The remote control setting could not be saved."));
         return;
     }
     requested = on;

+ 40 - 0
tests/RemoteInstrumentEditsTests.cpp

@@ -167,6 +167,45 @@ void jsonNesting()
     check (withinNestingLimit ("{\"name\":\"" + std::string (1000, '[') + "\"}"), "string data counted toward nesting");
     check (withinNestingLimit (R"json({"escaped":"\"[[[[\\","x":[0]})json", 2), "escaped quote or slash corrupted nesting count");
     check (! withinNestingLimit (R"json({"escaped":"\\","x":[[0]]})json", 2), "escaped slash hid actual nesting");
+    check (withinNestingLimit (R"json({'name':'"[[[[',"x":[0]})json", 2), "single-quoted string data counted toward nesting");
+    check (withinNestingLimit (R"json({'escaped':'\'[[[[',"x":[0]})json", 2), "escaped single quote corrupted nesting count");
+    for (const auto limit : { 8u, 64u })
+    {
+        const auto deep = std::string (limit, '[') + "0" + std::string (limit, ']');
+        check (! withinNestingLimit ("['\"'," + deep + "]", limit), "single-quoted double quote hid actual nesting");
+        check (! withinNestingLimit ("{\"x\":'\"',\"deep\":" + deep + "}", limit), "mixed-quote object hid actual nesting");
+        check (! withinNestingLimit ("['\\'\"'," + deep + "]", limit), "escaped single quote hid actual nesting");
+    }
+}
+
+void jsonUtf8()
+{
+    using remote_json::withinNestingLimit;
+    for (const auto& valid : { std::string ("\xc2\x80"), std::string ("\xdf\xbf"), std::string ("\xe0\xa0\x80"),
+                              std::string ("\xed\x9f\xbf"), std::string ("\xee\x80\x80"), std::string ("\xef\xbf\xbf"),
+                              std::string ("\xf0\x90\x80\x80"), std::string ("\xf4\x8f\xbf\xbf"),
+                              std::string ("\xe9\x9f\xb3\xe6\xa8\x82\xf0\x9f\x8e\xb5") })
+        check (withinNestingLimit ("{\"text\":\"" + valid + "\",\"array\":[0]}", 2), "canonical Unicode JSON was rejected");
+    for (const auto& invalid : { std::string ("\x80"), std::string ("\xbf"), std::string ("\xc0\x80"), std::string ("\xc1\x9b"),
+                                std::string ("\xc2"), std::string ("\xc2\x7f"), std::string ("\xc3\x20"),
+                                std::string ("\xe0\x9f\xbf"), std::string ("\xe1\x80"), std::string ("\xe1\x80\x7f"),
+                                std::string ("\xed\xa0\x80"), std::string ("\xed\xbf\xbf"),
+                                std::string ("\xf0\x8f\xbf\xbf"), std::string ("\xf0\x90\x80"), std::string ("\xf1\x80\x80\x7f"),
+                                std::string ("\xf4\x90\x80\x80"), std::string ("\xf5\x80\x80\x80"),
+                                std::string ("\xfe"), std::string ("\xff"), std::string (1, '\0') })
+        check (! withinNestingLimit ("{\"text\":\"" + invalid + "\"}"), "noncanonical UTF-8 or raw NUL reached the JSON parser");
+    check (withinNestingLimit (R"({"nul":"\u0000","bracket":"\u005b"})", 1), "escaped Unicode syntax was rejected");
+    for (const auto limit : { 8u, 64u })
+    {
+        // JUCE 8.0.4 decodes these malformed two-byte sequences to recursive
+        // array delimiters; a raw ASCII-only depth scan used to miss all of them.
+        std::string attack = "[";
+        for (unsigned int i = 0; i < limit + 1; ++i) attack += "\xc1\x9b";
+        attack += "0";
+        for (unsigned int i = 0; i < limit + 1; ++i) attack += "\xc1\x9d";
+        attack += "]";
+        check (! withinNestingLimit (attack, limit), "overlong UTF-8 delimiters bypassed the nesting guard");
+    }
 }
 }
 int main()
@@ -175,6 +214,7 @@ int main()
     {
         instrumentEdits();
         jsonNesting();
+        jsonUtf8();
         authentication();
         std::puts ("Remote instrument edits, JSON nesting and authentication tests passed");
         return 0;

+ 89 - 0
tests/RemoteNotesTests.inc

@@ -0,0 +1,89 @@
+// Exercised through the same codec used by pattern.notes / pattern.replace_notes.
+void remoteNotesRoundtrip()
+{
+    auto expressive = fixture().patterns[0].notes[0];
+    expressive.muted = true;
+    expressive.slide = true;
+    expressive.porta = true;
+    expressive.colour = 13;
+    expressive.group = 23;
+    auto inactiveChance = expressive;
+    inactiveChance.chance = 1.0f;
+    inactiveChance.velocityRange = 0.0f;
+    inactiveChance.chanceGroup = 0;
+    inactiveChance.chanceOne = true;
+    auto tiny = expressive;
+    tiny.velocity = std::numeric_limits<float>::denorm_min();
+    tiny.pan = -1.23456788e-20f;
+    tiny.chance = 1.23456788e-12f;
+    tiny.velocityRange = -1.23456788e-12f;
+    for (const auto& note : { expressive, inactiveChance, tiny, Note {} })
+    {
+        const auto value = remote_notes::toValue (note);
+        check (value.getDynamicObject()->getProperties().size() == 19, "Note read omitted an expression field");
+        check (remote_notes::fromValue (value, 1) == note, "Note codec changed native expression values");
+        // Use the socket writer's JSON precision, rather than only testing an in-memory var.
+        const auto wire = json (juce::JSON::toString (value, true).toRawUTF8());
+        check (remote_notes::fromValue (wire, 1) == note, "Note read/replace JSON roundtrip lost expression data");
+    }
+
+    const auto complete = remote_notes::toValue (expressive);
+    for (const auto* field : { "start", "length", "channel", "key", "velocity", "pan", "muted", "finePitch",
+                              "slide", "porta", "release", "modX", "modY", "colour", "group", "chance",
+                              "velocityRange", "chanceGroup", "chanceOne" })
+    {
+        auto missing = complete.clone();
+        missing.getDynamicObject()->removeProperty (field);
+        refuses ([&] { remote_notes::fromValue (missing, 1); });
+    }
+    auto unknown = complete.clone();
+    unknown.getDynamicObject()->setProperty ("futureExpression", 1);
+    refuses ([&] { remote_notes::fromValue (unknown, 1); });
+    refuses ([&] { remote_notes::fromValue (complete, 0); });
+    refuses ([&] { remote_notes::fromValue (juce::Array<juce::var> {}, 1); });
+
+    const auto rejects = [&] (const char* field, const juce::var& value) {
+        auto invalid = complete.clone();
+        invalid.getDynamicObject()->setProperty (field, value);
+        refuses ([&] { remote_notes::fromValue (invalid, 1); });
+    };
+    for (const auto* field : { "chance", "velocityRange" })
+    {
+        rejects (field, "0.5");
+        rejects (field, false);
+        rejects (field, std::numeric_limits<double>::quiet_NaN());
+        rejects (field, std::numeric_limits<double>::infinity());
+        rejects (field, -std::numeric_limits<double>::infinity());
+    }
+    rejects ("chance", -0.001);
+    rejects ("chance", 1.001);
+    rejects ("velocityRange", -1.001);
+    rejects ("velocityRange", 1.001);
+    rejects ("chanceGroup", -1);
+    rejects ("chanceGroup", 1.5);
+    rejects ("chanceGroup", "7");
+    rejects ("chanceGroup", true);
+    rejects ("chanceGroup", (juce::int64) std::numeric_limits<int>::max() + 1);
+    rejects ("chanceOne", 1);
+    rejects ("chanceOne", "true");
+    rejects ("length", 0);
+    rejects ("start", 1000000000);
+    rejects ("channel", 1);
+
+    for (const auto probability : { 0.0, 1.0 })
+        for (const auto range : { -1.0, 1.0 })
+            for (const auto group : { 0, std::numeric_limits<int>::max() })
+                for (const auto one : { false, true })
+                {
+                    auto edge = complete.clone();
+                    auto* object = edge.getDynamicObject();
+                    object->setProperty ("chance", probability);
+                    object->setProperty ("velocityRange", range);
+                    object->setProperty ("chanceGroup", group);
+                    object->setProperty ("chanceOne", one);
+                    const auto parsed = remote_notes::fromValue (edge, 1);
+                    check (parsed.chance == (float) probability && parsed.velocityRange == (float) range
+                           && parsed.chanceGroup == group && parsed.chanceOne == one,
+                           "Note probability/range/group boundary was not retained");
+                }
+}

+ 235 - 18
tests/RemoteProjectControlTests.cpp

@@ -2,6 +2,7 @@
 #include "engine/RemoteJsonPatch.h"
 #include "engine/RemoteFileSecurity.h"
 #include "engine/ProjectFile.h"
+#include "engine/RemoteNotes.h"
 #include "core/SessionIds.h"
 #include "core/ClipLauncher.h"
 #include "core/PluginSubstitutes.h"
@@ -11,6 +12,7 @@
 #include "core/Vfx.h"
 #include <cstdio>
 #include <stdexcept>
+#include <limits>
 
 using namespace lynx;
 namespace
@@ -123,6 +125,8 @@ Song fixture()
     uids::normalize (song);
     return song;
 }
+#include "RemoteNotesTests.inc"
+
 void patchSemantics()
 {
     const auto source = json (R"({"a/b":{"~name":[1,2]},"x":1})");
@@ -330,6 +334,12 @@ void knownNativeStatePolicy()
     refusesWith ([&] {
         remote_document::stage (player, addValue ("/channels/0/pluginState", encoded (video::write (incoming))));
     }, "native media, page or resource locations");
+    auto volumeOnly = videoSettings;
+    volumeOnly.volume = 64;
+    const auto adjustedVideo = remote_document::stage (player, addValue ("/channels/0/pluginState", encoded (video::write (volumeOnly))));
+    check (video::readOrDefault (adjustedVideo.channels[0].pluginState).volume == 64
+           && video::readOrDefault (adjustedVideo.channels[0].pluginState).path == videoSettings.path,
+           "Allowlisted native state edit changed or refused an existing media resource");
     const auto playerDocument = json (ProjectFile::toJsonExact (player).toRawUTF8());
     auto newPlayer = playerDocument["channels"][0].clone();
     newPlayer.getDynamicObject()->removeProperty ("uid");
@@ -415,32 +425,211 @@ void hostedStateClearIsRejectedBeforeCommit()
     };
     auto changed = source;
     changed.channels[0].plugin.state.clear();
-    refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "clear hosted device state");
+    refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
     refusesWith ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/channels/0/plugin/state"}])")); },
-                 "clear hosted device state");
+                 "Hosted plugin state is read-only");
     changed = source;
     changed.mixer[1].effects[0].plugin.state.clear();
-    refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "clear hosted device state");
+    refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "Hosted plugin state is read-only");
     changed = source;
     changed.mixer[1].effects[1].branches[0].chain[0].plugin.state.clear();
-    refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "clear hosted device state");
+    refusesWith ([&] { remote_document::stage (source, replacement (changed, "mixer")); }, "Hosted plugin state is read-only");
     changed = source;
     changed.channels[1].patcher.nodes[0].effect.plugin.state.clear();
-    refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "clear hosted device state");
+    refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
     changed = source;
     changed.channels[1].patcher.nodes[0].busHeads[0].head->plugin.state.clear();
-    refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "clear hosted device state");
+    refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
     check (source.channels[0].plugin.state == saved && source.mixer[1].effects[0].plugin.state == saved,
            "Clear-state rejection changed its input");
 
-    // Ordinary metadata edits and deliberate nonempty state replacement remain supported.
+    // Metadata and typed wrapper routing remain editable without passing a vendor blob to a device.
     const auto renamed = remote_document::stage (source, json (R"([{"op":"replace","path":"/channels/0/name","value":"Renamed"}])"));
     check (renamed.channels[0].name == "Renamed" && renamed.channels[0].plugin.state == saved, "Metadata edit lost hosted state");
     changed = source;
     const auto other = juce::MemoryBlock ("new saved state", 15).toBase64Encoding().toStdString();
     changed.channels[0].plugin.state = other;
-    const auto stateEdit = remote_document::stage (source, replacement (changed, "channels"));
-    check (stateEdit.channels[0].plugin.state == other, "Nonempty hosted state edit was refused or discarded");
+    refusesWith ([&] { remote_document::stage (source, replacement (changed, "channels")); }, "Hosted plugin state is read-only");
+    for (const auto* path : { "/channels/0/plugin/state", "/mixer/1/effects/0/plugin/state",
+                             "/mixer/1/effects/1/branches/0/chain/0/plugin/state",
+                             "/channels/1/patcher/nodes/0/effect/plugin/state",
+                             "/channels/1/patcher/nodes/0/busHeads/0/head/plugin/state" })
+        refusesWith ([&] { remote_document::stage (source, addValue (path, juce::String (other))); }, "Hosted plugin state is read-only");
+
+    auto document = json (ProjectFile::toJsonExact (source).toRawUTF8());
+    auto copy = document["channels"][0].clone();
+    copy.getDynamicObject()->removeProperty ("uid");
+    refusesWith ([&] { remote_document::stage (source, addValue ("/channels/-", copy)); }, "Hosted plugin state is read-only");
+    copy = document["mixer"][1]["effects"][0].clone();
+    refusesWith ([&] { remote_document::stage (source, addValue ("/mixer/2/effects", juce::Array<juce::var> { copy })); },
+                 "Hosted plugin state is read-only");
+    changed = source;
+    changed.channels[0].plugin.state = other;
+    refusesWith ([&] { remote_document::stage (source, addValue ("", json (ProjectFile::toJsonExact (changed).toRawUTF8()))); },
+                 "Hosted plugin state is read-only");
+    auto substitute = source;
+    substitute.mixer[1].effects[0].kind = EffectKind::utility;
+    substitute.mixer[1].effects[0].substituteFor = hosted.plugin;
+    refusesWith ([&] { remote_document::stage (substitute, addValue ("/mixer/1/effects/0/substituteFor/state", juce::String (other))); },
+                 "Hosted plugin state is read-only");
+    auto empty = source;
+    empty.channels[0].plugin.state.clear();
+    refusesWith ([&] { remote_document::stage (empty, addValue ("/channels/0/plugin/state", juce::String (saved))); }, "Hosted plugin state is read-only");
+
+    const auto routed = remote_document::stage (source, addValue ("/channels/0/plugin/outputs", json ("[[1,1]]")));
+    check (routed.channels[0].plugin.outputs.size() == 1 && routed.channels[0].plugin.outputs[0].offset == 1
+           && routed.channels[0].plugin.state == saved, "Allowlisted wrapper output routing changed or refused hosted state");
+    // Stable channel identities permit reordering without treating their saved states as new data.
+    auto reordered = source;
+    std::swap (reordered.channels[0], reordered.channels[1]);
+    const auto moved = remote_document::stage (source, replacement (reordered, "channels"));
+    check (moved.channels[1].plugin.state == saved, "Reordering stable channel identities lost hosted state");
+    auto sameId = source;
+    auto second = sameId.channels[0];
+    second.uid = 0;
+    second.plugin.state.clear();
+    sameId.channels.push_back (second);
+    uids::normalize (sameId);
+    auto swapped = sameId;
+    std::swap (swapped.channels[0], swapped.channels[2]);
+    const auto sameIdMoved = remote_document::stage (sameId, replacement (swapped, "channels"));
+    check (sameIdMoved.channels[0].plugin.state.empty() && sameIdMoved.channels[2].plugin.state == saved,
+           "Reordering same-ID channels confused their stable device states");
+    swapped = sameId;
+    std::swap (swapped.channels[0].plugin.state, swapped.channels[2].plugin.state);
+    refusesWith ([&] { remote_document::stage (sameId, replacement (swapped, "channels")); }, "Hosted plugin state is read-only");
+    check (source.channels[0].plugin.state == saved && source.mixer[1].effects[0].plugin.state == saved,
+           "Hosted-state rejection changed its input");
+}
+
+void documentFieldAllowlist()
+{
+    auto source = fixture();
+    source.info.title = "Original";
+    source.info.url = "https://existing.example/project";
+    source.info.showOnOpen = true;
+    source.info.created = 1234.0;
+    source.info.workSeconds = 42.0;
+    const auto original = remote_document::bytes (source);
+    const auto named = remote_document::stage (source, json (R"([
+        {"op":"replace","path":"/info/title","value":"New title"},
+        {"op":"add","path":"/info/author","value":"Producer"},
+        {"op":"add","path":"/info/genre","value":"Electronic"},
+        {"op":"add","path":"/info/comments","value":"Session notes"},
+        {"op":"add","path":"/channels/0/synthSettings/chorus","value":1},
+        {"op":"replace","path":"/patterns/0/events/0/events/0/1","value":0.5},
+        {"op":"replace","path":"/automations/0/points/0/1","value":0.5}
+    ])"));
+    check (named.info.title == "New title" && named.info.author == "Producer" && named.info.genre == "Electronic"
+           && named.info.comments == "Session notes" && named.info.url == source.info.url
+           && named.info.showOnOpen && named.info.created == source.info.created && named.info.workSeconds == source.info.workSeconds
+           && named.channels[0].synth.chorus == 1 && named.patterns[0].events[0].events[0].value == 0.5f
+           && named.automations[0].points[0].value == 0.5f, "Allowlisted musical or project metadata edit failed");
+    for (const auto* path : { "/info/url", "/info/showOnOpen", "/info/created", "/info/workSeconds" })
+        refusesWith ([&] { remote_document::stage (source, addValue (path, juce::String (path) == "/info/url" ? juce::var ("file:///tmp/program") : juce::var (false))); },
+                     "read-only");
+    refusesWith ([&] { remote_document::stage (source, json (R"([{"op":"remove","path":"/info"}])")); }, "read-only");
+    auto changed = source;
+    changed.info.url = "https://new.example/launch";
+    refusesWith ([&] { remote_document::stage (source, addValue ("/info", json (ProjectFile::toJsonExact (changed).toRawUTF8())["info"])); },
+                 "read-only");
+    refusesWith ([&] { remote_document::stage (source, addValue ("", json (ProjectFile::toJsonExact (changed).toRawUTF8()))); }, "read-only");
+    refusesWith ([&] { remote_document::stage (fixture(), addValue ("/info", json (R"({"title":"Injected","url":"file:///tmp/program","showOnOpen":true})"))); },
+                 "read-only");
+
+    for (const auto* path : { "/futureLoader", "/channels/0/futureLoader", "/channels/0/synthSettings/futureLoader",
+                             "/patterns/0/events/0/futureLoader", "/automations/0/futureLoader", "/mixer/1/futureLoader" })
+        refusesWith ([&] { remote_document::stage (source, addValue (path, "file:///tmp/program")); }, "editable document allowlist");
+    auto document = json (ProjectFile::toJsonExact (source).toRawUTF8());
+    auto channel = document["channels"][0].clone();
+    channel.getDynamicObject()->removeProperty ("uid");
+    channel["synthSettings"].getDynamicObject()->setProperty ("futureLoader", "/tmp/program");
+    refusesWith ([&] { remote_document::stage (source, addValue ("/channels/-", channel)); }, "editable document allowlist");
+    refusesWith ([&] { remote_document::stage (source, addValue ("/patterns/0/notes/0/0", json (R"({"futureLoader":"/tmp/program"})"))); },
+                 "does not allow editable object members");
+    const auto labeled = remote_document::stage (source, addValue ("/channels/0/keyLabels", json (R"({"60":"Middle C","127":"Top"})")));
+    check (labeled.channels[0].keyLabels.at (60) == "Middle C", "MIDI key-label allowlist rejected a valid dictionary");
+    refusesWith ([&] { remote_document::stage (source, addValue ("/channels/0/keyLabels", json (R"({"futureLoader":"/tmp/program"})"))); }, "MIDI keys");
+    check (remote_document::bytes (source) == original, "Allowlist rejection changed its input");
+}
+
+void richDocumentAllowlist()
+{
+    auto source = fixture();
+    VideoTrack existingVideo;
+    existingVideo.name = "Existing picture";
+    existingVideo.clips.push_back ({ "/videos/existing.mp4", 0.0, 0.0, 2.0, 2.0, 99 });
+    source.videoTracks.push_back (existingVideo);
+    auto rich = source;
+    rich.channelGroups = { "Instruments" };
+    rich.channels[0].group = 0;
+    rich.channels[0].keyLabels[60] = "Middle C";
+    rich.channels[0].arp.direction = 1;
+    rich.channels[0].misc.gateBeats = 0.5f;
+    rich.channels[0].sampler.pitch = 3.0f;
+    rich.channels[0].sampler.warp = { { 0.0, 0.0 }, { 1.0, 2.0 } };
+    rich.channels[0].sampler.precompute.normalize = true;
+    ChannelDef layered;
+    layered.instrument = InstrumentKind::layer;
+    layered.layer.children = { 0 };
+    rich.channels.push_back (layered);
+    EffectSlot parallel;
+    parallel.kind = EffectKind::parallel;
+    parallel.branches.resize (1);
+    parallel.branches[0].chain.emplace_back();
+    rich.mixer[1].effects.push_back (parallel);
+    ChannelDef patcher;
+    patcher.instrument = InstrumentKind::patcher;
+    PatchNode node;
+    node.effect.kind = EffectKind::utility;
+    node.label = "Bus processor";
+    node.paramIns = { 0 };
+    node.busHeads.push_back ({ 1, node.effect, 0.5f });
+    patcher.patcher.nodes.push_back (node);
+    rich.channels.push_back (patcher);
+    Modulator modulator;
+    modulator.name = "LFO";
+    modulator.routes.push_back ({ { AutomationTargetKind::mixerPan, 1, 0, 0 }, 0.25f });
+    rich.modulators.push_back (modulator);
+    Vca vca;
+    vca.name = "Band";
+    vca.members = { 1, 2 };
+    rich.vcas.push_back (vca);
+    rich.clipGrid.emplace();
+    rich.clipGrid->scenes.emplace_back();
+    rich.clipGrid->scenes[0].name = "Scene";
+    rich.clipGrid->slots.emplace_back();
+    auto gridClip = source.playlist[0];
+    gridClip.uid = 0;
+    gridClip.start = 0;
+    gridClip.gridSlot = 0;
+    rich.clipGrid->clips.push_back (gridClip);
+    VideoTrack video;
+    video.name = "Picture";
+    video.clips.push_back ({ "/videos/existing.mp4", 0.0, 0.0, 2.0, 2.0, 0 });
+    rich.videoTracks.push_back (video);
+    AdrCue cue;
+    cue.id = "101";
+    cue.out = 2.0;
+    cue.line = "Dialogue";
+    cue.takes.emplace_back();
+    cue.takes[0].clip = source.playlist[0].uid;
+    cue.takes[0].note = "First take";
+    rich.adr.cues.push_back (cue);
+    auto document = json (ProjectFile::toJsonExact (rich).toRawUTF8());
+    const auto accepted = remote_document::stage (source, addValue ("", document));
+    check (accepted.channels.size() == 3 && accepted.channels[0].keyLabels.at (60) == "Middle C"
+           && accepted.channels[0].sampler.warp.size() == 2 && accepted.channels[1].layer.children == layered.layer.children
+           && accepted.channels[2].patcher.nodes[0].busHeads.size() == 1
+           && accepted.mixer[1].effects[0].branches[0].chain.size() == 1 && accepted.modulators.size() == 1
+           && accepted.vcas.size() == 1 && accepted.clipGrid->slots.size() == 1 && accepted.videoTracks.size() == 2
+           && accepted.adr.cues[0].takes[0].note == "First take", "Allowlist discarded a supported rich native object/tuple workflow");
+    for (const auto* path : { "/channels/2/patcher/nodes/0/futureLoader",
+                             "/channels/2/patcher/nodes/0/busHeads/0/head/futureLoader",
+                             "/mixer/1/effects/0/branches/0/chain/0/futureLoader",
+                             "/clipGrid/clips/0/futureLoader", "/video/tracks/0/clips/0/futureLoader",
+                             "/adr/cues/0/takes/0/futureLoader" })
+        refusesWith ([&] { remote_document::stage (accepted, addValue (path, "file:///tmp/program")); }, "editable document allowlist");
 }
 
 void discoveryCleanup()
@@ -467,6 +656,29 @@ void discoveryCleanup()
         remote_files::removeDiscoveryIfOwned (file, "owned");
         check (file.existsAsFile(), "Cleanup removed a malformed discovery record");
     }
+    // JUCE's release parser accepts overlong UTF-8 as recursive array brackets.
+    // The raw-byte gate must reject it before parsing even with a matching token.
+    std::string invalidUtf8 = R"({"token":"owned","deep":)";
+    for (int i = 0; i < 32; ++i) invalidUtf8 += "\xc1\x9b";
+    invalidUtf8 += "0";
+    for (int i = 0; i < 32; ++i) invalidUtf8 += "\xc1\x9d";
+    invalidUtf8 += "}";
+    // Keep malformed bytes outside JUCE strings: release-build conversion itself
+    // can corrupt memory before JSON parsing, so the raw gate must run first.
+    check (! remote_json::withinNestingLimit (invalidUtf8, 8), "Noncanonical UTF-8 passed the pre-conversion gate");
+    {
+        auto output = file.createOutputStream();
+        check (output != nullptr && output->setPosition (0) && output->truncate().wasOk()
+               && output->write (invalidUtf8.data(), invalidUtf8.size()), "Could not write malformed UTF-8 discovery fixture");
+        output->flush();
+    }
+    remote_files::removeDiscoveryIfOwned (file, "owned");
+    check (file.existsAsFile(), "Cleanup parsed a noncanonical UTF-8 discovery record");
+    const juce::String unicodeRecord = juce::String::fromUTF8 ("{\"token\":\"owned\",\"name\":\""
+        "\xe9\x9f\xb3\xe6\xa8\x82\xf0\x9f\x8e\xb5\"}");
+    remote_files::writeDiscovery (file, unicodeRecord);
+    remote_files::removeDiscoveryIfOwned (file, "owned");
+    check (! file.exists(), "Cleanup rejected a canonical Unicode discovery record");
     // An oversized record with a valid prefix must be rejected rather than parsed
     // from a truncated buffer. A record at the byte limit remains valid.
     remote_files::writeDiscovery (file, record + juce::String::repeatedString (" ", 16385 - record.length()));
@@ -479,22 +691,27 @@ void discoveryCleanup()
 }
 int main()
 {
+    const char* activeTest = "initialization";
+    const auto run = [&] (const char* name, auto test) { activeTest = name; test(); };
     try
     {
-        patchSemantics();
-        exactDocuments();
-        transactionValidation();
-        currentModelDocuments();
-        documentIoPolicy();
-        hostedStateClearIsRejectedBeforeCommit();
-        knownNativeStatePolicy();
-        discoveryCleanup();
+        run ("patchSemantics", patchSemantics);
+        run ("exactDocuments", exactDocuments);
+        run ("remoteNotesRoundtrip", remoteNotesRoundtrip);
+        run ("transactionValidation", transactionValidation);
+        run ("currentModelDocuments", currentModelDocuments);
+        run ("documentIoPolicy", documentIoPolicy);
+        run ("hostedStateClearIsRejectedBeforeCommit", hostedStateClearIsRejectedBeforeCommit);
+        run ("documentFieldAllowlist", documentFieldAllowlist);
+        run ("richDocumentAllowlist", richDocumentAllowlist);
+        run ("knownNativeStatePolicy", knownNativeStatePolicy);
+        run ("discoveryCleanup", discoveryCleanup);
         std::puts ("Remote JSON Patch, exact project documents, atomic staging and discovery cleanup tests passed");
         return 0;
     }
     catch (const std::exception& error)
     {
-        std::fprintf (stderr, "%s\n", error.what());
+        std::fprintf (stderr, "%s: %s\n", activeTest, error.what());
         return 1;
     }
 }