Skip to content

armgit / nota

Public Imported from GitHub
0

Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.

(fix) Undo covers device parameters and arrangement sections (#91)

Chris Laupamaeda823097bfa
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 8a72d74a..1790282e 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -22,6 +22,20 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.
## [Unreleased]
+### Fixed
+- **Undo covers device knobs** (nota-daw/nota#30): turning a knob, flipping a switch or
+ typing a value on an effect, a MIDI effect, an instrument or a plug-in is now one undo
+ step, in order with note and clip edits — before, ⌘Z skipped it and undid the edit before.
+ A drag is one step; so is an A/B switch, a MIDI controller movement (ended by a one-second
+ pause), a touch on Nota Remote's macro knobs or XY pad, and each MCP tool call.
+- **Undo covers arrangement sections** (nota-daw/nota#64): creating, renaming, moving,
+ resizing, duplicating and deleting a section are each one undo step. Sections are now
+ stored in the project file; a project saved by an earlier version keeps its sections and
+ moves them into the project file on the next save.
+
+### Added
+- **MCP `list_sections` and `set_sections`**: read and replace the arrangement's sections.
+
## [0.55.1] — 2026-10-15
### Added
diff --git a/FEATURES.md b/FEATURES.md
index f73018dd..6e2d54d0 100644
--- a/FEATURES.md
+++ b/FEATURES.md
@@ -45,10 +45,12 @@ JUCE module; the engine core is JUCE-free.
## Project and transport
- **Project**: create / open / save (`.nota`), autosaves, undo/redo for every editing
- operation — including volume, pan and master-volume moves from any source (Mixer, track
- headers, Session mixer, **MST**, Nota Remote, a MIDI controller, MCP), one step per move;
- a recorded automation pass undoes with its value. Mute, solo and sends are not in the
- history; automation playback, opening a project and freezing add no steps.
+ operation — including volume, pan and master-volume moves and the parameters of effects,
+ MIDI effects, instruments and plug-ins, from any source (device cards, Mixer, track
+ headers, Session mixer, **MST**, Nota Remote, a MIDI controller, MCP), one step per move,
+ and every arrangement section edit; a recorded automation pass undoes with its value.
+ Mute, solo, sends and devices inside racks are not in the history; automation playback,
+ opening a project and freezing add no steps.
- **New project template**: a new project (and the workspace Nota opens with) starts with an
instrument track (Nota Synth), an audio track and two returns — **Reverb** (Nota Reverb)
and **Delay** (Nota Delay), both Wet Only — ready to send to; it opens unmodified, with
@@ -107,7 +109,8 @@ track count and closes with Escape.
(Intro, Verse, Drop). Drag the empty lane to mark one, click it to jump the playhead
there, double-click to rename, drag its body or edges to move and resize it (always on
whole bars). Its menu loops the section, selects it as a time range across every track,
- duplicates it or deletes it. Saved with the project; View ▸ Toggle sections hides it.
+ duplicates it or deletes it. Each edit is one undo step. Saved with the project (MCP
+ `list_sections` / `set_sections`); View ▸ Toggle sections hides it.
- **Resizable tracks and track list** — drag a track's bottom edge (header or lane) to
set its height, 30–256 px, with a light snap to Compact / Standard / Large; a
multi-selection resizes together, ⌥-drag resizes every track, double-click resets.
@@ -1048,7 +1051,8 @@ appears in the UI immediately.
Coverage:
- **Transport**: play/stop, tempo, time signature, loop, metronome.
-- **Project**: `get_overview` (a full snapshot); version history — `list_versions` (with what
+- **Project**: `get_overview` (a full snapshot); the arrangement's sections
+ (`list_sections`, `set_sections`); version history — `list_versions` (with what
each changed), `save_version` with a note, `switch_version`, `annotate_version` (name, note,
star). Deleting versions stays with the user.
- **Tracks**: add and remove, volume/pan/mute/solo, groups, sends.
diff --git a/specs/016-device-param-section-undo/checklists/requirements.md b/specs/016-device-param-section-undo/checklists/requirements.md
new file mode 100644
index 00000000..4a3d0dcd
--- /dev/null
+++ b/specs/016-device-param-section-undo/checklists/requirements.md
@@ -0,0 +1,36 @@
+# Specification Quality Checklist: Undo for Device Parameters and Arrangement Sections
+
+**Purpose**: Validate specification completeness and quality before proceeding to planning
+**Created**: 2026-10-15
+**Feature**: [spec.md](../spec.md)
+
+## Content Quality
+
+- [x] No implementation details (languages, frameworks, APIs)
+- [x] Focused on user value and business needs
+- [x] Written for non-technical stakeholders
+- [x] All mandatory sections completed
+
+## Requirement Completeness
+
+- [x] No [NEEDS CLARIFICATION] markers remain
+- [x] Requirements are testable and unambiguous
+- [x] Success criteria are measurable
+- [x] Success criteria are technology-agnostic (no implementation details)
+- [x] All acceptance scenarios are defined
+- [x] Edge cases are identified
+- [x] Scope is clearly bounded
+- [x] Dependencies and assumptions identified
+
+## Feature Readiness
+
+- [x] All functional requirements have clear acceptance criteria
+- [x] User scenarios cover primary flows
+- [x] Feature meets measurable outcomes defined in Success Criteria
+- [x] No implementation details leak into specification
+
+## Notes
+
+- Resolved 2026-10-15: sections move into the engine's project (not an app-side bridge);
+ gesture grouping follows specs/009; rack-internal devices are a follow-up.
+- MCP tool names appear only as the names users and the AI see.
diff --git a/specs/016-device-param-section-undo/contracts/c-abi.md b/specs/016-device-param-section-undo/contracts/c-abi.md
new file mode 100644
index 00000000..460554e9
--- /dev/null
+++ b/specs/016-device-param-section-undo/contracts/c-abi.md
@@ -0,0 +1,60 @@
+# Contract: C ABI changes (`nota_engine.h`)
+
+## Value gestures (extends specs/009)
+
+```c
+#define NOTA_MIX_TRACK_VOLUME 0
+#define NOTA_MIX_TRACK_PAN 1
+#define NOTA_MIX_MASTER_VOLUME 2
+#define NOTA_MIX_DEVICE_PARAM 3 /* audio effect: device_index = chain position */
+#define NOTA_MIX_MIDI_DEVICE_PARAM 4 /* MIDI effect: device_index = MIDI-FX position */
+#define NOTA_MIX_PLUGIN_PARAM 5 /* normalized: device_index -1 = the instrument */
+
+typedef struct NotaMixTarget {
+ int32_t kind; /* NOTA_MIX_* */
+ int32_t track_id; /* ignored for NOTA_MIX_MASTER_VOLUME; master chain = master id */
+ int32_t device_index; /* parameter kinds only; -1 otherwise */
+ int32_t param_index; /* parameter kinds only; -1 otherwise */
+} NotaMixTarget;
+```
+
+`nota_mix_gesture_begin` / `nota_mix_gesture_end` keep their signatures; a target whose
+device or parameter does not exist is ignored at begin (as a missing track is today).
+
+`nota_engine_begin_automation_write(..., latch = 0)` on a parameter target also opens a
+value gesture for it; the matching `nota_engine_end_automation_write` closes it. A latched
+write does not.
+
+### Guarantees (smoke-tested)
+
+| # | Guarantee |
+|---|---|
+| G1 | begin(param) · n sets · end → one step; undo → exact before, redo → exact after |
+| G2 | begin · end without a change → no step |
+| G3 | an automation-write touch (unlatched) on a parameter is one step; latched is none |
+| G4 | parameter, note and section steps undo in reverse order of their edits |
+| G5 | a step whose device is gone is skipped; the next step is undone |
+| G6 | automation playback of a device parameter adds no step |
+| G7 | a recorded touch: the lane edit and the value undo as one step |
+
+## Sections
+
+```c
+typedef struct NotaSection {
+ double start_beat;
+ double length_beats;
+ const char* name_utf8; /* NULL = "" */
+} NotaSection;
+
+NOTA_API int32_t nota_engine_section_count(const NotaEngine* engine);
+NOTA_API double nota_engine_section_start(const NotaEngine* engine, int32_t index);
+NOTA_API double nota_engine_section_length(const NotaEngine* engine, int32_t index);
+NOTA_API const char* nota_engine_section_name(const NotaEngine* engine, int32_t index);
+/* Replace the list (sorted by start; entries with length <= 0 dropped; start clamped >= 0).
+ * checkpoint 1 = one undo step (user edit; an identical list makes none), 0 = baseline
+ * (project load). Message thread only. */
+NOTA_API NotaResult nota_engine_set_sections(NotaEngine* engine, const NotaSection* sections,
+ int32_t count, int32_t checkpoint);
+```
+
+Out-of-range index → 0 / 0.0 / "". `nota_engine_reset` (project load / new) clears them.
diff --git a/specs/016-device-param-section-undo/data-model.md b/specs/016-device-param-section-undo/data-model.md
new file mode 100644
index 00000000..5e39d7ec
--- /dev/null
+++ b/specs/016-device-param-section-undo/data-model.md
@@ -0,0 +1,42 @@
+# Data Model: Undo for Device Parameters and Arrangement Sections
+
+## Value target (`MixTarget`, engine + managed)
+
+| Field | Type | Meaning |
+|---|---|---|
+| kind | MixKind | TrackVolume 0 · TrackPan 1 · MasterVolume 2 (specs/009) · **DeviceParam 3** · **MidiDeviceParam 4** · **PluginParam 5** |
+| trackId | int32 | track (the master chain's devices use the master track id); ignored for MasterVolume |
+| deviceIndex | int32 | audio-effect chain position (3), MIDI-effect chain position (4), effect position or −1 = the instrument (5); −1 otherwise |
+| paramIndex | int32 | parameter index (3, 4: the device's own range; 5: normalized 0..1); −1 otherwise |
+
+Two targets are the same when all four fields match.
+
+## Value change (`MixChange`)
+
+A target plus `before` / `after` (float, exact). A step holds any number of changes, at most
+one per target. Merge rule (group / recording merge): per target the older `before`, the
+newer `after`; a target whose merged `before == after` is dropped.
+
+## Open gesture
+
+`handle`, the targets with their `before`, `pushCountAtBegin`, `stackSizeAtBegin`
+(specs/009, unchanged). Touch gestures additionally remember their automation-write
+identity `(track, target, device, param, paramId)` so the matching
+`endAutomationWrite` closes them; one open touch per identity.
+
+## Section (`Graph::sections`)
+
+| Field | Type | Rule |
+|---|---|---|
+| startBeat | double | ≥ 0 |
+| lengthBeats | double | > 0 (entries with ≤ 0 are dropped) |
+| name | UTF-8 string | free text |
+
+Kept sorted by `startBeat` (stable). Replaced as a whole; equality is field-wise, so
+re-setting an identical list makes no step.
+
+## Project document
+
+`ProjectDocument.Sections`: `List<SectionDto>?` — `{ "start": double, "length": double,
+"name": string }`. `null` (member absent) = older file → read the legacy `sections.json`
+sidecar once.
diff --git a/specs/016-device-param-section-undo/plan.md b/specs/016-device-param-section-undo/plan.md
new file mode 100644
index 00000000..a0f6b28d
--- /dev/null
+++ b/specs/016-device-param-section-undo/plan.md
@@ -0,0 +1,119 @@
+# Implementation Plan: Undo for Device Parameters and Arrangement Sections
+
+**Branch**: `fix/undo-device-params-sections` | **Date**: 2026-10-15 | **Spec**: [spec.md](spec.md)
+
+**Input**: Feature specification from `/specs/016-device-param-section-undo/spec.md`
+
+## Summary
+
+Device parameters join the value steps specs/009 introduced for volume and pan: three new
+target kinds (audio effect, MIDI effect, normalized plug-in / instrument parameter). The
+engine opens a value gesture from the automation-write touch every on-screen control
+already sends, so all cards are covered by one engine change; MIDI Learn, Nota Remote and
+MCP use the managed gesture helpers. Arrangement sections move into the engine's graph as
+project-level data next to scenes and the pan law: an edit publishes a new graph (a normal
+snapshot step), the project file stores them, and an older project's sidecar is read once.
+See [research.md](research.md).
+
+## Technical Context
+
+**Language/Version**: C++20 (engine), C# / .NET 10 (managed)
+
+**Primary Dependencies**: none new
+
+**Storage**: `project.json` gains `sections` (optional member, no format bump)
+
+**Audio-Thread Impact**: none. Gestures, history and sections are message-thread only;
+the audio thread never reads `Graph::sections`. Undo writes parameters through the same
+setters a hand move uses.
+
+**Testing**: `scripts/build.sh` → smoke test gains `ParamSectionUndoTests` (`--paramundo`)
+
+**Constraints**: exact values; history depth 128 shared
+
+**Scale/Scope**: engine ~250 lines; managed ~250 lines across ~15 files; smoke ~300 lines
+
+## Constitution Check
+
+| Principle | Status |
+|---|---|
+| I. Real-time audio safety | ✅ no audio-thread change |
+| II. Boundary discipline | ✅ C ABI only: extended `NotaMixTarget`, `NotaSection` + 5 functions |
+| III. Licensing hygiene | ✅ new files get the SPDX header; no dependency |
+| IV. Verification gate | ✅ engine behaviour change → smoke test |
+| V. One logical change | ✅ "undo covers device parameters and sections" (#30, #64) |
+| VI. Docs in sync | ⏳ CHANGELOG, FEATURES.md, user docs (EN + RU) |
+| VII. Spec-first | ✅ |
+| VIII. Rules not weakened | ✅ |
+
+## Design
+
+### 1. Engine — parameter value steps
+
+- `Engine.h`: `MixKind` += `DeviceParam = 3, MidiDeviceParam = 4, PluginParam = 5`;
+ `MixTarget` / `MixChange` gain `deviceIndex`, `paramIndex` (default −1, appended so
+ existing aggregate initialisers keep meaning).
+- `Engine.cpp`: `mixValue` / `applyMix` read and write the three kinds through
+ `deviceGetParam/SetParam`, `midiEffectGetParam/SetParam`, `pluginParamGet/Set` after
+ checking the device exists (else "gone"); `mergeMix` matches on all four fields.
+- `Engine_Automation.cpp`: `beginAutomationWrite` (unlatched, parameter target, no touch
+ open for it) → `beginMixGesture` and remember the touch; `endAutomationWrite` → end it.
+ Both before the existing early returns. `clearUndoHistory` drops open touches.
+- Undo comment blocks in `Engine.h` and `nota_engine.h` updated.
+
+### 2. Engine — sections
+
+- `Graph.h`: `struct Section { double startBeat, lengthBeats; std::string name; }`,
+ `std::vector<Section> sections` on `Graph`, copied in `inheritGraphLevel`.
+- `Engine`: `setSections(std::vector<Section>, bool checkpoint)` (normalise, compare, copy
+ the authoring graph, `publish` or `publishRaw`), getters. `reset()` publishes an empty
+ graph, which clears them.
+- C ABI per [contracts/c-abi.md](contracts/c-abi.md) in `nota_engine_core.cpp`.
+
+### 3. Managed
+
+- `EngineContracts.cs`: `MixKind` values, `MixTarget(Kind, TrackId, DeviceIndex = -1,
+ ParamIndex = -1)` + helpers; `SectionInfo` record. `IAudioEngine`: `Sections`,
+ `SetSections(list, checkpoint)`. Interop: `NotaMixTarget` layout, section P/Invokes.
+- Persistence: `ProjectDocument.Sections`, capture / apply, legacy sidecar migration,
+ sidecar removed on save.
+- `ArrangementView.Sections.cs`: working copy committed to the engine per edit,
+ `ReloadSections()` from the engine; the sidecar code goes. `MainWindow`: reload after
+ undo / redo / load / new; Remote reads the same list.
+- Gaps (research R2): `GenericMidiBody`, `ArpGrid`, device shell A/B, `ValueEntry`.
+- MIDI Learn: parameter targets use `MixMovement` like volume / pan. Remote: macro and XY
+ touches use the per-touch gesture. MCP: `Mutate` in an undo group; single-param tools via
+ `MixEdit.Step`; `list_sections` / `set_sections`.
+
+### 4. Smoke test + docs
+
+`tests/Nota.SmokeTest/ParamSectionUndoTests.cs` covering every contract guarantee and the
+spec's FR-010 list; `Program.cs` full run + `--paramundo`. CHANGELOG, FEATURES.md, user
+docs.
+
+## Project Structure
+
+```text
+specs/016-device-param-section-undo/ spec, plan, research, data-model, contracts/, quickstart, tasks
+src/native/nota.engine/include/nota/nota_engine.h
+src/native/nota.engine/src/{Graph.h, Engine.h, Engine.cpp, Engine_Automation.cpp, nota_engine_core.cpp}
+src/managed/Nota.Application/Engine/{EngineContracts.cs, IAudioEngine.cs}
+src/managed/Nota.Infrastructure/Interop/{NativeMethods.cs, NotaEngine.cs}
+src/managed/Nota.Infrastructure/Persistence/{ProjectModel.cs, ProjectService.cs}
+src/managed/Nota.App/{ArrangementView.Sections.cs, MainWindow.*.cs, MidiLearnService.cs, DeviceChainView.Shell.cs, Controls/ArpGrid.cs, Controls/ValueEntry.cs, DeviceCards/Midi/GenericMidiBody.cs}
+src/managed/Nota.Remote/{RemoteParams.cs, RemoteHub.Apply.cs}
+src/managed/Nota.Mcp/{EngineTools.cs, Tools/*}
+tests/Nota.SmokeTest/{ParamSectionUndoTests.cs (new), Program.cs}
+```
+
+## Out of Scope / Known Gaps
+
+- Devices inside racks and drum-kit pads, rack macros dragged on the rack's macro strip
+ slider, rack chain levels (no automation target today).
+- Bypass, sidechain routing, device presets.
+- A structural edit made by another source during an open gesture merges into it
+ (specs/009, unchanged).
+
+## Complexity Tracking
+
+No constitution violations.
diff --git a/specs/016-device-param-section-undo/quickstart.md b/specs/016-device-param-section-undo/quickstart.md
new file mode 100644
index 00000000..430ba68d
--- /dev/null
+++ b/specs/016-device-param-section-undo/quickstart.md
@@ -0,0 +1,21 @@
+# Quickstart: verify undo for device parameters and sections
+
+## Automated
+
+```bash
+CI=true dotnet run --project tests/Nota.SmokeTest -c Release -- --paramundo
+```
+
+## By hand
+
+1. New project → instrument track with Nota Bass. Draw a few notes, then open Devices and
+ drag Cutoff from 400 Hz to 300 Hz. ⌘Z → Cutoff is 400 Hz again (the notes stay). ⌘Z again
+ → the last note edit is undone. ⌘⇧Z twice → both come back (#30).
+2. On an effect, double-click a knob (reset), flip a switch, type a value into a read-out:
+ each is one ⌘Z.
+3. View ▸ Toggle sections. Drag out a section, rename it, drag its right edge, move it,
+ duplicate it, delete one. ⌘Z repeatedly → each edit comes off in reverse order; ⌘⇧Z
+ replays them (#64).
+4. Save, close, reopen → sections are there, and no ⌘Z removes them.
+5. Open a project saved by v0.55.1 with sections → they appear; save → the bundle no longer
+ holds `sections.json`.
diff --git a/specs/016-device-param-section-undo/research.md b/specs/016-device-param-section-undo/research.md
new file mode 100644
index 00000000..8225a5ee
--- /dev/null
+++ b/specs/016-device-param-section-undo/research.md
@@ -0,0 +1,76 @@
+# Research: Undo for Device Parameters and Arrangement Sections
+
+## R1 — Device parameters ride on the specs/009 value steps
+
+**Decision**: extend the existing mix gesture (`MixKind` / `MixTarget` / `MixChange` in
+`Engine.h`) with three parameter kinds — audio-effect parameter, MIDI-effect parameter,
+normalized plug-in / instrument parameter — addressed by `(track, device index, parameter
+index)`. Undo/redo, the group merge, the automation-recording merge, the "skip a step
+whose target is gone" rule and the depth limit all apply unchanged.
+
+**Why**: device parameters, like volume and pan, live outside the graph snapshot — a
+cloned track *shares* its `Device` objects (`Engine::cloneTrack`), so restoring an older
+graph never restores a parameter. A value step is the only model that fits, and specs/009
+already built it with the exact gesture semantics the spec asks for.
+
+**Alternatives**: a second, parameter-only undo stack (rejected: two histories can't keep
+order, which is bug #30 itself); snapshotting the device's whole state per edit (rejected:
+heavy, and hosted plug-ins' state blobs are large).
+
+**Device index stability**: a step addresses its device by chain position. Every structural
+edit that moves or removes a device is itself a step above the parameter step, so by the
+time a parameter step is undone the chain is back in the layout it was recorded in (the
+same argument specs/009 makes for track ids). A target that is out of range is skipped.
+
+## R2 — Gestures come from the existing automation "touch"
+
+**Decision**: `Engine::beginAutomationWrite` / `endAutomationWrite` — which every on-screen
+parameter control already calls on press and release (88 call sites: knobs, sliders, curve
+handles, graphs, and the one-shot `Begin; set; End` helpers of switches and menus) — also
+open / close a value gesture for that parameter. Latched writes (hardware controls: MIDI
+Learn, Nota Remote) do not; those sources use the managed `MixMovement` / per-touch
+gestures of specs/009 instead. Volume / pan touches are skipped (specs/009 wires those).
+
+**Why**: one change in the engine covers every card, including those added later, with no
+per-card wiring. The touch already means "the user is moving this control".
+
+**Alternatives**: wire a gesture next to each of the 88 call sites (rejected: churn, and
+every future card must remember it); record a step on every setter call without a gesture
+(rejected: preset and project loads and internal sets go through the same setters and
+would flood the history — FR-006).
+
+**Gaps found and closed**: `GenericMidiBody` knobs and `ArpGrid` steps set MIDI-effect
+parameters without a touch; the device shell's A/B switch restores every parameter with
+plain sets; `ValueEntry` solved a typed value by trial sets *before* opening its gesture,
+which would have recorded a solver value as the "before". Each gets a gesture.
+
+## R3 — Sections become graph-level project data
+
+**Decision**: `Graph::sections` (start beat, length in beats, name), copied by
+`inheritGraphLevel` like scenes and the pan law. `setSections(list, checkpoint)` publishes a
+new graph — with a checkpoint for a user edit, without one for a load — so a section edit
+is an ordinary structural snapshot step. The C ABI reads the list and replaces it whole.
+
+**Why**: sections are a few dozen bytes; one source of truth; they are saved with the
+project, visible to MCP and Nota Remote through the engine; undo needs no new machinery.
+
+**Alternatives**: an opaque app-state marker on the engine's undo stack (rejected by the
+user: two models to keep in step; sections stay invisible to MCP / Remote).
+
+**View**: the Sections lane keeps a working copy for drawing and drags; it commits the
+whole list to the engine once per edit (drag release, rename, add, duplicate, delete,
+delete all) and reloads from the engine after undo / redo / load / new.
+
+## R4 — Persistence and migration
+
+**Decision**: `project.json` gains `sections: [{ start, length, name }]` (always written,
+`[]` when empty). On load, a document without the member (an older build's) reads the
+bundle's `sections.json` sidecar once; saving removes the sidecar. No format-version bump:
+the member is optional and older builds keep unknown members on re-save
+(`[JsonExtensionData]`).
+
+## R5 — MCP: one call, one step
+
+**Decision**: every MCP mutation runs inside an engine undo group, so a tool that sets
+several parameters (or adds a device and sets its parameters) is one step; the single-value
+parameter tools use `MixEdit.Step`. New tools `list_sections` / `set_sections`.
diff --git a/specs/016-device-param-section-undo/spec.md b/specs/016-device-param-section-undo/spec.md
new file mode 100644
index 00000000..3539cb98
--- /dev/null
+++ b/specs/016-device-param-section-undo/spec.md
@@ -0,0 +1,264 @@
+# Feature Specification: Undo for Device Parameters and Arrangement Sections
+
+**Feature Branch**: `fix/undo-device-params-sections`
+
+**Created**: 2026-10-15
+
+**Status**: Draft
+
+## Clarifications
+
+### Session 2026-10-15
+
+- Q: Where should arrangement sections live so they can be undone — in the engine's project
+ (one source of truth, saved in the project, visible to MCP / Nota Remote) or stay in the
+ app with a bridge into the undo history? → A: Move them into the engine's project. The
+ sections sidecar file of older projects is read once on load.
+- Q: How is a continuous change grouped? → A: As for volume and pan (specs/009): a mouse drag
+ from press to release is one step; a one-off change (a switch, a menu choice, a reset, a
+ typed value) is one step; a MIDI-controller movement ends after a 1 s pause; one Nota
+ Remote touch is one step; one MCP call is one step.
+- Q: Devices nested inside racks and drum-kit pads? → A: Out of scope for this change: their
+ parameters have no automation target and no gesture today. They follow on the same
+ mechanism.
+
+**Input**: User description: "Undo for device knobs and sections (nota-daw/nota#30,
+nota-daw/nota#64). Ctrl+Z inside a device does nothing for a knob change and instead undoes
+the last note edit (#30, reproduced with Nota Bass's cutoff). Creating, renaming, moving,
+resizing or deleting an arrangement section can't be undone either (#64). Make every
+user change of a device parameter one undo step in the one history, in order with all other
+edits, and move the sections into the engine's project so their edits are undo steps too."
+
+## Nota Context *(fill in — drives plan and tasks)*
+
+**Feature area** *(pick the main one)*:
+
+- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table
+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation
+- [ ] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md`
+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed
+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`
+- [ ] Docs only
+
+**Nota docs to keep in mind** *(links relative to `specs/<slug>/`)*:
+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),
+[`CONTRIBUTING.md`](../../CONTRIBUTING.md), [`BUILD.md`](../../BUILD.md),
+[`FEATURES.md`](../../FEATURES.md), specs/009 (the volume / pan undo this builds on).
+
+**Current state (for reference)**:
+
+- One history (⌘Z / ⌘⇧Z, Edit menu, command palette, Nota Remote, MCP `undo`) covers
+ structural edits and — since specs/009 — volume, pan and master-volume gestures. It does
+ **not** cover device parameters: the engine's undo comment says so, and a knob change
+ leaves the history untouched, so ⌘Z undoes whatever structural edit came before it (#30).
+- Device parameters are changed from device cards (knobs, sliders, curve and graph
+ handles, switches, step grids — built-in effects, built-in instruments, MIDI effects,
+ hosted plug-ins), MIDI Learn, Nota Remote (macros, XY pad), and MCP tools
+ (`set_device_param`, `set_instrument_param`, `set_plugin_param`, `set_midi_fx_param`
+ and the device-specific tools). Every on-screen drag already reports its press and release
+ to the engine (the automation-write "touch").
+- Arrangement sections (named spans in the Sections lane) live only in the arrangement view
+ and are saved to a `sections.json` file next to the project; the engine and its history
+ never see them (#64). A failed sidecar write is silently ignored.
+
+## User Scenarios & Testing *(mandatory)*
+
+### User Story 1 - Take back a knob move (Priority: P1)
+
+A producer turns Nota Bass's cutoff from 400 Hz to 300 Hz, doesn't like it and presses
+⌘Z: the cutoff is back at exactly 400 Hz. ⌘⇧Z brings 300 Hz back. The same works for a
+reverb's decay, an arpeggiator's rate, a plug-in's knob, a double-click reset and a
+switch.
+
+**Why this priority**: the reported bug (#30); the basic expectation of any DAW.
+
+**Independent Test**: on an instrument and an effect, drag a knob, double-click-reset one,
+flip a switch; undo and redo each.
+
+**Acceptance Scenarios**:
+
+1. **Given** a built-in instrument's knob at a value, **When** the user drags it in one
+ press and release and presses ⌘Z, **Then** it is back at exactly the starting value and
+ ⌘⇧Z returns the dragged value.
+2. **Given** an effect, a MIDI effect or a hosted plug-in, **When** the user changes one of
+ its parameters from its card, **Then** that change is one undo step.
+3. **Given** a double-click reset, a switch, a menu choice or a step toggle, **When** it
+ is done, **Then** it is one undo step.
+4. **Given** a drag that ends where it started, **Then** no step is added.
+
+---
+
+### User Story 2 - One history, in order (Priority: P1)
+
+The producer edits a note, turns a filter knob, then presses ⌘Z: the knob comes back
+first, then the note — never the note first (#30).
+
+**Why this priority**: undo that skips edits or jumps out of order is worse than none.
+
+**Independent Test**: alternate note edits, knob moves, section edits and volume moves;
+undo and redo the whole chain.
+
+**Acceptance Scenarios**:
+
+1. **Given** a mixed sequence of structural, volume/pan, device-parameter and section
+ edits, **When** the user undoes repeatedly, **Then** each step reverts exactly the most
+ recent remaining edit, and redo replays them in order.
+2. **Given** an undone parameter change, **When** the user looks at the device card,
+ **Then** it shows the restored value.
+3. **Given** a device deleted after its parameter was changed, **When** the user undoes
+ the delete and then the change, **Then** both come back correctly.
+4. **Given** automation recording, **When** the user moves a knob in one gesture, **Then**
+ the recorded lane and the value undo together as one step.
+
+---
+
+### User Story 3 - Take back a section edit (Priority: P1)
+
+The producer drags out a new section, renames it "Chorus", stretches it by four bars, then
+deletes another by mistake. ⌘Z brings the deleted section back, then shrinks "Chorus" to
+its old length, then gives it its old name, then removes it — one step each.
+
+**Why this priority**: the reported bug (#64).
+
+**Independent Test**: create, rename, move, resize, duplicate, delete and delete-all; undo
+and redo each.
+
+**Acceptance Scenarios**:
+
+1. **Given** each section edit (create, rename, move, resize, duplicate, delete, delete
+ all), **When** it is done and the user presses ⌘Z, **Then** the lane shows the sections
+ exactly as before that edit, and ⌘⇧Z redoes it.
+2. **Given** a move or resize drag, **Then** the whole drag is one step; a click that only
+ moves the playhead is no step.
+3. **Given** a project with sections, **When** it is saved and reopened, **Then** the
+ sections are there, and the history starts empty.
+4. **Given** a project saved by an older build (sections in the sidecar file), **When** it
+ is opened, **Then** its sections appear; after the next save they are stored in the
+ project itself.
+5. **Given** sections, **When** the user opens a new project, **Then** there are none.
+
+---
+
+### User Story 4 - Every source of a parameter change is undoable (Priority: P2)
+
+A parameter moved from a MIDI controller, from Nota Remote (macro or XY pad) or by the AI
+assistant (MCP) can be taken back with ⌘Z.
+
+**Why this priority**: consistency across sources; on-screen editing (US1) carries most of
+the value.
+
+**Independent Test**: change a parameter once from each source and undo each.
+
+**Acceptance Scenarios**:
+
+1. **Given** a MIDI controller knob mapped to a parameter, **When** the user turns it and
+ stops, **Then** the movement up to a 1 s pause is one step.
+2. **Given** a Nota Remote macro knob or XY pad, **When** a finger moves it and lifts,
+ **Then** the touch is one step.
+3. **Given** an MCP call that sets one or several parameters, **When** it completes,
+ **Then** it is one step.
+4. **Given** the MCP tools, **When** the AI reads sections, **Then** it gets the same list
+ the lane shows, and it can replace them in one undoable step.
+
+---
+
+### User Story 5 - Things that are not edits stay out (Priority: P1)
+
+Automation playback moves knobs by itself; a project load, a preset load, a new project and
+a freeze set parameters internally. None of that fills the history.
+
+**Acceptance Scenarios**:
+
+1. **Given** device-parameter automation in read mode, **When** the song plays, **Then** no
+ undo steps appear.
+2. **Given** a project load or a new project, **When** the user presses ⌘Z, **Then** no
+ parameter or section step is undone and the loaded sections stay. (A new project has
+ nothing to undo; a load's own track-building steps predate this feature and are out of
+ scope.)
+
+### Edge Cases
+
+- **Undo during playback** with automation in read mode on that parameter: the automation
+ keeps winning, as for a hand move today.
+- **A step whose device or track no longer exists** (deleted, not undone): skipped quietly;
+ the next step is undone instead.
+- **A gesture interrupted** (focus lost, device removed mid-drag): the change so far is one
+ step; nothing is left half-open.
+- **Two parameters in one gesture** (a curve handle moving frequency and gain; an A/B
+ switch restoring every parameter): one step.
+- **Card refresh**: knobs follow the restored value on the next UI tick, including when
+ the card is closed and reopened.
+- **History depth**: parameter and section steps count against the existing limit.
+
+## Requirements *(mandatory)*
+
+### Functional Requirements
+
+- **FR-001**: Every user change of a parameter of a track's instrument, audio effect, MIDI
+ effect or hosted plug-in (track or master chain) MUST be undoable and redoable through
+ the existing history.
+- **FR-002**: Every user edit of the arrangement sections — create, rename, move, resize,
+ duplicate, delete, delete all — MUST be undoable and redoable through the same history.
+- **FR-003**: Parameter and section steps MUST share one ordered history with all other
+ undoable edits.
+- **FR-004**: One gesture MUST be exactly one step, grouped as in the Clarifications.
+- **FR-005**: A step MUST restore the exact previous value(s) and redo the exact new ones; a
+ gesture that ends where it started MUST NOT add a step.
+- **FR-006**: Automation playback, project load, a new project, preset loads and other
+ internal settings MUST NOT create steps; automation recording MUST undo together with the
+ value it recorded.
+- **FR-007**: A parameter step whose device or track no longer exists MUST be skipped
+ without error.
+- **FR-008**: Sections MUST be part of the project held by the engine and saved inside the
+ project file. A project from an older build MUST open with its sections (read once from
+ the sidecar file); a project load MUST leave no section step behind.
+- **FR-009**: MCP MUST be able to list sections and to replace them in one undoable step;
+ Nota Remote keeps showing the same sections as the lane.
+- **FR-010**: The automated smoke test MUST cover: a knob gesture (begin, values, end) on an
+ effect, a built-in instrument and a MIDI effect is one exact step; a no-change gesture
+ adds none; parameter, note and section steps interleave in order; automation playback adds
+ none; recording merges; a step for a removed device is skipped; MIDI-controller and MCP
+ sources are one step each; section create / rename / move / delete undo and redo; sections
+ survive save → load, and a legacy sidecar is migrated.
+- **FR-011**: The change MUST be listed in the changelog, FEATURES.md and the user docs
+ (EN + RU) where undo is described.
+
+### Key Entities
+
+- **Value step**: an undo step holding before/after values for one or more targets —
+ volume, pan, master volume (specs/009) and now device parameters, addressed by track,
+ device kind (instrument, audio effect, MIDI effect, hosted plug-in) and parameter.
+- **Section**: a named span of arrangement time (start, length, name), held in the
+ project next to the tempo map, scenes and pan law.
+
+## Success Criteria *(mandatory)*
+
+### Measurable Outcomes
+
+- **SC-001**: 100 % of device-parameter changes made from the listed sources can be undone
+ and redone, landing on the exact previous value.
+- **SC-002**: 100 % of section edits can be undone and redone.
+- **SC-003**: A mixed sequence of 50 structural, mix, parameter and section edits undoes and
+ redoes in exactly the reverse / forward order.
+- **SC-004**: Playing a song with device-parameter automation for 10 minutes adds 0 steps.
+- **SC-005**: Every project saved with sections by an earlier build opens with the same
+ sections.
+
+## Assumptions
+
+- Undo steps have no labels (Nota's history has none).
+- Devices inside racks and drum-kit pads, rack macros and rack chain levels are out of
+ scope (clarified); so are bypass, sidechain routing and device presets (a preset load is
+ not an undo step today and stays so).
+- Section colours follow their position, as today; there is no recolour edit.
+- MCP calls run one at a time on the UI thread; each call is one step.
+
+## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*
+
+- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)
+- [x] No new dependency
+- [x] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), immutable snapshots for structural edits (AR-5) — sections are graph-level data the audio thread never reads
+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7)
+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`
+- [x] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned, FEATURES.md and user docs via the nota-features / nota-docs skills
+- [x] UI change → no new UI; the Sections lane keeps its look
diff --git a/specs/016-device-param-section-undo/tasks.md b/specs/016-device-param-section-undo/tasks.md
new file mode 100644
index 00000000..7445ab01
--- /dev/null
+++ b/specs/016-device-param-section-undo/tasks.md
@@ -0,0 +1,60 @@
+---
+
+description: "Task list for 016 Undo for Device Parameters and Arrangement Sections"
+---
+
+# Tasks: Undo for Device Parameters and Arrangement Sections
+
+**Input**: Design documents from `/specs/016-device-param-section-undo/`
+
+**Prerequisites**: [plan.md](plan.md), [spec.md](spec.md), [research.md](research.md),
+[data-model.md](data-model.md), [contracts/c-abi.md](contracts/c-abi.md), [quickstart.md](quickstart.md)
+
+**Tests**: requested (FR-010, constitution IV) in one new file,
+`tests/Nota.SmokeTest/ParamSectionUndoTests.cs`.
+
+## Format: `[ID] [P?] [Story] Description`
+
+---
+
+## Phase 1: Setup
+
+- [x] T001 Build the untouched tree (engine + managed + smoke, `CI=true`) and confirm green
+
+## Phase 2: Foundational
+
+- [x] T002 `Engine.h`: `MixKind` += DeviceParam 3 / MidiDeviceParam 4 / PluginParam 5; `MixTarget`, `MixChange` += `deviceIndex`, `paramIndex` (default −1, appended); update the undo comment
+- [x] T003 `Engine.cpp`: `mixValue` / `applyMix` for the three kinds with existence checks; `mergeMix` matches all four fields
+- [x] T004 `nota_engine.h` / `nota_engine_core.cpp`: `NOTA_MIX_*` 3–5, `NotaMixTarget.device_index/param_index`, copy them in `nota_mix_gesture_begin`; undo comment
+- [x] T005 [P] Managed: `MixKind`, `MixTarget(Kind, TrackId, DeviceIndex = -1, ParamIndex = -1)` + `DeviceParam/MidiDeviceParam/PluginParam` helpers in `EngineContracts.cs`
+- [x] T006 Create `tests/Nota.SmokeTest/ParamSectionUndoTests.cs` + `Program.cs` wiring (full run + `--paramundo`)
+
+## Phase 3: US1 + US2 — knob undo, one history (P1) 🎯
+
+- [x] T007 [US1] `Engine_Automation.cpp`: unlatched `beginAutomationWrite` on a parameter target opens a touch gesture, `endAutomationWrite` closes it; `clearUndoHistory` drops touches
+- [x] T008 [P] [US1] `GenericMidiBody` knobs and `ArpGrid` edits send the touch
+- [x] T009 [P] [US1] `DeviceChainView.Shell` A/B restore: one multi-target gesture
+- [x] T010 [P] [US1] `ValueEntry`: restore the start value before opening the gesture
+- [x] T011 [US1/US2] Smoke: G1–G7 on an effect, a built-in instrument and a MIDI effect; interleave with note edits
+
+## Phase 4: US3 — sections (P1)
+
+- [x] T012 [US3] `Graph.h`: `Section`, `Graph::sections`, `inheritGraphLevel`
+- [x] T013 [US3] `Engine`: `setSections` / getters; C ABI per contract
+- [x] T014 [P] [US3] Managed: `SectionInfo`, `IAudioEngine.Sections` / `SetSections`, P/Invokes
+- [x] T015 [US3] Persistence: `ProjectDocument.Sections`, capture, apply (checkpoint 0), legacy sidecar read when absent, sidecar removed on save
+- [x] T016 [US3] `ArrangementView.Sections.cs`: commit per edit, `ReloadSections()`, drop sidecar code; duplicate / delete-all as one commit
+- [x] T017 [US3] `MainWindow`: reload sections after undo / redo / load / new; drop sidecar calls
+- [x] T018 [US3] Smoke: create / rename / move / delete undo + redo, interleaved with notes; save → load; legacy sidecar migrated; load / reset leave no step
+
+## Phase 5: US4 — other sources (P2)
+
+- [x] T019 [P] [US4] `MidiLearnService`: parameter targets through `MixTouch`
+- [x] T020 [P] [US4] Remote: macro and XY touches through the per-touch gesture
+- [x] T021 [US4] MCP: `Mutate` in an undo group; single-param tools via `MixEdit.Step`; `list_sections` / `set_sections`
+- [x] T022 [US4] Smoke: MIDI movement (simulated clock) and MCP tools are one step each; MCP sections round-trip
+
+## Phase 6: Polish
+
+- [x] T023 [P] CHANGELOG `[Unreleased]`, FEATURES.md (nota-features), user docs EN + RU (nota-docs)
+- [x] T024 Full build + smoke (`CI=true`) green; re-check the compliance list
diff --git a/src/managed/Nota.App/ArrangementView.Sections.cs b/src/managed/Nota.App/ArrangementView.Sections.cs
index 1739962b..9b9b3a98 100644
--- a/src/managed/Nota.App/ArrangementView.Sections.cs
+++ b/src/managed/Nota.App/ArrangementView.Sections.cs
@@ -4,8 +4,9 @@
// Arrangement · Sections — the song-structure lane between the Overview and the ruler
// (design 1a, "structure first"). A bar of numbers says nothing about a song; a row of named
// spans — Intro, Verse, Drop — says where you are. Sections are authoring metadata, not
-// audio: they live in the view and ride in the bundle as a sidecar, so a project written by
-// an older build still opens and simply has none.
+// audio, but they belong to the project (specs/016): the engine holds them next to scenes,
+// so every edit is one undo step and project.json stores them. The view keeps a working
+// copy that a drag reshapes live and commits to the engine on release.
using System;
using System.Collections.Generic;
@@ -18,6 +19,7 @@ using Avalonia.Input;
using Avalonia.Layout;
using Avalonia.Media;
using Avalonia.Threading;
+using Nota.Application;
namespace Nota.App;
@@ -74,33 +76,33 @@ public sealed partial class ArrangementView
// ---- model ------------------------------------------------------------
- /// <summary>The sections, in start order (what the bundle sidecar persists).</summary>
+ /// <summary>The sections, in start order.</summary>
public IReadOnlyList<ArrangementSection> SectionList
{
get { _sections.Sort((a, b) => a.StartBeat.CompareTo(b.StartBeat)); return _sections; }
}
- /// <summary>Replace the whole list (project load).</summary>
- public void SetSections(IEnumerable<ArrangementSection> sections)
+ /// <summary>Re-read the sections from the engine (load, new, undo / redo, an MCP edit).
+ /// Skipped while a drag is reshaping the working copy.</summary>
+ public void ReloadSections()
{
+ if (_engine is not { } eng || _sectionsLane.IsDragging) return;
_sections.Clear();
- foreach (var s in sections)
- if (s.LengthBeats > 0) _sections.Add(new ArrangementSection { StartBeat = Math.Max(0, s.StartBeat), LengthBeats = s.LengthBeats, Name = s.Name });
- _sections.Sort((a, b) => a.StartBeat.CompareTo(b.StartBeat));
- _sectionsLane.InvalidateVisual();
- }
-
- /// <summary>Drop every section (File ▸ New).</summary>
- public void ClearSections()
- {
- if (_sections.Count == 0) return;
- _sections.Clear();
+ foreach (var s in eng.Sections)
+ _sections.Add(new ArrangementSection { StartBeat = s.StartBeat, LengthBeats = s.LengthBeats, Name = s.Name });
_sectionsLane.InvalidateVisual();
}
+ // Commit the working copy as one edit: one undo step, none if nothing changed. The
+ // engine normalises the list (sorted, empty spans dropped), so read it back.
private void SectionsEdited()
{
_sections.Sort((a, b) => a.StartBeat.CompareTo(b.StartBeat));
+ if (_engine is { } eng)
+ {
+ eng.SetSections(_sections.Select(s => new SectionInfo(s.StartBeat, s.LengthBeats, s.Name)).ToList());
+ ReloadSections();
+ }
_sectionsLane.InvalidateVisual();
SectionsChanged?.Invoke();
}
@@ -125,16 +127,21 @@ public sealed partial class ArrangementView
Name = NextSectionName(),
};
_sections.Add(s);
- SectionsEdited();
return s;
}
private void RemoveSection(ArrangementSection s)
{
- if (!_sections.Remove(s)) return;
+ if (Live(s) is not { } live || !_sections.Remove(live)) return;
SectionsEdited();
}
+ // A reload (undo, an MCP edit) replaces the working copy, so a menu or rename flyout
+ // opened before it may hold a stale span: find the one it still means.
+ private ArrangementSection? Live(ArrangementSection s)
+ => _sections.Contains(s) ? s
+ : _sections.FirstOrDefault(x => x.StartBeat == s.StartBeat && x.LengthBeats == s.LengthBeats && x.Name == s.Name);
+
// Snap a section edge to whole bars — song structure is bar-aligned, always, so this
// ignores the clip snap grid (which is often finer than a bar).
private double SnapBar(double beat)
@@ -149,7 +156,11 @@ public sealed partial class ArrangementView
var flyout = new Flyout { Content = box, Placement = PlacementMode.Bottom };
box.KeyDown += (_, ke) =>
{
- if (ke.Key == Key.Enter) { s.Name = box.Text ?? ""; SectionsEdited(); flyout.Hide(); ke.Handled = true; }
+ if (ke.Key == Key.Enter)
+ {
+ if (Live(s) is { } live) { live.Name = box.Text ?? ""; SectionsEdited(); }
+ flyout.Hide(); ke.Handled = true;
+ }
else if (ke.Key == Key.Escape) { flyout.Hide(); ke.Handled = true; }
};
flyout.ShowAt(anchor);
@@ -186,6 +197,9 @@ public sealed partial class ArrangementView
private double _pressBeat, _grabOffset, _fixedBeat;
private bool _moved;
+ /// <summary>A span is being drawn, moved or resized: the working copy is ahead of the engine.</summary>
+ public bool IsDragging => _mode != Mode.None;
+
public SectionsControl(ArrangementView o)
{
_o = o;
@@ -293,6 +307,7 @@ public sealed partial class ArrangementView
double a = _o.SnapBar(Math.Min(_pressBeat, _draftEnd));
double b = _o.SnapBar(Math.Max(_pressBeat, _draftEnd));
_o.AddSection(a, Math.Max(_o._beatsPerBar, b - a));
+ _o.SectionsEdited();
}
else _o.SeekTo(_o.SnapBar(_pressBeat)); // a plain click on empty lane scrubs
InvalidateVisual();
@@ -327,9 +342,10 @@ public sealed partial class ArrangementView
var dup = new MenuItem { Header = "Duplicate", Icon = MenuKit.Icon(GlyphKind.Duplicate) };
dup.Click += (_, _) =>
{
+ if (_o.Live(s) is null) return;
var copy = _o.AddSection(s.StartBeat + s.LengthBeats, s.LengthBeats);
copy.Name = s.Name;
- _o.SectionsEdited();
+ _o.SectionsEdited(); // one step: the copy arrives already named
};
var del = new MenuItem { Header = "Delete", Icon = MenuKit.Icon(GlyphKind.Trash) };
del.Click += (_, _) => _o.RemoveSection(s);
@@ -343,12 +359,12 @@ public sealed partial class ArrangementView
else
{
var add = new MenuItem { Header = "Add section here", Icon = MenuKit.Icon(GlyphKind.Plus) };
- add.Click += (_, _) => _o.AddSection(_o.SnapBar(beat), _o._beatsPerBar * 8);
+ add.Click += (_, _) => { _o.AddSection(_o.SnapBar(beat), _o._beatsPerBar * 8); _o.SectionsEdited(); };
flyout.Items.Add(add);
if (_o._sections.Count > 0)
{
var clear = new MenuItem { Header = "Delete all sections", Icon = MenuKit.Icon(GlyphKind.Trash) };
- clear.Click += (_, _) => { _o.ClearSections(); _o.SectionsChangedRaise(); };
+ clear.Click += (_, _) => { _o._sections.Clear(); _o.SectionsEdited(); };
flyout.Items.Add(clear);
}
}
@@ -407,8 +423,6 @@ public sealed partial class ArrangementView
// ---- commands the lane's menu reaches ---------------------------------
- internal void SectionsChangedRaise() => SectionsChanged?.Invoke();
-
/// <summary>Make a section's span the arrangement's time selection, across every row —
/// so Delete / Duplicate / Consolidate act on the whole section.</summary>
internal void SelectSectionRange(ArrangementSection s)
@@ -416,44 +430,4 @@ public sealed partial class ArrangementView
if (_tracks.Count == 0) return;
SetTimeSelection(s.StartBeat, s.StartBeat + s.LengthBeats, 0, _tracks.Count - 1);
}
-
- // ---- sidecar persistence ---------------------------------------------
-
- private const string SectionsSidecar = "sections.json";
-
- private sealed class SectionDto
- {
- public double Start { get; set; }
- public double Length { get; set; }
- public string Name { get; set; } = "";
- }
-
- /// <summary>Write the sections into a .nota bundle. Cosmetic metadata — a failure here
- /// must never fail the save.</summary>
- public void SaveSections(string bundleDir)
- {
- var path = System.IO.Path.Combine(bundleDir, SectionsSidecar);
- try
- {
- if (_sections.Count == 0) { if (System.IO.File.Exists(path)) System.IO.File.Delete(path); return; }
- var dto = SectionList.Select(s => new SectionDto { Start = s.StartBeat, Length = s.LengthBeats, Name = s.Name }).ToList();
- System.IO.File.WriteAllText(path, System.Text.Json.JsonSerializer.Serialize(dto));
- }
- catch { /* sections are cosmetic — never block a save */ }
- }
-
- /// <summary>Read the sections back out of a bundle (absent / corrupt → none).</summary>
- public void LoadSections(string bundleDir)
- {
- ClearSections();
- var path = System.IO.Path.Combine(bundleDir, SectionsSidecar);
- if (!System.IO.File.Exists(path)) return;
- try
- {
- var dto = System.Text.Json.JsonSerializer.Deserialize<List<SectionDto>>(System.IO.File.ReadAllText(path));
- if (dto is null) return;
- SetSections(dto.Select(d => new ArrangementSection { StartBeat = d.Start, LengthBeats = d.Length, Name = d.Name }));
- }
- catch { /* a corrupt sidecar just means no sections */ }
- }
}
diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.cs
index d935076c..c24aa458 100644
--- a/src/managed/Nota.App/ArrangementView.cs
+++ b/src/managed/Nota.App/ArrangementView.cs
@@ -787,6 +787,7 @@ public sealed partial class ArrangementView : UserControl
foreach (var c in t.Clips)
if (!c.IsMidi && c.Peaks is not null) oldClips[(t.Id, c.ClipIndex)] = c;
}
+ if (rebuildHeaders) ReloadSections(); // sections live in the engine's project (specs/016)
_tracks.Clear();
_returns.Clear();
if (_engine is { } eng)
diff --git a/src/managed/Nota.App/Controls/ArpGrid.cs b/src/managed/Nota.App/Controls/ArpGrid.cs
index 4a80cd7d..6be9994b 100644
--- a/src/managed/Nota.App/Controls/ArpGrid.cs
+++ b/src/managed/Nota.App/Controls/ArpGrid.cs
@@ -21,6 +21,7 @@ using Avalonia.Controls;
using Avalonia.Input;
using Avalonia.Media;
using Nota.Application;
+using Nota.Application.Editing;
namespace Nota.App;
@@ -177,10 +178,14 @@ internal sealed class ArpGrid : Control
if (!Mini && p.Y > w.Bottom)
{
int s = Math.Clamp((int)((p.X - w.X) / w.Width * n), 0, n - 1);
- _e.MidiEffectSetParam(_t, _mi, LOn + s, G(LOn + s) > 0.5 ? 0f : 1f);
+ MixEdit.Step(_e, () => _e.MidiEffectSetParam(_t, _mi, LOn + s, G(LOn + s) > 0.5 ? 0f : 1f),
+ MixTarget.MidiDeviceParam(_t, _mi, LOn + s)); // one undo step (specs/016)
e.Handled = true; InvalidateVisual(); Edited?.Invoke(); return;
}
_dragStep = StepAt(p.X); _dragDisp = DispAt(p.Y);
+ // A drag (Alt draws a line across steps) is one undo step over the lane's steps.
+ var lane = Lanes[_lane];
+ _dragGesture = _e.BeginMixGesture(Enumerable.Range(0, n).Select(i => MixTarget.MidiDeviceParam(_t, _mi, lane.Base + i)).ToArray());
Apply(_dragStep, _dragDisp);
e.Pointer.Capture(this); e.Handled = true;
}
@@ -195,10 +200,13 @@ internal sealed class ArpGrid : Control
}
else Apply(s, d);
}
- protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_dragStep >= 0) { _dragStep = -1; InvalidateVisual(); e.Pointer.Capture(null); } }
+ protected override void OnPointerReleased(PointerReleasedEventArgs e) { if (_dragStep >= 0) { _dragStep = -1; EndDragGesture(); InvalidateVisual(); e.Pointer.Capture(null); } }
// Capture taken away mid-drag (the window deactivates): end the drag.
- protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) { if (_dragStep >= 0) { _dragStep = -1; InvalidateVisual(); } base.OnPointerCaptureLost(e); }
+ protected override void OnPointerCaptureLost(PointerCaptureLostEventArgs e) { if (_dragStep >= 0) { _dragStep = -1; EndDragGesture(); InvalidateVisual(); } base.OnPointerCaptureLost(e); }
+
+ private int _dragGesture;
+ private void EndDragGesture() { if (_dragGesture != 0) { _e.EndMixGesture(_dragGesture); _dragGesture = 0; } }
private int StepAt(double x) { var w = Well(); int n = StepCount; return Math.Clamp((int)((x - w.X) / w.Width * n), 0, n - 1); }
private double DispAt(double y)
diff --git a/src/managed/Nota.App/Controls/ValueEntry.cs b/src/managed/Nota.App/Controls/ValueEntry.cs
index f5e81042..c920cb50 100644
--- a/src/managed/Nota.App/Controls/ValueEntry.cs
+++ b/src/managed/Nota.App/Controls/ValueEntry.cs
@@ -48,6 +48,7 @@ internal static partial class ValueEntry
{
double from = norm();
double? to = Solve(typed, text(), n => { setNorm(n); return text(); });
+ setNorm(from); // the probes moved it: the gesture must open on the old value (undo, specs/016)
begin?.Invoke();
setNorm(to ?? from);
end?.Invoke();
diff --git a/src/managed/Nota.App/DeviceCards/Midi/GenericMidiBody.cs b/src/managed/Nota.App/DeviceCards/Midi/GenericMidiBody.cs
index 40d1a4b8..f5641682 100644
--- a/src/managed/Nota.App/DeviceCards/Midi/GenericMidiBody.cs
+++ b/src/managed/Nota.App/DeviceCards/Midi/GenericMidiBody.cs
@@ -9,6 +9,7 @@ using System.Globalization;
using Avalonia;
using Avalonia.Controls;
using Avalonia.Layout;
+using Nota.Application;
using static Nota.App.DeviceCardKit;
namespace Nota.App;
@@ -37,6 +38,9 @@ internal sealed class GenericMidiBody : IMidiDeviceBody
var bar = new Knob((v - min) / Math.Max(1e-6f, max - min), 1.0) { Accent = true, HorizontalAlignment = HorizontalAlignment.Center,
Default = (engine.MidiEffectParamDefault(track, index, pi) - min) / Math.Max(1e-6f, max - min) };
bar.ValueChanged += nv => { float nvv = (float)(min + nv * (max - min)); engine.MidiEffectSetParam(track, index, pi, nvv); value.Text = FmtParam(nvv, integral); };
+ // The touch makes a drag one undo step and lets automation record it (specs/016).
+ bar.GestureBegin += () => engine.BeginAutomationWrite(track, AutomationTarget.MidiDeviceParam, index, pi, "");
+ bar.GestureEnd += () => engine.EndAutomationWrite(track, AutomationTarget.MidiDeviceParam, index, pi, "");
MidiLearn.Bind(bar, MidiTarget.MidiDeviceParam(track, index, pi), engine.MidiEffectParamName(track, index, pi));
panel.Children.Add(new StackPanel { Spacing = 2, Children = { top, bar } });
}
diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.cs
index bdb33ee0..8bcc8a54 100644
--- a/src/managed/Nota.App/DeviceChainView.Shell.cs
+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs
@@ -89,7 +89,13 @@ public sealed partial class DeviceChainView
{
int n = Math.Min(p.Length, ParamCount(k, di));
int view = k == ChainKind.Instrument ? Nota.Application.InstrumentView.Index(_engine, _trackId) : -1; // A/B keeps the card size
- for (int i = 0; i < n; i++) if (i != view) SetPr(k, di, i, p[i]);
+ // One undo step for the whole switch (specs/016).
+ var targets = new List<MixTarget>(n);
+ for (int i = 0; i < n; i++)
+ if (i != view)
+ targets.Add(k == ChainKind.Instrument ? MixTarget.PluginParam(_trackId, -1, i)
+ : k == ChainKind.Midi ? MixTarget.MidiDeviceParam(_trackId, di, i) : MixTarget.DeviceParam(_trackId, di, i));
+ Nota.Application.Editing.MixEdit.Step(_engine, () => { for (int i = 0; i < n; i++) if (i != view) SetPr(k, di, i, p[i]); }, targets.ToArray());
}
internal readonly record struct ShellSpec(
diff --git a/src/managed/Nota.App/MainWindow.Files.cs b/src/managed/Nota.App/MainWindow.Files.cs
index 4d75b7f1..d91e6285 100644
--- a/src/managed/Nota.App/MainWindow.Files.cs
+++ b/src/managed/Nota.App/MainWindow.Files.cs
@@ -184,7 +184,6 @@ public partial class MainWindow
_panLawLegacy = false; // new projects use the Stereo pan law (set by the template)
_projectPath = null;
_learn?.Clear(); // start with a clean MIDI-map for the new project
- Timeline.ClearSections(); // …and a clean song structure
Timeline.ResetTrackView(); // …at the default track sizes
Nota.Infrastructure.ProjectTemplate.ApplyDefault(Engine); // instrument, audio, Reverb + Delay returns
RefreshAfterLoad();
@@ -249,7 +248,6 @@ public partial class MainWindow
_projectPath = dir;
_learn?.LoadMappings(dir); // MIDI-learn mappings ride in the bundle sidecar
_modular?.LoadLayout(dir); // modular-editor node/island positions (sidecar)
- Timeline.LoadSections(dir); // arrangement song sections (sidecar)
Timeline.LoadTrackView(dir); // track heights + track-list width (sidecar)
LoadFreezeLinks(dir); // live-freeze links (v1.1) — re-sleep linked sources
RecordRecentProject(dir); // surface it on the welcome screen next launch
@@ -318,7 +316,6 @@ public partial class MainWindow
var warnings = _projects.Save(Engine, TransportSnapshot(), dir);
_learn?.SaveMappings(dir); // MIDI-learn mappings ride in the bundle sidecar
_modular?.SaveLayout(dir); // modular-editor node/island positions (sidecar)
- Timeline.SaveSections(dir); // arrangement song sections (sidecar)
Timeline.SaveTrackView(dir); // track heights + track-list width (sidecar)
SaveFreezeLinks(dir); // live-freeze links (v1.1) ride in the bundle sidecar
_analysis.AdoptInto(dir); // analysis cached while unsaved moves into the bundle
diff --git a/src/managed/Nota.App/MidiLearnService.cs b/src/managed/Nota.App/MidiLearnService.cs
index aa545200..3233be3d 100644
--- a/src/managed/Nota.App/MidiLearnService.cs
+++ b/src/managed/Nota.App/MidiLearnService.cs
@@ -27,8 +27,8 @@ public sealed class MidiLearnService
private const float RackGainMax = 2.0f; // rack out / chain gain travel (matches the rack faders)
private readonly IAudioEngine _engine;
- // One undo step per controller movement on a mapped volume / pan target, ended by a 1 s
- // pause (specs/009); the pause is checked on every Tick.
+ // One undo step per controller movement on a mapped volume / pan / parameter target, ended by a 1 s
+ // pause (specs/009, specs/016); the pause is checked on every Tick.
private static readonly TimeSpan MixPause = TimeSpan.FromSeconds(1);
private readonly Dictionary<MixTarget, MixMovement> _mixUndo = new();
private void MixTouch(MixTarget target, Action set)
@@ -340,24 +340,28 @@ public sealed class MidiLearnService
switch (t.Kind)
{
+ // Device parameters, volume and pan: one undo step per movement, ended by a 1 s
+ // pause (specs/009, specs/016).
case MidiTargetKind.DeviceParam:
{
float min = _engine.DeviceParamMin(t.TrackId, t.DeviceIndex, t.ParamIndex);
float max = _engine.DeviceParamMax(t.TrackId, t.DeviceIndex, t.ParamIndex);
- _engine.DeviceSetParam(t.TrackId, t.DeviceIndex, t.ParamIndex, (float)(min + outv * (max - min)));
+ MixTouch(MixTarget.DeviceParam(t.TrackId, t.DeviceIndex, t.ParamIndex),
+ () => _engine.DeviceSetParam(t.TrackId, t.DeviceIndex, t.ParamIndex, (float)(min + outv * (max - min))));
break;
}
case MidiTargetKind.PluginParam:
- _engine.PluginParamSet(t.TrackId, t.DeviceIndex, t.ParamIndex, (float)outv);
+ MixTouch(MixTarget.PluginParam(t.TrackId, t.DeviceIndex, t.ParamIndex),
+ () => _engine.PluginParamSet(t.TrackId, t.DeviceIndex, t.ParamIndex, (float)outv));
break;
case MidiTargetKind.MidiDeviceParam:
{
float min = _engine.MidiEffectParamMin(t.TrackId, t.DeviceIndex, t.ParamIndex);
float max = _engine.MidiEffectParamMax(t.TrackId, t.DeviceIndex, t.ParamIndex);
- _engine.MidiEffectSetParam(t.TrackId, t.DeviceIndex, t.ParamIndex, (float)(min + outv * (max - min)));
+ MixTouch(MixTarget.MidiDeviceParam(t.TrackId, t.DeviceIndex, t.ParamIndex),
+ () => _engine.MidiEffectSetParam(t.TrackId, t.DeviceIndex, t.ParamIndex, (float)(min + outv * (max - min))));
break;
}
- // Volume / pan: one undo step per movement, ended by a 1 s pause (specs/009).
case MidiTargetKind.TrackVolume:
MixTouch(MixTarget.Volume(t.TrackId), () => _engine.SetTrackVolume(t.TrackId, (float)(outv * VolumeMax)));
break;
diff --git a/src/managed/Nota.Application/Editing/MixEdit.cs b/src/managed/Nota.Application/Editing/MixEdit.cs
index da268957..78ca1f27 100644
--- a/src/managed/Nota.Application/Editing/MixEdit.cs
+++ b/src/managed/Nota.Application/Editing/MixEdit.cs
@@ -8,6 +8,7 @@
// freeze, the template, automation) keep using the plain setters and never make steps.
using System;
+using System.Collections.Generic;
namespace Nota.Application.Editing;
@@ -16,10 +17,32 @@ public static class MixEdit
/// <summary>Runs <paramref name="set"/> as one undo step over <paramref name="targets"/>.</summary>
public static void Step(IAudioEngine engine, Action set, params MixTarget[] targets)
{
- int handle = engine.BeginMixGesture(targets);
- try { set(); }
- finally { engine.EndMixGesture(handle); }
+ if (targets.Length <= MaxGestureTargets)
+ {
+ int handle = engine.BeginMixGesture(targets);
+ try { set(); }
+ finally { engine.EndMixGesture(handle); }
+ return;
+ }
+ // More targets than one gesture holds (a plug-in's whole parameter set, specs/016):
+ // several gestures inside an undo group still undo as one step.
+ engine.BeginUndoGroup();
+ var handles = new List<int>();
+ try
+ {
+ for (int i = 0; i < targets.Length; i += MaxGestureTargets)
+ handles.Add(engine.BeginMixGesture(targets[i..Math.Min(targets.Length, i + MaxGestureTargets)]));
+ set();
+ }
+ finally
+ {
+ foreach (int h in handles) engine.EndMixGesture(h);
+ engine.EndUndoGroup();
+ }
}
+
+ /// <summary>The most targets one engine gesture takes (<c>nota_mix_gesture_begin</c>).</summary>
+ public const int MaxGestureTargets = 64;
}
/// <summary>A gesture held by one control or source: <see cref="Begin"/> on press,
diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.cs
index ee10611c..1e2e26e8 100644
--- a/src/managed/Nota.Application/Engine/EngineContracts.cs
+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs
@@ -258,19 +258,32 @@ public struct StereoMeasure
public readonly bool Silent => LevelDb < -60f;
}
-/// <summary>What a mix gesture targets (specs/009). Matches NOTA_MIX_*.</summary>
-public enum MixKind { TrackVolume = 0, TrackPan = 1, MasterVolume = 2 }
-
-/// <summary>One parameter a mix gesture records for undo; laid out like native NotaMixTarget.
-/// <see cref="TrackId"/> is ignored for the master volume.</summary>
+/// <summary>What a value gesture targets (specs/009 volume / pan, specs/016 device
+/// parameters). Matches NOTA_MIX_*.</summary>
+public enum MixKind { TrackVolume = 0, TrackPan = 1, MasterVolume = 2, DeviceParam = 3, MidiDeviceParam = 4, PluginParam = 5 }
+
+/// <summary>One value a gesture records for undo; laid out like native NotaMixTarget.
+/// <see cref="TrackId"/> is ignored for the master volume; <see cref="DeviceIndex"/> /
+/// <see cref="ParamIndex"/> address a device parameter (−1 otherwise; a plugin parameter's
+/// device −1 is the track's instrument).</summary>
[StructLayout(LayoutKind.Sequential)]
-public readonly record struct MixTarget(MixKind Kind, int TrackId)
+public readonly record struct MixTarget(MixKind Kind, int TrackId, int DeviceIndex = -1, int ParamIndex = -1)
{
public static MixTarget Volume(int trackId) => new(MixKind.TrackVolume, trackId);
public static MixTarget Pan(int trackId) => new(MixKind.TrackPan, trackId);
public static MixTarget Master => new(MixKind.MasterVolume, -1);
+ /// <summary>A built-in audio effect's parameter (its own min..max range).</summary>
+ public static MixTarget DeviceParam(int trackId, int deviceIndex, int paramIndex) => new(MixKind.DeviceParam, trackId, deviceIndex, paramIndex);
+ /// <summary>A MIDI effect's parameter.</summary>
+ public static MixTarget MidiDeviceParam(int trackId, int index, int paramIndex) => new(MixKind.MidiDeviceParam, trackId, index, paramIndex);
+ /// <summary>A normalized plugin / built-in instrument parameter (device −1 = the instrument).</summary>
+ public static MixTarget PluginParam(int trackId, int deviceIndex, int paramIndex) => new(MixKind.PluginParam, trackId, deviceIndex, paramIndex);
}
+/// <summary>A named span of arrangement time — Intro / Verse / Drop (specs/016). Project
+/// data held by the engine: undoable, saved with the project.</summary>
+public readonly record struct SectionInfo(double StartBeat, double LengthBeats, string Name);
+
/// <summary>MIDI clip envelope target (M9 follow-up). Velocity scales note velocities;
/// Volume scales the instrument output during the clip.</summary>
diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.cs
index 8776d462..47e92c08 100644
--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs
+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs
@@ -833,9 +833,16 @@ public interface IAudioEngine : IDisposable
/// step (project load, the new-project baseline). No-op if unchanged.</summary>
void SetPanLaw(PanLaw law, bool checkpoint = true);
- // --- Mix undo (specs/009) --------------------------------------------
- /// <summary>Starts a gesture on volume / pan / master volume: their values now are what
- /// undo returns to. Returns a handle (0 = no valid target).</summary>
+ // --- Arrangement sections (specs/016) -------------------------------
+ /// <summary>The project's sections, sorted by start.</summary>
+ IReadOnlyList<SectionInfo> Sections { get; }
+ /// <summary>Replaces the sections (sorted; zero-length dropped). <paramref name="checkpoint"/>
+ /// = one undo step (an identical list makes none); false = baseline (project load).</summary>
+ void SetSections(IReadOnlyList<SectionInfo> sections, bool checkpoint = true);
+
+ // --- Value undo (specs/009, specs/016) -------------------------------
+ /// <summary>Starts a gesture on volume / pan / master volume / device parameters: their
+ /// values now are what undo returns to. Returns a handle (0 = no valid target).</summary>
int BeginMixGesture(params MixTarget[] targets);
/// <summary>Ends the gesture: one undo step for whatever it changed (none → no step).</summary>
void EndMixGesture(int handle);
diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
index fe89a5d3..61b65d7f 100644
--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs
@@ -186,6 +186,24 @@ internal static partial class NativeMethods
[LibraryImport(Lib, EntryPoint = "nota_engine_pan_law")]
internal static partial int PanLaw(IntPtr engine);
+ [StructLayout(LayoutKind.Sequential)]
+ internal readonly record struct NotaSection(double StartBeat, double LengthBeats, IntPtr Name);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_section_count")]
+ internal static partial int SectionCount(IntPtr engine);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_section_start")]
+ internal static partial double SectionStart(IntPtr engine, int index);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_section_length")]
+ internal static partial double SectionLength(IntPtr engine, int index);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_section_name")]
+ internal static partial IntPtr SectionName(IntPtr engine, int index);
+
+ [LibraryImport(Lib, EntryPoint = "nota_engine_set_sections")]
+ internal static partial NotaResult SetSections(IntPtr engine, [In] NotaSection[] sections, int count, int checkpoint);
+
[LibraryImport(Lib, EntryPoint = "nota_mix_gesture_begin")]
internal static partial int MixGestureBegin(IntPtr engine, [In] MixTarget[] targets, int count);
diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
index 5426ef04..18a9c8de 100644
--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs
@@ -163,7 +163,38 @@ public sealed partial class NotaEngine : IAudioEngine
public void SetPanLaw(PanLaw law, bool checkpoint = true)
{ ThrowIfDisposed(); Check(NativeMethods.SetPanLaw(_handle, (int)law, checkpoint ? 1 : 0)); }
- // --- Mix undo (specs/009) --------------------------------------------------
+ // --- Arrangement sections (specs/016) ---------------------------------------
+ public IReadOnlyList<SectionInfo> Sections
+ {
+ get
+ {
+ ThrowIfDisposed();
+ int n = NativeMethods.SectionCount(_handle);
+ var list = new SectionInfo[n];
+ for (int i = 0; i < n; i++)
+ list[i] = new SectionInfo(NativeMethods.SectionStart(_handle, i), NativeMethods.SectionLength(_handle, i),
+ Marshal.PtrToStringUTF8(NativeMethods.SectionName(_handle, i)) ?? "");
+ return list;
+ }
+ }
+ public void SetSections(IReadOnlyList<SectionInfo> sections, bool checkpoint = true)
+ {
+ ThrowIfDisposed();
+ var rows = new NativeMethods.NotaSection[sections.Count];
+ try
+ {
+ for (int i = 0; i < rows.Length; i++)
+ rows[i] = new NativeMethods.NotaSection(sections[i].StartBeat, sections[i].LengthBeats,
+ Marshal.StringToCoTaskMemUTF8(sections[i].Name ?? ""));
+ Check(NativeMethods.SetSections(_handle, rows, rows.Length, checkpoint ? 1 : 0));
+ }
+ finally
+ {
+ foreach (var r in rows) if (r.Name != IntPtr.Zero) Marshal.FreeCoTaskMem(r.Name);
+ }
+ }
+
+ // --- Value undo (specs/009, specs/016) -------------------------------------
public int BeginMixGesture(params MixTarget[] targets)
{ ThrowIfDisposed(); return targets.Length == 0 ? 0 : NativeMethods.MixGestureBegin(_handle, targets, targets.Length); }
public void EndMixGesture(int handle) { ThrowIfDisposed(); if (handle > 0) NativeMethods.MixGestureEnd(_handle, handle); }
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
index af1577fb..ddabe010 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectModel.cs
@@ -35,6 +35,10 @@ public sealed class ProjectDocument
/// <summary>Mixer-wide settings: the project pan law (format v21). Null = a pre-v21 project
/// (migration fills it in) = Balance + older project.</summary>
public MixerDto? Mixer { get; set; }
+ /// <summary>Arrangement sections (specs/016), sorted by start. Null in files from before
+ /// sections moved into the project: their bundle's <c>sections.json</c> sidecar is read
+ /// once on load instead.</summary>
+ public List<SectionDto>? Sections { get; set; }
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
@@ -74,6 +78,17 @@ public sealed class MixerDto
[JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
}
+/// <summary>A named span of arrangement time (specs/016). The same shape the legacy
+/// <c>sections.json</c> sidecar used.</summary>
+public sealed class SectionDto
+{
+ public double Start { get; set; }
+ public double Length { get; set; }
+ public string Name { get; set; } = "";
+
+ [JsonExtensionData] public Dictionary<string, JsonElement>? Extra { get; set; }
+}
+
public sealed class TransportDto
{
public double Bpm { get; set; } = 120.0;
diff --git a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
index 571f7d16..bec11f28 100644
--- a/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/ProjectService.cs
@@ -18,6 +18,7 @@ using System.Collections.Generic;
using System.IO;
using System.Text.Json;
using System.Text.Json.Nodes;
+using Nota.Application;
namespace Nota.Infrastructure;
@@ -73,6 +74,8 @@ public sealed class ProjectService
PanLaw = engine.PanLaw == PanLaw.Stereo ? "stereo" : "balance",
PanLawLegacy = transport.PanLawLegacy,
},
+ // Always written ([] when none), so a load can tell "no sections" from "older file".
+ Sections = engine.Sections.Select(s => new SectionDto { Start = s.StartBeat, Length = s.LengthBeats, Name = s.Name }).ToList(),
};
int trackCount = engine.TrackCount;
@@ -444,6 +447,11 @@ public sealed class ProjectService
// is a pre-v21 project: Balance, so the mix sounds as it was saved.
engine.SetPanLaw(ParsePanLaw(doc.Mixer?.PanLaw, warnings), checkpoint: false);
+ // Arrangement sections (specs/016), also a baseline. A file from before they moved into
+ // the project keeps them in the bundle's sidecar.
+ var sections = doc.Sections ?? ReadLegacySections(bundleDir);
+ engine.SetSections(sections.Select(d => new SectionInfo(d.Start, d.Length, d.Name ?? "")).ToList(), checkpoint: false);
+
// Restore the scene count before tracks so their session slots size to it (the doc may
// hold more/fewer scenes than the fresh default after add/remove-scene edits).
while (engine.SceneCount < doc.SceneCount) engine.AddScene();
@@ -854,6 +862,20 @@ public sealed class ProjectService
// Only now that the new manifest is in place: nothing on disk points at these any more.
BundleContent.PruneUnreferenced(bundleDir, doc);
+ // The sections now live in the manifest; a leftover sidecar would only mislead an older build.
+ try { File.Delete(Path.Combine(bundleDir, LegacySectionsSidecar)); } catch (IOException) { } catch (UnauthorizedAccessException) { }
+ }
+
+ /// <summary>Where builds before specs/016 kept the arrangement sections, next to the manifest.</summary>
+ public const string LegacySectionsSidecar = "sections.json";
+
+ // Sections of a project saved before they moved into the manifest (absent / corrupt → none).
+ private static List<SectionDto> ReadLegacySections(string bundleDir)
+ {
+ string path = Path.Combine(bundleDir, LegacySectionsSidecar);
+ if (!File.Exists(path)) return new();
+ try { return JsonSerializer.Deserialize<List<SectionDto>>(File.ReadAllText(path)) ?? new(); }
+ catch (Exception e) when (e is JsonException or IOException or UnauthorizedAccessException) { return new(); }
}
/// <summary>Serializes just the manifest JSON (same options Save uses). Used by
diff --git a/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs b/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs
index a0a70621..7f222e13 100644
--- a/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs
+++ b/src/managed/Nota.Infrastructure/Persistence/VersionDiff.cs
@@ -107,10 +107,19 @@ internal static class VersionDiff
NewAudio = newAudio,
Other = changedFiles
.Select(f => OtherNames.TryGetValue(f, out var label) ? label : Path.GetFileNameWithoutExtension(f))
+ .Concat(SectionsDiffer(before, after) ? ["sections"] : [])
.Distinct().ToList(),
};
}
+ // Arrangement sections live in the manifest since specs/016 (before that, in the
+ // sections.json sidecar above). A version without the member has none.
+ private static bool SectionsDiffer(JsonNode? before, JsonNode? after)
+ {
+ static JsonNode? Of(JsonNode? doc) => doc?["sections"] is JsonArray { Count: > 0 } a ? a : null;
+ return !JsonNode.DeepEquals(Of(before), Of(after));
+ }
+
private static List<JsonObject> Tracks(JsonNode? manifest)
=> (manifest?["tracks"] as JsonArray)?.OfType<JsonObject>().ToList() ?? new();
diff --git a/src/managed/Nota.Mcp/EngineTools.cs b/src/managed/Nota.Mcp/EngineTools.cs
index d65c4dc6..baa21ca1 100644
--- a/src/managed/Nota.Mcp/EngineTools.cs
+++ b/src/managed/Nota.Mcp/EngineTools.cs
@@ -4,9 +4,12 @@
// Base for every MCP tool group: holds the shared engine + dispatch + refresh, and gives two
// helpers so a tool body stays one line — Read (query on the UI thread) and Mutate (edit on the
// UI thread, then refresh the UI). Exceptions are turned into a readable string rather than
-// thrown across the transport.
+// thrown across the transport. A Mutate is one undo group, so a tool call undoes as one step
+// whatever it changed (specs/016); parameter writes go through DevParam / MidiParam /
+// PlugParam so a plain value change lands in that step too.
using Nota.Application;
+using Nota.Application.Editing;
namespace Nota.Mcp;
@@ -20,10 +23,37 @@ public abstract class EngineTools(IAudioEngine engine, IEngineDispatch dispatch,
protected Task<T> Read<T>(Func<T> func) => _d.InvokeAsync(func);
/// <summary>Run an edit on the UI thread, then refresh the arrangement/device panel.</summary>
- protected Task Mutate(Action action) => _d.InvokeAsync(() => { action(); _r.Refresh(); });
+ protected Task Mutate(Action action) => _d.InvokeAsync(() =>
+ {
+ E.BeginUndoGroup();
+ try { action(); }
+ finally { E.EndUndoGroup(); }
+ _r.Refresh();
+ });
/// <summary>Run an edit that returns a value on the UI thread, then refresh.</summary>
- protected Task<T> Mutate<T>(Func<T> func) => _d.InvokeAsync(() => { var v = func(); _r.Refresh(); return v; });
+ protected Task<T> Mutate<T>(Func<T> func) => _d.InvokeAsync(() =>
+ {
+ T v;
+ E.BeginUndoGroup();
+ try { v = func(); }
+ finally { E.EndUndoGroup(); }
+ _r.Refresh();
+ return v;
+ });
+
+ /// <summary>Set a built-in audio effect's parameter as an undoable value change.</summary>
+ protected void DevParam(int trackId, int deviceIndex, int paramIndex, float value)
+ => MixEdit.Step(E, () => E.DeviceSetParam(trackId, deviceIndex, paramIndex, value), MixTarget.DeviceParam(trackId, deviceIndex, paramIndex));
+
+ /// <summary>Set a MIDI effect's parameter as an undoable value change.</summary>
+ protected void MidiParam(int trackId, int index, int paramIndex, float value)
+ => MixEdit.Step(E, () => E.MidiEffectSetParam(trackId, index, paramIndex, value), MixTarget.MidiDeviceParam(trackId, index, paramIndex));
+
+ /// <summary>Set a normalized plug-in / instrument parameter (deviceIndex -1 = the instrument)
+ /// as an undoable value change.</summary>
+ protected void PlugParam(int trackId, int deviceIndex, int paramIndex, float value)
+ => MixEdit.Step(E, () => E.PluginParamSet(trackId, deviceIndex, paramIndex, value), MixTarget.PluginParam(trackId, deviceIndex, paramIndex));
/// <summary>Resolve a track id to its enumeration index (0..TrackCount-1), or -1. UI thread.</summary>
protected int IndexOfTrack(int trackId)
diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
index d257c823..4eb8744b 100644
--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs
+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs
@@ -62,7 +62,7 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I
});
[McpServerTool(Name = "set_device_param"), Description("Set a device parameter by index (value is in the param's own min..max range from get_device_params).")]
- public Task SetDeviceParam(int trackId, int deviceIndex, int paramIndex, float value) => Mutate(() => E.DeviceSetParam(trackId, deviceIndex, paramIndex, value));
+ public Task SetDeviceParam(int trackId, int deviceIndex, int paramIndex, float value) => Mutate(() => DevParam(trackId, deviceIndex, paramIndex, value));
[McpServerTool(Name = "load_device_file"), Description("Load an audio file into a device that takes one — Nota Chamber: a user impulse response (WAV / FLAC / MP3; mono, stereo or 4-channel true stereo), which also selects it. Returns true on success.")]
public Task<bool> LoadDeviceFile(int trackId, int deviceIndex, [Description("Absolute path to the audio file")] string path) => Mutate(() => E.DeviceLoadFile(trackId, deviceIndex, path));
diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
index 1e27a753..e29dee83 100644
--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs
@@ -63,7 +63,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
[McpServerTool(Name = "set_instrument_param"), Description("Set a track instrument parameter by index to a normalized value (0..1). Use get_instrument_params for indices.")]
public Task SetInstrumentParam(int trackId, int paramIndex, [Description("Normalized 0..1")] float value)
- => Mutate(() => E.PluginParamSet(trackId, -1, paramIndex, Math.Clamp(value, 0f, 1f)));
+ => Mutate(() => PlugParam(trackId, -1, paramIndex, Math.Clamp(value, 0f, 1f)));
public sealed record PhysicalPartial(int Index, double Ratio, double Hz, double Amp, double RingSeconds, bool Audible);
public sealed record PhysicalReading(string Summary, string Guide, int ActiveVoices, int MaxVoices, bool Mono,
@@ -175,7 +175,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
int pc = E.PluginParamCount(trackId, -1);
var ids = new Dictionary<string, int>();
for (int i = 0; i < pc; i++) ids[E.PluginParamId(trackId, -1, i)] = i;
- void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
+ void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) PlugParam(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
static int Find(string[] names, string? v) => v is null ? -1 : Array.FindIndex(names, n => string.Equals(n, v.Trim(), StringComparison.OrdinalIgnoreCase));
var errors = new List<string>();
@@ -276,7 +276,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
int pc = E.PluginParamCount(trackId, -1);
var ids = new Dictionary<string, int>();
for (int i = 0; i < pc; i++) ids[E.PluginParamId(trackId, -1, i)] = i;
- void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
+ void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) PlugParam(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
static int Find(string[] names, string? v) => v is null ? -1 : Array.FindIndex(names, n => string.Equals(n, v.Trim(), StringComparison.OrdinalIgnoreCase));
static double Pct(double p) => Math.Clamp(p, 0, 100) / 100.0;
var errors = new List<string>();
@@ -347,7 +347,7 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc
for (int i = 0; i < pc; i++)
{
if (E.PluginParamId(trackId, -1, i) != paramId) continue;
- E.PluginParamSet(trackId, -1, i, Math.Clamp(value, 0f, 1f));
+ PlugParam(trackId, -1, i, Math.Clamp(value, 0f, 1f));
return true;
}
return false;
diff --git a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs b/src/managed/Nota.Mcp/Tools/MidiFxTools.cs
index 061dd984..ed9a3a74 100644
--- a/src/managed/Nota.Mcp/Tools/MidiFxTools.cs
+++ b/src/managed/Nota.Mcp/Tools/MidiFxTools.cs
@@ -54,7 +54,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
});
[McpServerTool(Name = "set_midi_fx_param"), Description("Set a MIDI effect parameter by index (value in the param's min..max range).")]
- public Task SetMidiFxParam(int trackId, int index, int paramIndex, float value) => Mutate(() => E.MidiEffectSetParam(trackId, index, paramIndex, value));
+ public Task SetMidiFxParam(int trackId, int index, int paramIndex, float value) => Mutate(() => MidiParam(trackId, index, paramIndex, value));
// ---- Nota Arp (kind 0) — named access to its globals and 16-step Groove lanes ----------
// Param layout mirrors Arpeggiator.h: 13 globals, 7 lanes × 16 steps, then VelAmt / View.
@@ -131,7 +131,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
string? loopMode = null, string? view = null) => Mutate(() =>
{
RequireArp(trackId, index);
- void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ void S(int p, float v) => MidiParam(trackId, index, p, v);
if (order is not null) S(GOrder, Pick(ArpOrders, order, "order"));
if (rate is not null) { S(GRate, Pick(ArpRates, rate, "rate")); S(GSync, 1); }
if (freeMs is { } ms) { S(GFreeRate, 1000f / Math.Clamp(ms, 20, 1000)); S(GSync, 0); }
@@ -156,7 +156,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
RequireArp(trackId, index);
if (!ArpLanes.TryGetValue(lane.Trim().ToLowerInvariant(), out var l))
throw new ArgumentException($"Unknown lane '{lane}'. Use one of: {string.Join(", ", ArpLanes.Keys)}.");
- for (int s = 0; s < values.Length && s < ArpSteps; s++) E.MidiEffectSetParam(trackId, index, l.Base + s, l.From(values[s]));
+ for (int s = 0; s < values.Length && s < ArpSteps; s++) MidiParam(trackId, index, l.Base + s, l.From(values[s]));
});
[McpServerTool(Name = "set_arp_step"), Description(
@@ -166,7 +166,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
{
RequireArp(trackId, index);
int s = Math.Clamp(step, 1, ArpSteps) - 1;
- void L(string n, float? v) { if (v is { } x) { var l = ArpLanes[n]; E.MidiEffectSetParam(trackId, index, l.Base + s, l.From(x)); } }
+ void L(string n, float? v) { if (v is { } x) { var l = ArpLanes[n]; MidiParam(trackId, index, l.Base + s, l.From(x)); } }
L("velocity", velocity); L("length", length); L("chance", chance);
L("ratchet", ratchet); L("transpose", transpose); L("on", on is { } b ? (b ? 1 : 0) : null);
});
@@ -232,7 +232,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
bool? keepRoot = null, bool? fold = null, string? foldKey = null, string? foldMode = null, string? view = null) => Mutate(() =>
{
RequireChord(trackId, index);
- void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ void S(int p, float v) => MidiParam(trackId, index, p, v);
int[]? iv = shifts;
if (iv is null && type is not null)
{
@@ -267,7 +267,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
RequireChord(trackId, index);
if (slot is < 1 or > CSlots) throw new ArgumentException("slot must be 1..6.");
int s = slot - 1;
- void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ void S(int p, float v) => MidiParam(trackId, index, p, v);
if (semitones is { } st) { S(CVoice + s, Math.Clamp(st, -12, 12)); if (on is null) S(COn + s, 1); }
if (on is { } o) S(COn + s, o ? 1 : 0);
if (velocity is { } v) S(CVel + s, Math.Clamp(v, -64, 63));
@@ -313,8 +313,8 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
{
if ((int)MathF.Round(E.MidiEffectGetParam(trackId, index, SScale)) >= SCustom) return;
int m = ScaleMask(trackId, index);
- for (int i = 0; i < 12; i++) E.MidiEffectSetParam(trackId, index, SMask + i, (m >> i) & 1);
- E.MidiEffectSetParam(trackId, index, SScale, SCustom);
+ for (int i = 0; i < 12; i++) MidiParam(trackId, index, SMask + i, (m >> i) & 1);
+ MidiParam(trackId, index, SScale, SCustom);
}
[McpServerTool(Name = "get_scale"), Description(
@@ -365,7 +365,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
string? view = null) => Mutate(() =>
{
RequireScale(trackId, index);
- void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ void S(int p, float v) => MidiParam(trackId, index, p, v);
if (root is not null) S(SRoot, ParsePc(root));
if (scale is not null)
{
@@ -406,7 +406,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
RequireScale(trackId, index);
ScaleMakeCustom(trackId, index);
int r = ((int)MathF.Round(E.MidiEffectGetParam(trackId, index, SRoot)) % 12 + 12) % 12;
- E.MidiEffectSetParam(trackId, index, SMask + ((ParsePc(note) - r) % 12 + 12) % 12, on ? 1 : 0);
+ MidiParam(trackId, index, SMask + ((ParsePc(note) - r) % 12 + 12) % 12, on ? 1 : 0);
});
// ---- Nota Length (kind 3) — named access in musical units --------------------------------
@@ -469,7 +469,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
bool? legato = null, bool? clipLimit = null, string? view = null) => Mutate(() =>
{
RequireLength(trackId, index);
- void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ void S(int p, float v) => MidiParam(trackId, index, p, v);
if (division is not null)
{
string d = division.Trim().Replace("D", ".", StringComparison.OrdinalIgnoreCase).Replace("t", "T");
@@ -564,7 +564,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
{
RequireVelocity(trackId, index);
float G(int p) => E.MidiEffectGetParam(trackId, index, p);
- void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ void S(int p, float v) => MidiParam(trackId, index, p, v);
if (drive is { } d) S(VDrive, MathF.Round(Math.Clamp(d, 0.25f, 4f), 2));
if (fixedValue is { } fv) { S(VFixed, Math.Clamp(fv, 1, 127) / 127f); S(VMode, 2); }
if (mode is not null)
@@ -645,7 +645,7 @@ public sealed class MidiFxTools(IAudioEngine engine, IEngineDispatch dispatch, I
bool? stayInScale = null, int? seed = null, bool? reroll = null, bool? locked = null, int? lockBar = null, string? view = null) => Mutate(() =>
{
RequireRandom(trackId, index);
- void S(int p, float v) => E.MidiEffectSetParam(trackId, index, p, v);
+ void S(int p, float v) => MidiParam(trackId, index, p, v);
if (chancePercent is { } c) S(RChance, Math.Clamp(c, 0, 100) / 100f);
if (noteRangeSemitones is { } n) S(RNote, Math.Clamp(n, 0, 12));
if (velocityRange is { } v) S(RVel, Math.Clamp(v, 0, 64) / 64f);
diff --git a/src/managed/Nota.Mcp/Tools/MosaicTools.cs b/src/managed/Nota.Mcp/Tools/MosaicTools.cs
index 3ac18465..ae8220b9 100644
--- a/src/managed/Nota.Mcp/Tools/MosaicTools.cs
+++ b/src/managed/Nota.Mcp/Tools/MosaicTools.cs
@@ -40,7 +40,7 @@ public sealed class MosaicTools(IAudioEngine engine, IEngineDispatch dispatch, I
private void Set(int t, string id, double v)
{
int pc = E.PluginParamCount(t, -1);
- for (int i = 0; i < pc; i++) if (E.PluginParamId(t, -1, i) == id) { E.PluginParamSet(t, -1, i, (float)Math.Clamp(v, 0, 1)); return; }
+ for (int i = 0; i < pc; i++) if (E.PluginParamId(t, -1, i) == id) { PlugParam(t, -1, i, (float)Math.Clamp(v, 0, 1)); return; }
}
private bool IsMosaic(int t) => E.TrackInstrumentKind(t) == MosaicModel.Kind;
diff --git a/src/managed/Nota.Mcp/Tools/PluginTools.cs b/src/managed/Nota.Mcp/Tools/PluginTools.cs
index 0106ad35..95314833 100644
--- a/src/managed/Nota.Mcp/Tools/PluginTools.cs
+++ b/src/managed/Nota.Mcp/Tools/PluginTools.cs
@@ -65,7 +65,7 @@ public sealed class PluginTools(IAudioEngine engine, IEngineDispatch dispatch, I
[McpServerTool(Name = "set_plugin_param"), Description("Set a hosted plugin parameter by index to a normalized value 0..1 (deviceIndex -1 = the track instrument).")]
public Task SetPluginParam(int trackId, int deviceIndex, int paramIndex, [Description("Normalized 0..1")] float value)
- => Mutate(() => E.PluginParamSet(trackId, deviceIndex, paramIndex, Math.Clamp(value, 0f, 1f)));
+ => Mutate(() => PlugParam(trackId, deviceIndex, paramIndex, Math.Clamp(value, 0f, 1f)));
[McpServerTool(Name = "get_plugin_state"), Description("Get a hosted plugin's opaque state as base64 (deviceIndex -1 = the track instrument). Round-trips with set_plugin_state.")]
public Task<string> GetPluginState(int trackId, int deviceIndex) => Read(() => Convert.ToBase64String(E.GetPluginState(trackId, deviceIndex) ?? Array.Empty<byte>()));
diff --git a/src/managed/Nota.Mcp/Tools/ProjectTools.cs b/src/managed/Nota.Mcp/Tools/ProjectTools.cs
index 518f8ba0..5a528e71 100644
--- a/src/managed/Nota.Mcp/Tools/ProjectTools.cs
+++ b/src/managed/Nota.Mcp/Tools/ProjectTools.cs
@@ -1,7 +1,8 @@
// SPDX-License-Identifier: AGPL-3.0-only
// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
//
-// MCP tools — whole-project snapshot (so the AI can see before it acts) + undo/redo.
+// MCP tools — whole-project snapshot (so the AI can see before it acts), undo/redo and the
+// arrangement's song sections.
using System.ComponentModel;
using ModelContextProtocol.Server;
@@ -52,4 +53,20 @@ public sealed class ProjectTools(IAudioEngine engine, IEngineDispatch dispatch,
[McpServerTool(Name = "redo"), Description("Redo the last undone edit. Returns whether anything was redone.")]
public Task<bool> Redo() => Mutate(() => E.Redo());
+
+ public sealed record Section(double StartBeat, double LengthBeats, string Name);
+
+ [McpServerTool(Name = "list_sections"), Description(
+ "List the arrangement's song sections (the named spans on the Sections lane — Intro, Verse, Drop …) in start order: "
+ + "start and length in beats, and the name.")]
+ public Task<Section[]> ListSections() => Read(() => E.Sections.Select(s => new Section(s.StartBeat, s.LengthBeats, s.Name)).ToArray());
+
+ [McpServerTool(Name = "set_sections"), Description(
+ "Replace the arrangement's song sections with this list (pass [] to remove them all). Each needs startBeat >= 0 and "
+ + "lengthBeats > 0; they are sorted by start, and a span with no length is dropped. One undo step. Returns the list as stored.")]
+ public Task<Section[]> SetSections(Section[] sections) => Mutate(() =>
+ {
+ E.SetSections(sections.Select(s => new SectionInfo(s.StartBeat, s.LengthBeats, s.Name ?? "")).ToList());
+ return E.Sections.Select(s => new Section(s.StartBeat, s.LengthBeats, s.Name)).ToArray();
+ });
}
diff --git a/src/managed/Nota.Mcp/Tools/RhythmTools.cs b/src/managed/Nota.Mcp/Tools/RhythmTools.cs
index 4271d652..396c4836 100644
--- a/src/managed/Nota.Mcp/Tools/RhythmTools.cs
+++ b/src/managed/Nota.Mcp/Tools/RhythmTools.cs
@@ -181,7 +181,7 @@ public sealed class RhythmTools(IAudioEngine engine, IEngineDispatch dispatch, I
int v = VoiceIndex(voice);
if (v < 0) return $"error: voice '{voice}' (0..7 or kick, snare, clap, rim, ch, oh, tom, perc)";
var ids = Ids(trackId);
- void Set(string p, float? val) { if (val is { } x && ids.TryGetValue(RM.Id(v, p), out var i)) E.PluginParamSet(trackId, -1, i, Math.Clamp(x, 0f, 1f)); }
+ void Set(string p, float? val) { if (val is { } x && ids.TryGetValue(RM.Id(v, p), out var i)) PlugParam(trackId, -1, i, Math.Clamp(x, 0f, 1f)); }
Set("tune", tune); Set("decay", decay); Set("punch", punch); Set("tone", tone); Set("drive", drive);
Set("level", level); Set("pan", pan); Set("start", start); Set("length", length);
if (semitones is { } st) Set("tune", RM.SampleSemisNorm(st));
@@ -223,7 +223,7 @@ public sealed class RhythmTools(IAudioEngine engine, IEngineDispatch dispatch, I
if (E.TrackInstrumentKind(trackId) != RM.Kind) return $"error: track {trackId} is not a Nota Rhythm";
if (macro is < 0 or >= RM.Macros) return "error: macro 0..7";
if (name is not null) E.RhythmSetMacroName(trackId, macro, name);
- if (value is { } v && Ids(trackId).TryGetValue(RM.MacroId(macro), out var pi)) E.PluginParamSet(trackId, -1, pi, Math.Clamp(v, 0f, 1f));
+ if (value is { } v && Ids(trackId).TryGetValue(RM.MacroId(macro), out var pi)) PlugParam(trackId, -1, pi, Math.Clamp(v, 0f, 1f));
return $"{E.RhythmMacroName(trackId, macro)}";
});
@@ -276,7 +276,7 @@ public sealed class RhythmTools(IAudioEngine engine, IEngineDispatch dispatch, I
{
if (E.TrackInstrumentKind(trackId) != RM.Kind) return $"error: track {trackId} is not a Nota Rhythm";
var ids = Ids(trackId);
- void Set(string id, float? val) { if (val is { } x && ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, Math.Clamp(x, 0f, 1f)); }
+ void Set(string id, float? val) { if (val is { } x && ids.TryGetValue(id, out var i)) PlugParam(trackId, -1, i, Math.Clamp(x, 0f, 1f)); }
Set("swing", swing); Set("humanize", humanize); Set("accent", accent); Set("glue", glue); Set("volume", volume);
var g = Getter(trackId);
return $"swing {RM.Pct(g("swing"))} · humanize {RM.Pct(g("humanize"))} · accent {RM.Pct(g("accent"))} · glue {RM.Pct(g("glue"))} · volume {RM.Pct(g("volume"))}";
@@ -304,7 +304,7 @@ public sealed class RhythmTools(IAudioEngine engine, IEngineDispatch dispatch, I
if (!E.SetRhythmVoiceSample(trackId, v, path)) return false;
var ids = Ids(trackId);
foreach (var (p, val) in new[] { ("tune", 0.5f), ("tone", 1f), ("start", 0f), ("length", 1f) })
- if (ids.TryGetValue(RM.Id(v, p), out var i)) E.PluginParamSet(trackId, -1, i, val);
+ if (ids.TryGetValue(RM.Id(v, p), out var i)) PlugParam(trackId, -1, i, val);
return true;
});
diff --git a/src/managed/Nota.Mcp/Tools/SampleTools.cs b/src/managed/Nota.Mcp/Tools/SampleTools.cs
index 69be5980..83ad0a32 100644
--- a/src/managed/Nota.Mcp/Tools/SampleTools.cs
+++ b/src/managed/Nota.Mcp/Tools/SampleTools.cs
@@ -125,7 +125,7 @@ public sealed class SampleTools(IAudioEngine engine, IEngineDispatch dispatch, I
var ids = new Dictionary<string, int>();
for (int i = 0; i < pc; i++) ids[E.PluginParamId(trackId, -1, i)] = i;
float Get(string id) => ids.TryGetValue(id, out var i) ? E.PluginParamGet(trackId, -1, i) : 0f;
- void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) E.PluginParamSet(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
+ void Set(string id, double v) { if (ids.TryGetValue(id, out var i)) PlugParam(trackId, -1, i, (float)Math.Clamp(v, 0, 1)); }
static int Find(string[] names, string v) => Array.FindIndex(names, n => string.Equals(n, v.Trim(), StringComparison.OrdinalIgnoreCase)
|| n.StartsWith(v.Trim(), StringComparison.OrdinalIgnoreCase));
var errors = new List<string>();
diff --git a/src/managed/Nota.Remote/RemoteHub.Apply.cs b/src/managed/Nota.Remote/RemoteHub.Apply.cs
index b538561e..b0b9611f 100644
--- a/src/managed/Nota.Remote/RemoteHub.Apply.cs
+++ b/src/managed/Nota.Remote/RemoteHub.Apply.cs
@@ -119,7 +119,7 @@ public sealed partial class RemoteHub
if (r != PhoneControlResult.None) break;
var devs = MacroDevicesFor(c.TrackId);
if (c.MacroDevice < devs.Count && knob < devs[c.MacroDevice].Params.Count)
- RemoteParams.Set(_engine, devs[c.MacroDevice].Params[knob], cmd.V);
+ SetParam(c, devs[c.MacroDevice].Params[knob], cmd.V, cmd.Phase);
if (cmd.Phase == 2) host.Refresh();
break;
}
@@ -140,7 +140,8 @@ public sealed partial class RemoteHub
_heldFaders[faderId] = (c.ConnectionId, ShortName(c.Name), DateTime.UtcNow.Add(FaderHold).Ticks);
}
- // Undo (specs/009): one step per touch on a volume / pan / master fader — opened by the
+ // Undo (specs/009, specs/016): one step per touch on a volume / pan / master fader, a
+ // macro knob or the XY pad — opened by the
// touch's first command, closed by its phase-2 command, by the phone going away, or after
// FaderHold without a command (a lost finger-up never leaves a gesture open).
private readonly Dictionary<(int Conn, MixTarget Target), (int Handle, long Until)> _mixUndo = new();
@@ -154,6 +155,13 @@ public sealed partial class RemoteHub
else _mixUndo[key] = (handle, DateTime.UtcNow.Add(FaderHold).Ticks);
}
+ // A device parameter moved from the phone: one undo step per touch, as a fader (specs/016).
+ private void SetParam(RemoteClient c, RemoteParam p, double norm, int phase)
+ {
+ if (RemoteParams.UndoTarget(p) is { } target) MixTouch(c, target, phase, () => RemoteParams.Set(_engine, p, norm));
+ else RemoteParams.Set(_engine, p, norm);
+ }
+
private void ExpireMixUndo()
{
if (_mixUndo.Count == 0) return;
@@ -200,7 +208,7 @@ public sealed partial class RemoteHub
if (r2 == PhoneControlResult.Mapped) return;
}
if (!defResolved) { def = RemoteParams.DefaultXy(_engine, c.TrackId); defResolved = true; }
- if (def is { } d) RemoteParams.Set(_engine, isX ? d.X : d.Y, v);
+ if (def is { } d) SetParam(c, isX ? d.X : d.Y, v, cmd.Phase);
}
if (doX) Axis(true, Math.Clamp(cmd.V, 0, 1));
diff --git a/src/managed/Nota.Remote/RemoteParams.cs b/src/managed/Nota.Remote/RemoteParams.cs
index 71dd8c69..f731b2ae 100644
--- a/src/managed/Nota.Remote/RemoteParams.cs
+++ b/src/managed/Nota.Remote/RemoteParams.cs
@@ -181,6 +181,15 @@ public static class RemoteParams
}
}
+ /// <summary>The undo target for a parameter (specs/016); none for a rack macro, which
+ /// value undo does not cover.</summary>
+ public static MixTarget? UndoTarget(RemoteParam p) => p.Kind switch
+ {
+ RemoteParamKind.DeviceParam => MixTarget.DeviceParam(p.TrackId, p.DeviceIndex, p.ParamIndex),
+ RemoteParamKind.PluginParam => MixTarget.PluginParam(p.TrackId, p.DeviceIndex, p.ParamIndex),
+ _ => null,
+ };
+
/// <summary>Move a parameter to <paramref name="norm"/> as a hardware control would: a
/// latching automation write (an override when Record is off).</summary>
public static void Set(IAudioEngine e, RemoteParam p, double norm)
diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.h
index 8d408b72..2c7f9e56 100644
--- a/src/native/nota.engine/include/nota/nota_engine.h
+++ b/src/native/nota.engine/include/nota/nota_engine.h
@@ -430,7 +430,9 @@ NOTA_API int32_t nota_engine_automation_device_remap_selftest(NotaEngine* engine
* gesture; latch != 0 means a hardware/MIDI control, which keeps writing past the
* release until the transport stops. With record off, touching a parameter that
* already carries automation overrides its lane until re-enable. For a
- * PluginParam target pass param_id; otherwise param_id may be NULL/empty. */
+ * PluginParam target pass param_id; otherwise param_id may be NULL/empty.
+ * An unlatched begin/end on a parameter target (device, MIDI-effect or plugin param) is
+ * also that parameter's value-undo gesture (specs/016): one undo step for what changed. */
NOTA_API void nota_engine_set_automation_record(NotaEngine* engine, int32_t on);
NOTA_API int32_t nota_engine_automation_record(const NotaEngine* engine);
NOTA_API void nota_track_begin_automation_write(NotaEngine* engine, int32_t track_id,
@@ -790,10 +792,10 @@ NOTA_API NotaResult nota_engine_poll(NotaEngine* engine);
/* ---- Undo / redo (M6-6) -------------------------------------------------- */
/* Undo/redo of structural edits (tracks, clips, notes, device chains, session
- * slots) — restores a retained Graph snapshot — and of volume / pan / master volume
- * steps made through mix gestures (009). Returns NOTA_OK if a step was applied,
- * NOTA_ERR_UNKNOWN if there was nothing to undo/redo. Mute, solo, sends, bypass,
- * device params and the transport are not covered. */
+ * slots, arrangement sections) — restores a retained Graph snapshot — and of volume /
+ * pan / master volume (009) and device-parameter (016) steps made through value
+ * gestures. Returns NOTA_OK if a step was applied, NOTA_ERR_UNKNOWN if there was nothing
+ * to undo/redo. Mute, solo, sends, bypass and the transport are not covered. */
NOTA_API NotaResult nota_engine_undo(NotaEngine* engine);
NOTA_API NotaResult nota_engine_redo(NotaEngine* engine);
NOTA_API int32_t nota_engine_can_undo(const NotaEngine* engine);
@@ -807,8 +809,9 @@ NOTA_API void nota_engine_undo_group_end(NotaEngine* engine);
* closed. Message thread only. No-op for a null engine. */
NOTA_API void nota_engine_clear_undo_history(NotaEngine* engine);
-/* ---- Mix undo (009) ------------------------------------------------------ */
-/* Volume / pan / master volume changes become undo steps through gestures. A gesture
+/* ---- Value undo (009, 016) ----------------------------------------------- */
+/* Volume / pan / master volume and device-parameter changes become undo steps through
+ * gestures. A gesture
* records its targets' values at begin and, at end, pushes ONE undo step with the values
* that changed (none changed → no step). If a structural checkpoint was pushed during the
* gesture (automation recording) the step merges into it. The plain setters never record:
@@ -816,13 +819,18 @@ NOTA_API void nota_engine_clear_undo_history(NotaEngine* engine);
#define NOTA_MIX_TRACK_VOLUME 0
#define NOTA_MIX_TRACK_PAN 1
#define NOTA_MIX_MASTER_VOLUME 2
+#define NOTA_MIX_DEVICE_PARAM 3 /* audio effect: device_index = chain position */
+#define NOTA_MIX_MIDI_DEVICE_PARAM 4 /* MIDI effect: device_index = MIDI-FX chain position */
+#define NOTA_MIX_PLUGIN_PARAM 5 /* normalized 0..1; device_index -1 = the instrument */
typedef struct NotaMixTarget {
- int32_t kind; /* NOTA_MIX_* */
- int32_t track_id; /* ignored for NOTA_MIX_MASTER_VOLUME */
+ int32_t kind; /* NOTA_MIX_* */
+ int32_t track_id; /* ignored for NOTA_MIX_MASTER_VOLUME; the master chain = master id */
+ int32_t device_index; /* parameter kinds only (-1 otherwise) */
+ int32_t param_index; /* parameter kinds only (-1 otherwise) */
} NotaMixTarget;
-/* Returns a handle > 0, or 0 if no target is valid. */
+/* Returns a handle > 0, or 0 if no target is valid (a missing track, device or param). */
NOTA_API int32_t nota_mix_gesture_begin(NotaEngine* engine, const NotaMixTarget* targets, int32_t count);
/* Ends the gesture; unknown / already-ended handles are ignored. */
NOTA_API void nota_mix_gesture_end(NotaEngine* engine, int32_t handle);
@@ -870,6 +878,26 @@ NOTA_API NotaResult nota_engine_set_pan_law(NotaEngine* engine, int32_t law, int
/* Current law (authoring graph). NOTA_PAN_LAW_BALANCE for a null engine. */
NOTA_API int32_t nota_engine_pan_law(const NotaEngine* engine);
+/* ---- Arrangement sections (016) ----------------------------------------- */
+/* Named spans of arrangement time (Intro / Verse / Drop), project-level data in the graph
+ * snapshot: undo/redo restore them, a reset (load / new) clears them. Sorted by start. */
+typedef struct NotaSection {
+ double start_beat;
+ double length_beats;
+ const char* name_utf8; /* NULL = "" */
+} NotaSection;
+
+NOTA_API int32_t nota_engine_section_count(const NotaEngine* engine);
+/* Out-of-range index: 0.0 / 0.0 / "". The name stays valid until the next edit. */
+NOTA_API double nota_engine_section_start(const NotaEngine* engine, int32_t index);
+NOTA_API double nota_engine_section_length(const NotaEngine* engine, int32_t index);
+NOTA_API const char* nota_engine_section_name(const NotaEngine* engine, int32_t index);
+/* Replace the list: sorted by start, entries with length <= 0 dropped, start clamped to
+ * >= 0. checkpoint = 1: one undo step (user edit; an identical list makes none); 0: no
+ * undo entry (project load). count 0 clears. Message thread only. */
+NOTA_API NotaResult nota_engine_set_sections(NotaEngine* engine, const NotaSection* sections,
+ int32_t count, int32_t checkpoint);
+
/* ---- Project load (M7-6) ------------------------------------------------- */
/* Clear the session to an empty project: stop transport, drop all tracks,
* reset the track-id counter and undo/redo history. Message thread only. */
diff --git a/src/native/nota.engine/src/Engine.cpp b/src/native/nota.engine/src/Engine.cpp
index 68e0aad3..894a8c37 100644
--- a/src/native/nota.engine/src/Engine.cpp
+++ b/src/native/nota.engine/src/Engine.cpp
@@ -576,8 +576,48 @@ bool Engine::redo() {
// --- mix gestures (specs/009) ----------------------------------------------
+namespace {
+bool isParamKind(MixKind k) {
+ return k == MixKind::DeviceParam || k == MixKind::MidiDeviceParam || k == MixKind::PluginParam;
+}
+// The CV-modulation target kind (Engine_Modulation) a parameter value step addresses.
+int32_t cvKindOf(MixKind k) {
+ return k == MixKind::DeviceParam ? 0 : k == MixKind::PluginParam ? 1 : 2;
+}
+}
+
+// Does the parameter a value step addresses exist right now? (specs/016: a step whose
+// device is gone is skipped, like one whose track is gone.)
+bool Engine::paramTargetExists(MixKind kind, int32_t trackId, int32_t deviceIndex, int32_t paramIndex) const {
+ if (paramIndex < 0) return false;
+ switch (kind) {
+ case MixKind::DeviceParam: {
+ auto* d = deviceAt(trackId, deviceIndex);
+ return d && paramIndex < d->paramCount();
+ }
+ case MixKind::MidiDeviceParam: {
+ auto* m = midiDeviceAt(trackId, deviceIndex);
+ return m && paramIndex < m->paramCount();
+ }
+ case MixKind::PluginParam: return paramIndex < pluginParamCount(trackId, deviceIndex);
+ default: return false;
+ }
+}
+
bool Engine::mixValue(const MixTarget& t, float& v) const {
if (t.kind == MixKind::MasterVolume) { v = masterVolume(); return true; }
+ if (isParamKind(t.kind)) {
+ if (!paramTargetExists(t.kind, t.trackId, t.deviceIndex, t.paramIndex)) return false;
+ // A CV-modulated parameter: the user edits (and undo restores) the link's base, not
+ // the value the modulation is driving right now.
+ if (cvBaseValue(cvKindOf(t.kind), t.trackId, t.deviceIndex, t.paramIndex, v)) return true;
+ switch (t.kind) {
+ case MixKind::DeviceParam: v = deviceGetParam(t.trackId, t.deviceIndex, t.paramIndex); break;
+ case MixKind::MidiDeviceParam: v = midiEffectGetParam(t.trackId, t.deviceIndex, t.paramIndex); break;
+ default: v = pluginParamGet(t.trackId, t.deviceIndex, t.paramIndex); break;
+ }
+ return true;
+ }
auto tr = findTrackAuthoring(t.trackId);
if (!tr) return false;
v = t.kind == MixKind::TrackVolume ? tr->volume() : tr->pan();
@@ -587,6 +627,15 @@ bool Engine::mixValue(const MixTarget& t, float& v) const {
bool Engine::applyMix(const MixChange& c, bool after) {
const float v = after ? c.after : c.before;
if (c.kind == MixKind::MasterVolume) { setMasterVolume(v); return true; }
+ if (isParamKind(c.kind)) {
+ if (!paramTargetExists(c.kind, c.trackId, c.deviceIndex, c.paramIndex)) return false; // gone: skip
+ switch (c.kind) { // the user-facing setters: CV bases, PDC and plugin hosts follow
+ case MixKind::DeviceParam: deviceSetParam(c.trackId, c.deviceIndex, c.paramIndex, v); break;
+ case MixKind::MidiDeviceParam: midiEffectSetParam(c.trackId, c.deviceIndex, c.paramIndex, v); break;
+ default: pluginParamSet(c.trackId, c.deviceIndex, c.paramIndex, v); break;
+ }
+ return true;
+ }
auto tr = findTrackAuthoring(c.trackId);
if (!tr) return false; // the track is gone: skip quietly
if (c.kind == MixKind::TrackVolume) tr->setVolume(v); else tr->setPan(v);
@@ -598,7 +647,8 @@ bool Engine::applyMix(const MixChange& c, bool after) {
void Engine::mergeMix(std::vector<MixChange>& into, const std::vector<MixChange>& later) {
for (const auto& c : later) {
auto it = std::find_if(into.begin(), into.end(), [&](const MixChange& m) {
- return m.kind == c.kind && (c.kind == MixKind::MasterVolume || m.trackId == c.trackId);
+ return m.kind == c.kind && (c.kind == MixKind::MasterVolume ||
+ (m.trackId == c.trackId && m.deviceIndex == c.deviceIndex && m.paramIndex == c.paramIndex));
});
if (it == into.end()) into.push_back(c); else it->after = c.after;
}
@@ -657,7 +707,8 @@ int32_t Engine::beginMixGesture(const MixTarget* targets, int32_t count) {
OpenMixGesture g{ nextMixGesture_, {}, undoPushCount_, undoStack_.size() };
for (int32_t i = 0; i < count; ++i) {
float v = 0.0f;
- if (mixValue(targets[i], v)) g.targets.push_back({ targets[i].kind, targets[i].trackId, v, v });
+ if (mixValue(targets[i], v))
+ g.targets.push_back({ targets[i].kind, targets[i].trackId, v, v, targets[i].deviceIndex, targets[i].paramIndex });
}
if (g.targets.empty()) return 0;
if (++nextMixGesture_ <= 0) nextMixGesture_ = 1;
@@ -674,7 +725,7 @@ void Engine::endMixGesture(int32_t handle) {
std::vector<MixChange> changes;
for (auto& c : g.targets) {
float v = 0.0f;
- if (!mixValue({ c.kind, c.trackId }, v)) continue; // the track went away mid-gesture
+ if (!mixValue({ c.kind, c.trackId, c.deviceIndex, c.paramIndex }, v)) continue; // gone mid-gesture
if (v == c.before) continue; // exact: no net change, no step
c.after = v;
changes.push_back(c);
@@ -717,6 +768,23 @@ bool Engine::setPanLaw(PanLaw law, bool checkpoint) {
return true;
}
+// --- arrangement sections (specs/016) ---------------------------------------
+
+void Engine::setSections(std::vector<Section> sections, bool checkpoint) {
+ if (!authoring_) return;
+ sections.erase(std::remove_if(sections.begin(), sections.end(),
+ [](const Section& s) { return !(s.lengthBeats > 0.0); }), // also drops NaN
+ sections.end());
+ for (auto& s : sections) if (!(s.startBeat > 0.0)) s.startBeat = 0.0;
+ std::stable_sort(sections.begin(), sections.end(),
+ [](const Section& a, const Section& b) { return a.startBeat < b.startBeat; });
+ if (sections == authoring_->sections) return; // nothing changed: no step
+ auto g = std::make_shared<Graph>(*authoring_); // copy: tracks shared, graph-level fields kept
+ g->sections = std::move(sections);
+ if (checkpoint) publish(std::move(g));
+ else publishRaw(std::move(g));
+}
+
// --- project load (M7-6) ---------------------------------------------------
void Engine::reset() {
@@ -748,6 +816,7 @@ void Engine::clearUndoHistory() {
undoStack_.clear();
redoStack_.clear();
mixGestures_.clear(); // a gesture can't outlive the history it would land in
+ touchGestures_.clear();
undoGroupDepth_ = 0; undoGroupBase_ = 0;
}
diff --git a/src/native/nota.engine/src/Engine.h b/src/native/nota.engine/src/Engine.h
index 4f46eee8..436b9b2a 100644
--- a/src/native/nota.engine/src/Engine.h
+++ b/src/native/nota.engine/src/Engine.h
@@ -71,12 +71,23 @@ using MonitorQueue = SpscRingBuffer<InputFrame, 1u << 14>; // input thread -> au
// is the pitch and value the velocity. The engine still routes notes to instruments.
struct ControlEvent { int32_t kind; int32_t channel; int32_t number; int32_t value; };
-// Mix undo (specs/009): volume / pan / master volume live in atomics outside the graph, so
-// their undo steps carry values instead of a snapshot. They share one history with the
-// structural snapshots (UndoEntry), which keeps the order of all edits.
-enum class MixKind : int32_t { TrackVolume = 0, TrackPan = 1, MasterVolume = 2 };
-struct MixTarget { MixKind kind; int32_t trackId; }; // trackId ignored for MasterVolume
-struct MixChange { MixKind kind; int32_t trackId; float before; float after; };
+// Value undo (specs/009, specs/016): volume / pan / master volume live in atomics outside the
+// graph, and device parameters live in Device objects that cloned tracks share — restoring
+// an older graph restores neither. Their undo steps carry values instead of a snapshot. They
+// share one history with the structural snapshots (UndoEntry), which keeps the order of all
+// edits. Parameter kinds address (track, device index, parameter index): DeviceParam an audio
+// effect, MidiDeviceParam a MIDI effect, PluginParam a normalized hosted-plugin / built-in
+// instrument parameter (deviceIndex -1 = the instrument).
+enum class MixKind : int32_t { TrackVolume = 0, TrackPan = 1, MasterVolume = 2,
+ DeviceParam = 3, MidiDeviceParam = 4, PluginParam = 5 };
+struct MixTarget {
+ MixKind kind; int32_t trackId; // trackId ignored for MasterVolume
+ int32_t deviceIndex = -1; int32_t paramIndex = -1; // parameter kinds only
+};
+struct MixChange {
+ MixKind kind; int32_t trackId; float before; float after;
+ int32_t deviceIndex = -1; int32_t paramIndex = -1; // parameter kinds only
+};
struct UndoEntry {
std::shared_ptr<Graph> graph; // the state to restore; null for a mix-only step
std::vector<MixChange> mix; // empty for a structural step; one change per target
@@ -999,9 +1010,9 @@ public:
// previous authoring_ is already a complete restore point. Undo/redo just
// swap the authoring/live pointer between retained snapshots (audio sample
// buffers are shared via shared_ptr, so a snapshot costs only metadata).
- // Scope: structural graph edits, plus volume / pan / master volume steps made through
- // mix gestures (specs/009). Mute, solo, sends, bypass, device params and the transport
- // live outside the Graph and are not covered.
+ // Scope: structural graph edits (arrangement sections included, specs/016), plus volume /
+ // pan / master volume (specs/009) and device-parameter (specs/016) steps made through
+ // value gestures. Mute, solo, sends, bypass and the transport are not covered.
bool undo();
bool redo();
bool canUndo() const { return !undoStack_.empty(); }
@@ -1016,10 +1027,12 @@ public:
// built default project). Message thread only.
void clearUndoHistory();
- // --- mix gestures (specs/009) ---
+ // --- value gestures (specs/009 volume / pan, specs/016 device parameters) ---
// begin records the targets' values; end pushes ONE undo step with the values that
// changed (none → no step), merged into a structural checkpoint pushed meanwhile
- // (automation recording). The plain setters never record. Message thread only.
+ // (automation recording). The plain setters never record. An unlatched automation-write
+ // touch on a parameter (every on-screen control's press / release) opens and closes one
+ // for that parameter. Message thread only.
int32_t beginMixGesture(const MixTarget* targets, int32_t count); // handle > 0, or 0
void endMixGesture(int32_t handle); // unknown handle: no-op
float masterVolume() const { return masterVolume_.load(std::memory_order_relaxed); }
@@ -1037,6 +1050,10 @@ public:
// Graph-level, so undo/redo restore it. checkpoint = false for load / the new-project
// baseline. False for an unknown law; a no-op (no undo step) if unchanged. Message thread.
bool setPanLaw(PanLaw law, bool checkpoint);
+ // Arrangement sections (specs/016): project-level, replaced as a whole. checkpoint =
+ // one undo step (an identical list makes none); false = baseline (project load).
+ void setSections(std::vector<Section> sections, bool checkpoint);
+ const std::vector<Section>& sections() const { static const std::vector<Section> none; return authoring_ ? authoring_->sections : none; }
PanLaw panLaw() const { return authoring_ ? authoring_->panLaw : PanLaw::Balance; }
// --- offline render (tests / export) ---
@@ -1105,6 +1122,8 @@ private:
float modOutput(Track& t, int32_t modId, double beat, double timeSec);
void restoreLinkTarget(int32_t ownerTrack, const CvLink& l); // drive target param back to base
void routeCvBaseEdit(int32_t targetKind, int32_t trackId, int32_t device, int32_t param, float value);
+ // The base a CV link holds for this target, if one targets it (what a UI edit sets).
+ bool cvBaseValue(int32_t targetKind, int32_t trackId, int32_t device, int32_t param, float& out) const;
int32_t addCvLinkFull(int32_t trackId, int32_t sourceKind, int32_t modId, int32_t srcDev, int32_t srcParam,
int32_t targetKind, int32_t targetTrack, int32_t targetDevice, int32_t targetParam);
Modulator* modulatorPtr(Track& t, int32_t modId);
@@ -1304,6 +1323,7 @@ private:
std::vector<OpenMixGesture> mixGestures_; // message thread; `before` filled at begin
int32_t nextMixGesture_ = 1;
bool mixValue(const MixTarget& t, float& v) const; // current value; false = gone
+ bool paramTargetExists(MixKind kind, int32_t trackId, int32_t deviceIndex, int32_t paramIndex) const;
bool applyMix(const MixChange& c, bool after); // write before/after; false = gone
static void mergeMix(std::vector<MixChange>& into, const std::vector<MixChange>& later);
static constexpr size_t kMaxUndoDepth = 128;
@@ -1384,6 +1404,15 @@ private:
// reenableAutomation() (Live's "Re-Enable Automation").
struct OverrideTarget { int32_t trackId; int32_t laneIndex; };
std::vector<ActiveWrite> activeWrites_;
+ // Value gestures opened by unlatched parameter touches (specs/016), closed by the
+ // matching endAutomationWrite. One per touch identity.
+ struct TouchGesture {
+ int32_t trackId; int32_t target; int32_t deviceIndex; int32_t paramIndex;
+ std::string paramId; int32_t handle;
+ };
+ std::vector<TouchGesture> touchGestures_;
+ void beginParamTouch(int32_t trackId, int32_t target, int32_t deviceIndex, int32_t paramIndex, const std::string& id);
+ void endParamTouch(int32_t trackId, int32_t target, int32_t deviceIndex, int32_t paramIndex, const std::string& id);
std::vector<OverrideTarget> overrides_;
bool wasPlaying_ = false; // poll() edge detection: stop ends latched writes
bool renderWasPlaying_ = false; // audio-thread play→stop edge (flush stuck notes)
diff --git a/src/native/nota.engine/src/Engine_Automation.cpp b/src/native/nota.engine/src/Engine_Automation.cpp
index d73d012b..7752783d 100644
--- a/src/native/nota.engine/src/Engine_Automation.cpp
+++ b/src/native/nota.engine/src/Engine_Automation.cpp
@@ -278,9 +278,50 @@ static int32_t findLaneFor(const Track& t, int32_t target, int32_t deviceIndex,
return -1;
}
+// specs/016: an unlatched touch — a mouse press on a parameter control, or a one-off edit
+// bracketed by begin/end — is one value-undo gesture on that parameter. Latched touches
+// (hardware controls) end by pause on the managed side instead; volume / pan touches are
+// gestured by their sources (specs/009).
+void Engine::beginParamTouch(int32_t trackId, int32_t target, int32_t deviceIndex,
+ int32_t paramIndex, const std::string& id) {
+ MixKind kind;
+ switch (static_cast<AutomationTarget>(target)) {
+ case AutomationTarget::DeviceParam: kind = MixKind::DeviceParam; break;
+ case AutomationTarget::MidiDeviceParam: kind = MixKind::MidiDeviceParam; break;
+ case AutomationTarget::PluginParam: kind = MixKind::PluginParam;
+ paramIndex = pluginParamIndexOfId(trackId, deviceIndex, id); break;
+ default: return;
+ }
+ for (const auto& tg : touchGestures_)
+ if (tg.trackId == trackId &&
+ sameTarget(tg.target, tg.deviceIndex, tg.paramIndex, tg.paramId, target, deviceIndex, paramIndex, id))
+ return; // already open
+ const MixTarget mt{ kind, trackId, deviceIndex, paramIndex };
+ if (const int32_t h = beginMixGesture(&mt, 1))
+ touchGestures_.push_back({ trackId, target, deviceIndex, paramIndex, id, h });
+}
+
+void Engine::endParamTouch(int32_t trackId, int32_t target, int32_t deviceIndex,
+ int32_t paramIndex, const std::string& id) {
+ for (size_t i = 0; i < touchGestures_.size(); ++i) {
+ const auto& tg = touchGestures_[i];
+ // PluginParam touches match by id (sameTarget ignores the index begin resolved).
+ if (tg.trackId != trackId ||
+ !sameTarget(tg.target, tg.deviceIndex, tg.paramIndex, tg.paramId, target, deviceIndex, paramIndex, id))
+ continue;
+ const int32_t h = tg.handle;
+ touchGestures_.erase(touchGestures_.begin() + static_cast<std::ptrdiff_t>(i));
+ endMixGesture(h);
+ return;
+ }
+}
+
void Engine::beginAutomationWrite(int32_t trackId, int32_t target, int32_t deviceIndex,
int32_t paramIndex, const char* paramId, bool latch) {
const std::string id = paramId ? paramId : "";
+ // Open the undo gesture first, so a checkpoint the write pushes below (recording) merges
+ // into it and the lane edit and the value undo as one step.
+ if (!latch) beginParamTouch(trackId, target, deviceIndex, paramIndex, id);
for (auto& aw : activeWrites_) // already writing this target?
if (aw.trackId == trackId &&
sameTarget(aw.target, aw.deviceIndex, aw.paramIndex, aw.paramId, target, deviceIndex, paramIndex, id))
@@ -325,6 +366,7 @@ void Engine::endAutomationWrite(int32_t trackId, int32_t target, int32_t deviceI
// A released mouse gesture stops writing here; a latched one (hardware control)
// keeps writing its last value until the transport stops (finishAllWrites).
const std::string id = paramId ? paramId : "";
+ endParamTouch(trackId, target, deviceIndex, paramIndex, id); // the value-undo step (specs/016)
for (size_t i = 0; i < activeWrites_.size(); ++i) {
auto& aw = activeWrites_[i];
if (aw.trackId == trackId &&
diff --git a/src/native/nota.engine/src/Engine_Modulation.cpp b/src/native/nota.engine/src/Engine_Modulation.cpp
index e79464f9..e0d9e8e3 100644
--- a/src/native/nota.engine/src/Engine_Modulation.cpp
+++ b/src/native/nota.engine/src/Engine_Modulation.cpp
@@ -293,6 +293,21 @@ void Engine::routeCvBaseEdit(int32_t targetKind, int32_t trackId, int32_t device
}
}
+bool Engine::cvBaseValue(int32_t targetKind, int32_t trackId, int32_t device, int32_t param, float& out) const {
+ if (!authoring_) return false;
+ for (auto& op : authoring_->tracks) {
+ const int32_t owner = op->id();
+ for (auto& l : op->cvLinks) {
+ const int32_t tgt = l.targetTrack < 0 ? owner : l.targetTrack;
+ if (tgt == trackId && l.targetKind == targetKind && l.targetDevice == device && l.targetParam == param) {
+ out = l.base.load(std::memory_order_relaxed);
+ return true;
+ }
+ }
+ }
+ return false;
+}
+
// ---- device edit → CV-link index fix-up (message thread) -------------------
// New index of `idx` after the device at `from` is moved to `to` (vector erase+insert).
diff --git a/src/native/nota.engine/src/Graph.h b/src/native/nota.engine/src/Graph.h
index 32e05a5d..145d0a91 100644
--- a/src/native/nota.engine/src/Graph.h
+++ b/src/native/nota.engine/src/Graph.h
@@ -14,6 +14,7 @@
#include "Track.h"
#include <memory>
+#include <string>
#include <vector>
namespace nota {
@@ -23,6 +24,15 @@ namespace nota {
// mono material and at centre. Groups, clip pan envelopes and rack chains ignore it.
enum class PanLaw : int32_t { Balance = 0, Stereo = 1 };
+// A named span of arrangement time — Intro / Verse / Drop (specs/016). Project-level
+// authoring data: the audio thread never reads it.
+struct Section {
+ double startBeat = 0.0; // >= 0
+ double lengthBeats = 0.0; // > 0
+ std::string name;
+ bool operator==(const Section&) const = default;
+};
+
struct Graph {
std::vector<std::shared_ptr<Track>> tracks;
int32_t sceneCount = 8; // Session view rows (M5)
@@ -40,6 +50,9 @@ struct Graph {
// Project pan law (specs/006). In the snapshot so undo/redo restore it; Balance is the
// engine default (and every project before format v21).
PanLaw panLaw = PanLaw::Balance;
+ // Arrangement sections (specs/016), sorted by start. In the snapshot so undo/redo
+ // restore them and the project saves them.
+ std::vector<Section> sections;
};
// Graph-level fields (everything except `tracks`). A fresh graph built from scratch must
@@ -51,6 +64,7 @@ inline void inheritGraphLevel(Graph& dst, const Graph& src) {
dst.masterVolume = src.masterVolume;
dst.masterTrack = src.masterTrack;
dst.panLaw = src.panLaw;
+ dst.sections = src.sections;
}
} // namespace nota
diff --git a/src/native/nota.engine/src/nota_engine_core.cpp b/src/native/nota.engine/src/nota_engine_core.cpp
index d8e0f673..f2fa31b6 100644
--- a/src/native/nota.engine/src/nota_engine_core.cpp
+++ b/src/native/nota.engine/src/nota_engine_core.cpp
@@ -249,7 +249,7 @@ void nota_engine_undo_group_begin(NotaEngine* e) { if (e) ENG(e)->beginUndoGroup
void nota_engine_undo_group_end(NotaEngine* e) { if (e) ENG(e)->endUndoGroup(); }
void nota_engine_clear_undo_history(NotaEngine* e) { if (e) ENG(e)->clearUndoHistory(); }
-// ---- Mix undo (009) ---------------------------------------------------------
+// ---- Value undo (009, 016) -------------------------------------------------
int32_t nota_mix_gesture_begin(NotaEngine* e, const NotaMixTarget* targets, int32_t count) {
if (!e || !targets || count <= 0 || count > 64) return 0;
@@ -257,8 +257,8 @@ int32_t nota_mix_gesture_begin(NotaEngine* e, const NotaMixTarget* targets, int3
int32_t n = 0;
for (int32_t i = 0; i < count; ++i) {
const int32_t k = targets[i].kind;
- if (k < NOTA_MIX_TRACK_VOLUME || k > NOTA_MIX_MASTER_VOLUME) continue;
- t[n++] = { static_cast<nota::MixKind>(k), targets[i].track_id };
+ if (k < NOTA_MIX_TRACK_VOLUME || k > NOTA_MIX_PLUGIN_PARAM) continue;
+ t[n++] = { static_cast<nota::MixKind>(k), targets[i].track_id, targets[i].device_index, targets[i].param_index };
}
return n > 0 ? ENG(e)->beginMixGesture(t, n) : 0;
}
@@ -282,6 +282,29 @@ int32_t nota_engine_pan_law(const NotaEngine* e) {
return e ? static_cast<int32_t>(CENG(e)->panLaw()) : NOTA_PAN_LAW_BALANCE;
}
+// ---- Arrangement sections (016) ----------------------------------------------
+
+int32_t nota_engine_section_count(const NotaEngine* e) {
+ return e ? static_cast<int32_t>(CENG(e)->sections().size()) : 0;
+}
+static const nota::Section* sectionAt(const NotaEngine* e, int32_t i) {
+ if (!e) return nullptr;
+ const auto& v = CENG(e)->sections();
+ return (i >= 0 && i < static_cast<int32_t>(v.size())) ? &v[static_cast<size_t>(i)] : nullptr;
+}
+double nota_engine_section_start(const NotaEngine* e, int32_t i) { auto* s = sectionAt(e, i); return s ? s->startBeat : 0.0; }
+double nota_engine_section_length(const NotaEngine* e, int32_t i) { auto* s = sectionAt(e, i); return s ? s->lengthBeats : 0.0; }
+const char* nota_engine_section_name(const NotaEngine* e, int32_t i) { auto* s = sectionAt(e, i); return s ? s->name.c_str() : ""; }
+NotaResult nota_engine_set_sections(NotaEngine* e, const NotaSection* sections, int32_t count, int32_t checkpoint) {
+ if (!e || count < 0 || (count > 0 && !sections)) return NOTA_ERR_INVALID_ARG;
+ std::vector<nota::Section> v;
+ v.reserve(static_cast<size_t>(count));
+ for (int32_t i = 0; i < count; ++i)
+ v.push_back({ sections[i].start_beat, sections[i].length_beats, sections[i].name_utf8 ? sections[i].name_utf8 : "" });
+ ENG(e)->setSections(std::move(v), checkpoint != 0);
+ return NOTA_OK;
+}
+
// ---- Project reset (M7-6) -------------------------------------------------
void nota_engine_reset(NotaEngine* e) {
diff --git a/tests/Nota.SmokeTest/HistoryTests.cs b/tests/Nota.SmokeTest/HistoryTests.cs
index 93df64d5..39822f33 100644
--- a/tests/Nota.SmokeTest/HistoryTests.cs
+++ b/tests/Nota.SmokeTest/HistoryTests.cs
@@ -88,7 +88,7 @@ internal static class HistoryTests
yield return (c6.TracksRenamed.Count == 1 && c6.TracksRenamed[0] == new TrackRename("Lead", "Strings")
&& c6.TracksAdded.Count == 0 && c6.TracksRemoved.Count == 0, "a renamed track reads as a rename");
- var c7 = Step(() => { e.RemoveTrack(vox); File.WriteAllText(Path.Combine(dir, "sections.json"), "[]"); });
+ var c7 = Step(() => { e.RemoveTrack(vox); e.SetSections([new SectionInfo(0, 16, "Intro")]); });
yield return (c7.TracksRemoved.SequenceEqual(["Vox"]) && c7.Other.SequenceEqual(["sections"]),
$"a removed track and edited sections are seen ({string.Join(" · ", VersionSummary.Parts(c7, Bpm))})");
diff --git a/tests/Nota.SmokeTest/ParamSectionUndoTests.cs b/tests/Nota.SmokeTest/ParamSectionUndoTests.cs
new file mode 100644
index 00000000..3f8d535b
--- /dev/null
+++ b/tests/Nota.SmokeTest/ParamSectionUndoTests.cs
@@ -0,0 +1,458 @@
+// SPDX-License-Identifier: AGPL-3.0-only
+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.
+//
+// Undo for device parameters and arrangement sections (specs/016-device-param-section-undo):
+// a parameter drag is one exact step on an effect, a MIDI effect and the instrument; the
+// automation-write touch every card sends opens it; parameter, note and section steps share one
+// ordered history; playback and loads add none; sections live in the project, undo and redo,
+// survive save / load and migrate from the old sidecar; MIDI Learn and MCP each make one step.
+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --paramundo`.
+
+using System.Text.Json.Nodes;
+using Nota.Application;
+using Nota.Application.Editing;
+using Nota.Infrastructure;
+
+namespace Nota.SmokeTest;
+
+internal static class ParamSectionUndoTests
+{
+ public static IEnumerable<(bool ok, string label)> Run()
+ {
+ foreach (var r in Gestures()) yield return r;
+ foreach (var r in Touches()) yield return r;
+ foreach (var r in OneHistory()) yield return r;
+ foreach (var r in NotEdits()) yield return r;
+ foreach (var r in Sections()) yield return r;
+ foreach (var r in SectionFiles()) yield return r;
+ foreach (var r in Sources()) yield return r;
+ }
+
+ private const int Eq8 = 0, Reverb = 2;
+
+ // ---- G1, G2: value gestures on the three parameter kinds ----------------------------
+
+ private static IEnumerable<(bool, string)> Gestures()
+ {
+ using var eng = new NotaEngine();
+ int t = eng.AddInstrumentTrack();
+ int d = eng.AddBuiltinDevice(t, Reverb);
+ int m = eng.AddMidiEffect(t, 0); // Nota Arp
+ yield return (d >= 0 && m >= 0 && eng.DeviceParamCount(t, d) > 1 && eng.MidiEffectParamCount(t, m) > 1
+ && eng.PluginParamCount(t, -1) > 1, "param undo: test track has an effect, a MIDI effect and an instrument");
+ eng.ClearUndoHistory();
+
+ eng.DeviceSetParam(t, d, 1, 0.123f); // a plain set: never a step
+ yield return (!eng.CanUndo, "param undo: a plain parameter set makes no step");
+
+ // G1 on an audio effect: 50 values, one step, exact both ways.
+ float start = eng.DeviceGetParam(t, d, 1);
+ int h = eng.BeginMixGesture(MixTarget.DeviceParam(t, d, 1));
+ for (int i = 1; i <= 50; i++) eng.DeviceSetParam(t, d, 1, 0.2f + i * 0.0119f);
+ float last = eng.DeviceGetParam(t, d, 1);
+ eng.EndMixGesture(h);
+ bool one = eng.CanUndo;
+ eng.Undo();
+ bool back = eng.DeviceGetParam(t, d, 1) == start && !eng.CanUndo;
+ eng.Redo();
+ yield return (h > 0 && one && back && eng.DeviceGetParam(t, d, 1) == last,
+ $"param undo: a 50-value effect drag is one step, undo → exactly {start}, redo → exactly {last}");
+
+ // G1 on a MIDI effect.
+ eng.ClearUndoHistory();
+ float m0 = eng.MidiEffectGetParam(t, m, 3);
+ Gesture(eng, MixTarget.MidiDeviceParam(t, m, 3), () => eng.MidiEffectSetParam(t, m, 3, m0 == 0.75f ? 0.25f : 0.75f));
+ float m1 = eng.MidiEffectGetParam(t, m, 3);
+ eng.Undo(); bool mBack = eng.MidiEffectGetParam(t, m, 3) == m0 && !eng.CanUndo;
+ eng.Redo();
+ yield return (mBack && eng.MidiEffectGetParam(t, m, 3) == m1 && m1 != m0, "param undo: a MIDI effect parameter undoes and redoes exactly");
+
+ // G1 on the instrument (normalized, device -1).
+ eng.ClearUndoHistory();
+ float p0 = eng.PluginParamGet(t, -1, 1);
+ float pWant = p0 > 0.5f ? 0.1f : 0.9f;
+ Gesture(eng, MixTarget.PluginParam(t, -1, 1), () => eng.PluginParamSet(t, -1, 1, pWant));
+ float p1 = eng.PluginParamGet(t, -1, 1);
+ eng.Undo(); bool pBack = eng.PluginParamGet(t, -1, 1) == p0 && !eng.CanUndo;
+ eng.Redo();
+ yield return (pBack && eng.PluginParamGet(t, -1, 1) == p1 && p1 != p0, $"param undo: an instrument parameter undoes and redoes exactly ({p0} ↔ {p1})");
+
+ // G2: no change, or a drag back to the start, is no step.
+ eng.ClearUndoHistory();
+ eng.EndMixGesture(eng.BeginMixGesture(MixTarget.DeviceParam(t, d, 1)));
+ float s0 = eng.DeviceGetParam(t, d, 1);
+ Gesture(eng, MixTarget.DeviceParam(t, d, 1), () => { eng.DeviceSetParam(t, d, 1, 0.9f); eng.DeviceSetParam(t, d, 1, s0); });
+ yield return (!eng.CanUndo, "param undo: a gesture without a net change makes no step");
+
+ // A target that doesn't exist is refused.
+ yield return (eng.BeginMixGesture(MixTarget.DeviceParam(t, 99, 0)) == 0 && eng.BeginMixGesture(MixTarget.DeviceParam(t, d, 9999)) == 0
+ && eng.BeginMixGesture(MixTarget.MidiDeviceParam(t, 99, 0)) == 0 && eng.BeginMixGesture(MixTarget.PluginParam(t, 5, 0)) == 0,
+ "param undo: a gesture on a missing device or parameter is refused");
+
+ // Several parameters in one step (an A/B switch), also past one gesture's 64 targets.
+ eng.ClearUndoHistory();
+ int pc = eng.PluginParamCount(t, -1);
+ var before = Enumerable.Range(0, pc).Select(i => eng.PluginParamGet(t, -1, i)).ToArray();
+ MixEdit.Step(eng, () => { for (int i = 0; i < pc; i++) eng.PluginParamSet(t, -1, i, before[i] > 0.5f ? 0.2f : 0.8f); },
+ Enumerable.Range(0, pc).Select(i => MixTarget.PluginParam(t, -1, i)).ToArray());
+ eng.Undo();
+ bool all = Enumerable.Range(0, pc).All(i => eng.PluginParamGet(t, -1, i) == before[i]);
+ yield return (all && !eng.CanUndo, $"param undo: setting all {pc} instrument parameters at once is one step");
+ }
+
+ // ---- G3, G7: the automation-write touch opens the gesture ----------------------------
+
+ private static IEnumerable<(bool, string)> Touches()
+ {
+ var buf = new float[512 * 2];
+ using var eng = new NotaEngine();
+ eng.SetBpm(120);
+ int t = eng.AddInstrumentTrack();
+ int d = eng.AddBuiltinDevice(t, Reverb);
+ int m = eng.AddMidiEffect(t, 0);
+ eng.ClearUndoHistory();
+
+ // G3: an unlatched touch on each kind is one step.
+ float v0 = eng.DeviceGetParam(t, d, 2);
+ eng.BeginAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "");
+ for (int i = 0; i < 20; i++) eng.DeviceSetParam(t, d, 2, 0.1f + i * 0.03f);
+ eng.EndAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "");
+ eng.Undo();
+ yield return (eng.DeviceGetParam(t, d, 2) == v0 && !eng.CanUndo, "param undo: a knob touch (automation write) on an effect is one step");
+
+ string pid = eng.PluginParamId(t, -1, 2);
+ float i0 = eng.PluginParamGet(t, -1, 2);
+ eng.BeginAutomationWrite(t, AutomationTarget.PluginParam, -1, -1, pid);
+ eng.PluginParamSet(t, -1, 2, i0 > 0.5f ? 0.05f : 0.95f);
+ eng.EndAutomationWrite(t, AutomationTarget.PluginParam, -1, -1, pid);
+ bool iStep = eng.CanUndo;
+ eng.Undo();
+ yield return (iStep && eng.PluginParamGet(t, -1, 2) == i0 && !eng.CanUndo, "param undo: a knob touch on the instrument is one step");
+
+ float a0 = eng.MidiEffectGetParam(t, m, 3);
+ eng.BeginAutomationWrite(t, AutomationTarget.MidiDeviceParam, m, 3, "");
+ eng.MidiEffectSetParam(t, m, 3, a0 == 0.6f ? 0.3f : 0.6f);
+ eng.EndAutomationWrite(t, AutomationTarget.MidiDeviceParam, m, 3, "");
+ bool aStep = eng.CanUndo;
+ eng.Undo();
+ yield return (aStep && eng.MidiEffectGetParam(t, m, 3) == a0 && !eng.CanUndo, "param undo: a knob touch on a MIDI effect is one step");
+
+ // A latched (hardware) write opens nothing: its source makes the step.
+ eng.BeginAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "", latch: true);
+ eng.DeviceSetParam(t, d, 2, 0.77f);
+ eng.EndAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "");
+ yield return (!eng.CanUndo, "param undo: a latched automation write makes no step of its own");
+
+ // A gesture the caller already holds and the touch on top of it are still one step.
+ eng.ClearUndoHistory();
+ float n0 = eng.DeviceGetParam(t, d, 2);
+ int h = eng.BeginMixGesture(MixTarget.DeviceParam(t, d, 2));
+ eng.BeginAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "");
+ eng.DeviceSetParam(t, d, 2, 0.31f);
+ eng.EndAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "");
+ eng.EndMixGesture(h);
+ eng.Undo();
+ bool nestedOne = eng.DeviceGetParam(t, d, 2) == n0;
+ yield return (nestedOne, $"param undo: an outer gesture plus the touch undo together in one go ({eng.DeviceGetParam(t, d, 2)}, want {n0})");
+
+ // G7: recording a touch — the lane it creates and the value are one step.
+ eng.ClearUndoHistory();
+ float r0 = eng.DeviceGetParam(t, d, 2);
+ int lanes0 = eng.AutomationLaneCount(t);
+ eng.SetAutomationRecord(true);
+ eng.Seek(0); eng.Play();
+ eng.BeginAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "");
+ for (int i = 0; i < 40; i++) { eng.DeviceSetParam(t, d, 2, 0.2f + i * 0.01f); eng.RenderOffline(buf, 512, 48000); }
+ eng.EndAutomationWrite(t, AutomationTarget.DeviceParam, d, 2, "");
+ eng.StopTransport();
+ eng.SetAutomationRecord(false);
+ int lanes1 = eng.AutomationLaneCount(t);
+ float r1 = eng.DeviceGetParam(t, d, 2);
+ eng.Undo();
+ bool undone = eng.AutomationLaneCount(t) == lanes0 && eng.DeviceGetParam(t, d, 2) == r0 && !eng.CanUndo;
+ eng.Redo();
+ yield return (lanes1 > lanes0 && undone && eng.AutomationLaneCount(t) == lanes1 && eng.DeviceGetParam(t, d, 2) == r1,
+ $"param undo: a recorded touch — lane and value — undoes and redoes as one step ({lanes0}→{lanes1} lanes)");
+ }
+
+ // ---- G4, G5: one ordered history with notes, sections and structure ------------------
+
+ private static IEnumerable<(bool, string)> OneHistory()
+ {
+ using var eng = new NotaEngine();
+ int t = eng.AddInstrumentTrack();
+ int d = eng.AddBuiltinDevice(t, Reverb);
+ int c = eng.AddMidiClip(t, 0, 4);
+ eng.ClearUndoHistory();
+
+ // notes → knob → section → knob, then undo each in reverse (#30's report: undo skipped the knob).
+ var notes1 = new[] { new NotaNote(60, 0, 1, 0.8f) };
+ eng.SetClipNotes(t, c, notes1);
+ float k0 = eng.DeviceGetParam(t, d, 1);
+ Gesture(eng, MixTarget.DeviceParam(t, d, 1), () => eng.DeviceSetParam(t, d, 1, 0.33f));
+ eng.SetSections(new[] { new SectionInfo(0, 16, "Intro") });
+ Gesture(eng, MixTarget.DeviceParam(t, d, 1), () => eng.DeviceSetParam(t, d, 1, 0.66f));
+
+ eng.Undo(); bool s3 = eng.DeviceGetParam(t, d, 1) == 0.33f && eng.Sections.Count == 1 && Notes(eng, t, c) == 1;
+ eng.Undo(); bool s2 = eng.Sections.Count == 0 && eng.DeviceGetParam(t, d, 1) == 0.33f && Notes(eng, t, c) == 1;
+ eng.Undo(); bool s1 = eng.DeviceGetParam(t, d, 1) == k0 && Notes(eng, t, c) == 1;
+ eng.Undo(); bool s0 = Notes(eng, t, c) == 0 && !eng.CanUndo;
+ yield return (s3 && s2 && s1 && s0, $"param undo: note, knob, section, knob undo in reverse order ({s3},{s2},{s1},{s0})");
+ eng.Redo(); eng.Redo(); eng.Redo(); eng.Redo();
+ yield return (Notes(eng, t, c) == 1 && eng.Sections.Count == 1 && eng.DeviceGetParam(t, d, 1) == 0.66f && !eng.CanRedo,
+ "param undo: …and redo replays them in order");
+
+ // G5: a device removed mid-gesture: the removal is the only step.
+ eng.ClearUndoHistory();
+ int d2 = eng.AddBuiltinDevice(t, Eq8);
+ eng.ClearUndoHistory();
+ int h = eng.BeginMixGesture(MixTarget.DeviceParam(t, d2, 1));
+ eng.DeviceSetParam(t, d2, 1, 0.4f);
+ eng.RemoveDevice(t, d2);
+ eng.EndMixGesture(h);
+ eng.Undo();
+ yield return (eng.TrackDeviceCount(t) == 2 && !eng.CanUndo, "param undo: a device removed mid-gesture leaves only the removal step");
+
+ // Knob, then remove the device: undo brings the device back, then its value.
+ eng.ClearUndoHistory();
+ float e0 = eng.DeviceGetParam(t, d2, 1);
+ Gesture(eng, MixTarget.DeviceParam(t, d2, 1), () => eng.DeviceSetParam(t, d2, 1, e0 == 0.25f ? 0.75f : 0.25f));
+ float e1 = eng.DeviceGetParam(t, d2, 1);
+ eng.RemoveDevice(t, d2);
+ eng.Undo(); bool devBack = eng.TrackDeviceCount(t) == 2 && eng.DeviceGetParam(t, d2, 1) == e1;
+ eng.Undo();
+ yield return (devBack && eng.DeviceGetParam(t, d2, 1) == e0, "param undo: undo restores a removed device, then its value");
+
+ // Steps on two tracks, then one of the tracks removed: each undoes in its turn.
+ eng.ClearUndoHistory();
+ int t2 = eng.AddAudioTrack();
+ int d3 = eng.AddBuiltinDevice(t2, Eq8);
+ eng.ClearUndoHistory();
+ Gesture(eng, MixTarget.DeviceParam(t, d, 1), () => eng.DeviceSetParam(t, d, 1, 0.1f));
+ Gesture(eng, MixTarget.DeviceParam(t2, d3, 1), () => eng.DeviceSetParam(t2, d3, 1, eng.DeviceGetParam(t2, d3, 1) == 0.5f ? 0.2f : 0.5f));
+ eng.RemoveTrack(t2);
+ eng.Undo(); // the removal
+ eng.Undo(); // t2's value
+ eng.Undo(); // t's value
+ yield return (eng.DeviceGetParam(t, d, 1) == 0.66f && !eng.CanUndo, "param undo: steps on two tracks and a removal undo in order");
+ }
+
+ // ---- G6 and loads: no steps ---------------------------------------------------------
+
+ private static IEnumerable<(bool, string)> NotEdits()
+ {
+ var buf = new float[512 * 2];
+ using (var eng = new NotaEngine())
+ {
+ eng.SetBpm(120);
+ int t = eng.AddInstrumentTrack();
+ int d = eng.AddBuiltinDevice(t, Reverb);
+ int lane = eng.AddAutomationLane(t, AutomationTarget.DeviceParam, d, 1);
+ eng.SetAutomationPoints(t, lane, new[] { new AutomationPoint(0, 0.1f), new AutomationPoint(8, 0.9f) });
+ eng.ClearUndoHistory();
+ float a = eng.DeviceGetParam(t, d, 1);
+ eng.Seek(0); eng.Play();
+ for (int i = 0; i < 200; i++) eng.RenderOffline(buf, 512, 48000);
+ eng.StopTransport();
+ yield return (!eng.CanUndo && eng.DeviceGetParam(t, d, 1) != a,
+ $"param undo: automation playback moves a device parameter ({a} → {eng.DeviceGetParam(t, d, 1)}) and adds no step");
+ }
+
+ using (var eng = new NotaEngine())
+ {
+ ProjectTemplate.ApplyDefault(eng);
+ int t = eng.AddInstrumentTrack();
+ int d = eng.AddBuiltinDevice(t, Reverb);
+ eng.DeviceSetParam(t, d, 1, 0.42f);
+ eng.SetSections(new[] { new SectionInfo(0, 8, "A") });
+ string dir = TempDir();
+ try
+ {
+ new ProjectStore().Save(eng, new TransportState(120, 1, false, false), dir);
+ using var e2 = new NotaEngine();
+ new ProjectStore().Load(e2, dir);
+ // Loading replays the tracks through edit ops, which the history keeps; the sections
+ // are the baseline under all of them, so no undo after a load takes them away.
+ bool kept = e2.Sections.Count == 1;
+ for (int i = 0; i < 300 && e2.CanUndo; i++) { e2.Undo(); kept &= e2.Sections.Count == 1; }
+ yield return (kept, "param undo: undoing after a load never removes the loaded sections");
+ }
+ finally { Cleanup(dir); }
+ }
+ }
+
+ // ---- US3: sections as project data ---------------------------------------------------
+
+ private static IEnumerable<(bool, string)> Sections()
+ {
+ using var eng = new NotaEngine();
+ yield return (eng.Sections.Count == 0, "sections: a new engine has none");
+ eng.ClearUndoHistory();
+
+ // create → rename → move → resize → duplicate → delete, each one step.
+ var steps = new List<SectionInfo[]>
+ {
+ new[] { new SectionInfo(0, 16, "Section 1") },
+ new[] { new SectionInfo(0, 16, "Intro") },
+ new[] { new SectionInfo(8, 16, "Intro") },
+ new[] { new SectionInfo(8, 32, "Intro") },
+ new[] { new SectionInfo(8, 32, "Intro"), new SectionInfo(40, 32, "Intro") },
+ new[] { new SectionInfo(40, 32, "Intro") },
+ };
+ foreach (var s in steps) eng.SetSections(s);
+ bool atEnd = Same(eng.Sections, steps[^1]);
+ bool reverse = true;
+ for (int i = steps.Count - 2; i >= 0; i--) { eng.Undo(); reverse &= Same(eng.Sections, steps[i]); }
+ eng.Undo(); reverse &= eng.Sections.Count == 0 && !eng.CanUndo;
+ yield return (atEnd && reverse, "sections: create, rename, move, resize, duplicate and delete undo one at a time");
+ bool forward = true;
+ foreach (var s in steps) { eng.Redo(); forward &= Same(eng.Sections, s); }
+ yield return (forward && !eng.CanRedo, "sections: …and redo replays them");
+
+ // The same list again is no step; the engine normalises what it is given.
+ eng.ClearUndoHistory();
+ eng.SetSections(steps[^1]);
+ yield return (!eng.CanUndo, "sections: setting the same list makes no step");
+ eng.SetSections(new[] { new SectionInfo(32, 8, "B"), new SectionInfo(-4, 8, "A"), new SectionInfo(4, 0, "empty"), new SectionInfo(8, double.NaN, "nan") });
+ var norm = eng.Sections;
+ yield return (norm.Count == 2 && norm[0] == new SectionInfo(0, 8, "A") && norm[1] == new SectionInfo(32, 8, "B"),
+ $"sections: stored sorted, start clamped to 0, empty spans dropped ({string.Join("; ", norm)})");
+
+ // UTF-8 names survive the boundary.
+ eng.SetSections(new[] { new SectionInfo(0, 4, "Куплет · drop ✦") });
+ yield return (eng.Sections.Count == 1 && eng.Sections[0].Name == "Куплет · drop ✦", "sections: a non-ASCII name round-trips");
+
+ // A load-style set (checkpoint off) is no step; reset clears them.
+ eng.ClearUndoHistory();
+ eng.SetSections(new[] { new SectionInfo(0, 4, "x") }, checkpoint: false);
+ bool noStep = !eng.CanUndo && eng.Sections.Count == 1;
+ eng.Reset();
+ yield return (noStep && eng.Sections.Count == 0, "sections: a baseline set makes no step and reset clears them");
+
+ // Sections survive edits that publish a new graph (a track add) and undo of those edits.
+ eng.SetSections(new[] { new SectionInfo(0, 4, "keep") }, checkpoint: false);
+ eng.ClearUndoHistory();
+ int t = eng.AddAudioTrack();
+ eng.SetTrackName(t, "x");
+ eng.Undo();
+ yield return (eng.Sections.Count == 1 && eng.Sections[0].Name == "keep", "sections: structural edits and their undo keep the sections");
+ }
+
+ private static IEnumerable<(bool, string)> SectionFiles()
+ {
+ // Save → load keeps them; the manifest holds them.
+ string dir = TempDir();
+ try
+ {
+ using var eng = new NotaEngine();
+ ProjectTemplate.ApplyDefault(eng);
+ var want = new[] { new SectionInfo(0, 16, "Intro"), new SectionInfo(16, 32, "Verse") };
+ eng.SetSections(want);
+ new ProjectStore().Save(eng, new TransportState(120, 1, false, false), dir);
+ var json = JsonNode.Parse(File.ReadAllText(Path.Combine(dir, "project.json")))!;
+ bool inManifest = json["sections"] is JsonArray arr && arr.Count == 2;
+ using var e2 = new NotaEngine();
+ new ProjectStore().Load(e2, dir);
+ yield return (inManifest && Same(e2.Sections, want), "sections: saved in project.json and loaded back");
+
+ // An older bundle: no `sections` member, a sections.json sidecar → migrated, and the
+ // next save drops the sidecar.
+ json.AsObject().Remove("sections");
+ File.WriteAllText(Path.Combine(dir, "project.json"), json.ToJsonString());
+ File.WriteAllText(Path.Combine(dir, ProjectService.LegacySectionsSidecar),
+ "[{\"Start\":4,\"Length\":8,\"Name\":\"Old\"},{\"Start\":12,\"Length\":0,\"Name\":\"bad\"}]");
+ using var e3 = new NotaEngine();
+ new ProjectStore().Load(e3, dir);
+ bool migrated = e3.Sections.Count == 1 && e3.Sections[0] == new SectionInfo(4, 8, "Old");
+ new ProjectStore().Save(e3, new TransportState(120, 1, false, false), dir);
+ bool sidecarGone = !File.Exists(Path.Combine(dir, ProjectService.LegacySectionsSidecar));
+ using var e4 = new NotaEngine();
+ new ProjectStore().Load(e4, dir);
+ yield return (migrated && sidecarGone && e4.Sections.Count == 1, "sections: an older project's sidecar is read once and removed on save");
+
+ // A corrupt sidecar is no sections, not a failed load.
+ json = JsonNode.Parse(File.ReadAllText(Path.Combine(dir, "project.json")))!;
+ json.AsObject().Remove("sections");
+ File.WriteAllText(Path.Combine(dir, "project.json"), json.ToJsonString());
+ File.WriteAllText(Path.Combine(dir, ProjectService.LegacySectionsSidecar), "{not json");
+ using var e5 = new NotaEngine();
+ new ProjectStore().Load(e5, dir);
+ yield return (e5.Sections.Count == 0, "sections: a corrupt sidecar loads as none");
+ }
+ finally { Cleanup(dir); }
+ }
+
+ // ---- US4: MIDI Learn movement and MCP -------------------------------------------------
+
+ private static IEnumerable<(bool, string)> Sources()
+ {
+ using var eng = new NotaEngine();
+ int t = eng.AddInstrumentTrack();
+ int d = eng.AddBuiltinDevice(t, Eq8);
+ eng.ClearUndoHistory();
+
+ // A controller knob on a device parameter: one step per movement.
+ float c0 = eng.DeviceGetParam(t, d, 3);
+ var knob = new MixMovement(eng, MixTarget.DeviceParam(t, d, 3), TimeSpan.FromSeconds(1));
+ knob.Touch(() => eng.DeviceSetParam(t, d, 3, 0.3f), 0);
+ knob.Touch(() => eng.DeviceSetParam(t, d, 3, 0.35f), 400);
+ knob.Poll(1400);
+ knob.Touch(() => eng.DeviceSetParam(t, d, 3, 0.6f), 3000);
+ knob.Poll(4100);
+ eng.Undo(); bool first = eng.DeviceGetParam(t, d, 3) == 0.35f;
+ eng.Undo();
+ yield return (first && eng.DeviceGetParam(t, d, 3) == c0 && !eng.CanUndo,
+ "param undo: two controller movements on a device parameter are two steps");
+
+ // MCP: the plain parameter tools and a multi-field device tool are one step each.
+ var dev = new Nota.Mcp.Tools.DeviceTools(eng, new SyncDispatch(), new NoRefresh());
+ var plug = new Nota.Mcp.Tools.InstrumentTools(eng, new SyncDispatch(), new NoRefresh());
+ eng.ClearUndoHistory();
+ float q0 = eng.DeviceGetParam(t, d, 1);
+ dev.SetDeviceParam(t, d, 1, q0 == 0.4f ? 0.6f : 0.4f).GetAwaiter().GetResult();
+ float i0 = eng.PluginParamGet(t, -1, 1);
+ plug.SetInstrumentParam(t, 1, i0 > 0.5f ? 0.2f : 0.8f).GetAwaiter().GetResult();
+ eng.Undo(); bool instBack = eng.PluginParamGet(t, -1, 1) == i0 && eng.DeviceGetParam(t, d, 1) != q0;
+ eng.Undo();
+ yield return (instBack && eng.DeviceGetParam(t, d, 1) == q0 && !eng.CanUndo,
+ "param undo: MCP set_device_param and set_instrument_param are one step each");
+
+ eng.ClearUndoHistory();
+ var bandBefore = Enumerable.Range(0, 5).Select(i => eng.DeviceGetParam(t, d, 5 + i)).ToArray();
+ dev.SetEq8Band(t, d, 2, on: true, freqHz: 1234, gainDb: 4.5, q: 2).GetAwaiter().GetResult();
+ bool changed = Enumerable.Range(0, 5).Any(i => eng.DeviceGetParam(t, d, 5 + i) != bandBefore[i]);
+ eng.Undo();
+ bool bandBack = Enumerable.Range(0, 5).All(i => eng.DeviceGetParam(t, d, 5 + i) == bandBefore[i]);
+ yield return (changed && bandBack && !eng.CanUndo, "param undo: MCP set_eq8_band (four fields) is one step");
+
+ // MCP sections round-trip, one step.
+ var proj = new Nota.Mcp.Tools.ProjectTools(eng, new SyncDispatch(), new NoRefresh());
+ eng.ClearUndoHistory();
+ var stored = proj.SetSections(new[] { new Nota.Mcp.Tools.ProjectTools.Section(16, 8, "Drop"), new Nota.Mcp.Tools.ProjectTools.Section(0, 16, "Build") })
+ .GetAwaiter().GetResult();
+ var listed = proj.ListSections().GetAwaiter().GetResult();
+ bool ok = stored.Length == 2 && stored[0].Name == "Build" && listed.SequenceEqual(stored);
+ eng.Undo();
+ yield return (ok && eng.Sections.Count == 0 && !eng.CanUndo, "sections: MCP set_sections / list_sections round-trip as one step");
+ }
+
+ // ---- helpers ------------------------------------------------------------------------
+
+ private static void Gesture(NotaEngine e, MixTarget t, Action set)
+ {
+ int h = e.BeginMixGesture(t);
+ set();
+ e.EndMixGesture(h);
+ }
+
+ private static int Notes(NotaEngine e, int t, int c) => e.GetClipNotes(t, c).Length;
+
+ private static bool Same(IReadOnlyList<SectionInfo> a, IReadOnlyList<SectionInfo> b) => a.Count == b.Count && a.SequenceEqual(b);
+
+ private static string TempDir() => Path.Combine(Path.GetTempPath(), "nota-paramundo-" + Guid.NewGuid().ToString("N"));
+
+ private static void Cleanup(string dir)
+ {
+ try { if (Directory.Exists(dir)) Directory.Delete(dir, recursive: true); } catch (IOException) { }
+ }
+}
diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.cs
index 8672d29b..9621b577 100644
--- a/tests/Nota.SmokeTest/Program.cs
+++ b/tests/Nota.SmokeTest/Program.cs
@@ -301,6 +301,14 @@ if (args.Length >= 1 && args[0] == "--mixundo")
Console.WriteLine(failures == 0 ? "MIXUNDO PASSED" : $"MIXUNDO FAILED ({failures})");
return failures == 0 ? 0 : 1;
}
+// Device-parameter and section undo alone: `--paramundo`. Also part of the full run.
+if (args.Length >= 1 && args[0] == "--paramundo")
+{
+ Console.WriteLine("-- param + section undo --");
+ foreach (var (ok, label) in ParamSectionUndoTests.Run()) Check(ok, label);
+ Console.WriteLine(failures == 0 ? "PARAMUNDO PASSED" : $"PARAMUNDO FAILED ({failures})");
+ return failures == 0 ? 0 : 1;
+}
// The project pan law alone: `--panlaw`. Also part of the full run.
if (args.Length >= 1 && args[0] == "--panlaw")
{
@@ -14661,6 +14669,9 @@ foreach (var (ok, label) in PumpPacerTests.Run()) Check(ok, label);
Console.WriteLine("-- mix undo --");
foreach (var (ok, label) in MixUndoTests.Run()) Check(ok, label);
+Console.WriteLine("-- param + section undo --");
+foreach (var (ok, label) in ParamSectionUndoTests.Run()) Check(ok, label);
+
Console.WriteLine("-- stereo map --");
foreach (var (ok, label) in StereoMeasureTests.Run()) Check(ok, label);