Nota — a free DAW for macOS, Windows and Linux. No subscription, no account — just open it and make music.
C# audioaudio-unitavaloniacpp20cross-platformdawdigital-audio-workstationdspjucelinux-audiomcp-servermidimusicmusic-productionpiano-rollplugin-hostsequencersynthesizervstvst3
(feat) The instrument as a device: select, replace, copy and move it; a Remove button on every device; instrument drops in Session (#350)
Egor Khindikaynen4d7a71104efc
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 0b58a8d6..ef0849db 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -77,8 +77,31 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.of a one-chain rack back out. Also in the device's right-click menu (**Group into rack** /**Ungroup rack**). A device with a sidechain key, automation or CV links stays where it isand the status line says why. ⌘G on tracks still groups tracks.+- **The instrument is a device you can select** (nota-daw/nota#327, nota-daw/nota#146): click+ the instrument card to select it. Its right-click menu has **Replace…** (any built-in+ instrument, an empty Instrument Rack or Drum Rack, or an installed plug-in, swapped in place+ with the clips and effects kept), **Copy**, **Cut** and **Paste** — a copied instrument,+ settings, chains and pads and all, replaces the instrument of the track it is pasted on — and+ **Delete track**.+- **Move a device to another track** (nota-daw/nota#327): **Move to track ▸** in any device's+ menu, or drag the device's header out of the Devices panel onto a track in the Arrangement or+ a column in Session view; hold ⌥ (Alt) to copy it instead. A moved device takes its+ automation along; one undo puts it back. Moving the instrument replaces the other track's+ instrument and removes its own track.+- **A Remove button on every device** (nota-daw/nota#110): a small × in each device's header,+ folded strip and rack chain card removes it; it is reachable with Tab and Enter. One undo+ brings the device back.+- **Drop instruments in Session view** (nota-daw/nota#313): an instrument or instrument preset+ dropped on a column header or slot replaces that track's instrument (on a rack it adds a+ chain or pad); dropped on an audio column it starts a new track after it, and right of the+ last column a new track at the end.+- **MCP**: `set_track_instrument` replaces a track's instrument with a built-in one (racks+ included); `move_device_to_track` moves or copies a device, the instrument included, to+ another track.### Changed+- **Delete on the instrument deletes its track**, as an instrument track always has an+ instrument; Nota asks first when the track has clips.- **A new Instrument Rack starts empty** instead of with a Nota Volt chain: drop an instrumentor a preset on it to add the first chain.- **A Mosaic in a rack chain lists the presets a Mosaic track does** in its window — the factorydiff --git a/FEATURES.md b/FEATURES.mdindex 484e3120..75f07948 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -170,7 +170,9 @@ track count and closes with Escape.Arrangement; and moving material between Session and Arrangement — the clipboard worksboth ways, and **⌘⇧C** (**Copy to Session** / **Copy to Arrangement** / **Copy toscene**) sends clips, slots or a whole scene across with notes, envelopes, warp, pitch- and gain, as one undo step.+ and gain, as one undo step. An instrument (or instrument preset) dropped from the Browser+ on an instrument column replaces its instrument (a rack gets a chain or pad); on an audio+ column or right of the last column it starts a new track.- **Modular View** — a signal-graph editor for the track's chain: MIDI FX → instrument →effects shown as nodes you can expand, bypass, duplicate, delete and reorder right on thecanvas (node positions are saved with the project), plus a **Global view** that shows@@ -234,7 +236,15 @@ track count and closes with Escape.its rotated name and on/off switch; double-click the strip to unfold. Saved with the project.- Click a device to select it: ⌘C / ⌘X / ⌘V copy, cut and paste it with all its settings(also into and out of rack chains), ⌘D duplicates it, Delete removes it; drag a header to- reorder.+ reorder. Every device header, folded strip and rack chain card has a **×** that removes it+ (also with Tab and Enter).+ - The instrument card selects too: **Replace…** swaps it for any built-in instrument, an+ empty Instrument Rack or Drum Rack, or an installed plug-in, clips and effects kept; a+ copied instrument pasted on another instrument track replaces that track's; deleting the+ instrument deletes its track (asking first when it has clips).+ - **Move to track ▸** in a device's menu, or dragging its header onto a track in the+ Arrangement or a Session column, moves it there with its automation; ⌥ copies instead.+ The instrument replaces the other track's instrument and its own track goes.---@@ -1226,8 +1236,11 @@ Coverage:star). Deleting versions stays with the user.- **Tracks**: add and remove, volume/pan/mute/solo, groups, sends.- **Instruments**: add by kind, read and write parameters (by index or by stable id), turn- on or off (`set_device_bypass` with device index -1; `get_overview` shows it); read /- shape Nota Keys in musical terms (`read_keys`, `set_keys`).+ on or off (`set_device_bypass` with device index -1; `get_overview` shows it), replace with+ another built-in or an empty rack (`set_track_instrument`); read / shape Nota Keys in+ musical terms (`read_keys`, `set_keys`).+- **Moving devices**: `move_device_to_track` moves or copies an audio effect, a MIDI effect or+ the instrument to another track, with its automation.- **Audio effects**: add, remove, reorder, bypass, parameters; load an audio file into adevice (a Nota Chamber impulse response) and read its resource text (IR names).- **MIDI clips and notes**: piano roll — add a clip, read/write/append/clear notes, movediff --git a/specs/043-instrument-device-chain/checklists/requirements.md b/specs/043-instrument-device-chain/checklists/requirements.mdnew file mode 100644index 00000000..d56201b2--- /dev/null+++ b/specs/043-instrument-device-chain/checklists/requirements.md@@ -0,0 +1,38 @@+# Specification Quality Checklist: The instrument as a first-class device in the chain++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-10-27+**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++- The three open questions (FR-005, FR-012, FR-014) were answered on 2026-10-27 and are+ recorded in the spec's Clarifications section.+- The Nota Context section names the engine as an affected area (the instrument+ clipboard and cross-track move); this is the template's required context, not a+ leak into the requirements.diff --git a/specs/043-instrument-device-chain/contracts/c-abi.md b/specs/043-instrument-device-chain/contracts/c-abi.mdnew file mode 100644index 00000000..841b2371--- /dev/null+++ b/specs/043-instrument-device-chain/contracts/c-abi.md@@ -0,0 +1,62 @@+# C ABI contract (`nota_engine.h`)++All calls: message thread only; each successful edit is one undo step (one published graph).++## Changed++```c+/* Replace the instrument on an existing instrument track with a fresh built-in `kind`.+ * kind 3 = an empty Instrument Rack, 4 = an empty Drum Rack (new in specs/043); other kinds as+ * nota_engine_add_*_track. NOTA_ERR_UNKNOWN for an unknown kind or a non-instrument track. */+NOTA_API NotaResult nota_track_set_builtin_instrument(NotaEngine* engine, int32_t track_id, int32_t kind);++/* clipboard_kind: 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument (specs/043). */+NOTA_API int32_t nota_device_clipboard_kind(const NotaEngine* engine);+```++## New++```c+/* The track's instrument on the shared device clipboard (specs/043): a full clone — every+ * param, its state, a rack's chains / pads and macros, a plug-in's state, bypass. Replaces+ * whatever the clipboard held. 1 = copied, 0 = no instrument (not an instrument track). */+NOTA_API int32_t nota_track_copy_instrument(NotaEngine* engine, int32_t track_id);++/* Replace track_id's instrument with a fresh clone of the clipboard's instrument; one undo+ * step, the clipboard kept. 0 = done, -1 nothing to paste (the clipboard holds no+ * instrument), -2 not an instrument track, -3 the clone failed (a plug-in that won't load). */+NOTA_API int32_t nota_track_paste_instrument(NotaEngine* engine, int32_t track_id);++/* Move (keep_source 0) or copy (keep_source 1) a device to another track, both tracks in one+ * undo step. family: 0 audio effect at `index`, 1 MIDI effect at `index`, 2 the instrument+ * (index ignored). at_index: position on the target, -1 = the end of its section (ignored for+ * the instrument, which replaces the target's).+ * A move takes the device's automation lanes along (index rewritten); a copy takes none. A move+ * of the instrument removes the source track. CV links and rack macro mappings to the device+ * stay with the source (dropped from a moved device). A sidechain key whose source is the+ * target track is cleared.+ * Returns the new index (>= 0; 0 for the instrument), -1 bad address or dst == src, -2 the+ * target can't take the family (an instrument / MIDI effect onto an audio, return, group or+ * master track), -3 the clone failed. *out_flags (may be NULL): bit 0 sidechain cleared,+ * bit 1 links dropped, bit 2 source track removed. */+NOTA_API int32_t nota_track_transfer_device(NotaEngine* engine, int32_t src_track_id, int32_t family,+ int32_t index, int32_t dst_track_id, int32_t at_index,+ int32_t keep_source, int32_t* out_flags);+```++## Managed mirror (`IAudioEngine`)++```csharp+bool CopyInstrument(int trackId);+int PasteInstrument(int trackId);+int TransferDevice(int srcTrackId, DeviceFamily family, int index, int dstTrackId, int atIndex,+ bool keepSource, out TransferFlags flags);+// DeviceClipboardKind() gains 3 = instrument.+```++## Smoke coverage (`InstrumentChainTests`)++Each new or changed call above is exercised: copy / paste instrument across built-in kinds+(params equal), Volt → Instrument Rack → Drum Rack → Volt via `set_builtin_instrument`, transfer+of each family with an automation lane, copy vs move, the instrument move removing its track,+the −2 refusals, the sidechain-cleared flag, and one undo restoring both tracks.diff --git a/specs/043-instrument-device-chain/contracts/mcp.md b/specs/043-instrument-device-chain/contracts/mcp.mdnew file mode 100644index 00000000..520416a6--- /dev/null+++ b/specs/043-instrument-device-chain/contracts/mcp.md@@ -0,0 +1,19 @@+# MCP contract++## `set_track_instrument` (InstrumentTools.cs) — new++- Args: `trackId: int`, `kind: int` (see `list_instrument_kinds`; 3 = Instrument Rack, 4 = Drum+ Rack, both empty).+- Replaces the track's instrument; clips, MIDI effects, audio effects and mixer stay. One undo+ step. Returns true, or an error for a non-instrument track / unknown kind.+- Description notes: plug-ins use `set_track_instrument_plugin`; there is no "delete+ instrument" — an instrument track always has one, `remove_track` deletes the track.++## `move_device_to_track` (DeviceTools.cs) — new++- Args: `trackId: int`, `chain: "audio" | "midi" | "instrument"`, `index: int` (ignored for+ "instrument"), `targetTrackId: int`, `atIndex: int = -1`, `copy: bool = false`.+- Calls `nota_track_transfer_device`. Returns `{ index, sidechainCleared, linksDropped,+ sourceTrackRemoved }`, or an error naming the refusal (−1 / −2 / −3 of the C contract).+- Description notes: moving the instrument replaces the target's instrument and removes the+ source track; automation moves along, a copy has none.diff --git a/specs/043-instrument-device-chain/contracts/ui.md b/specs/043-instrument-device-chain/contracts/ui.mdnew file mode 100644index 00000000..60a8422a--- /dev/null+++ b/specs/043-instrument-device-chain/contracts/ui.md@@ -0,0 +1,64 @@+# UI contract++## Device panel — the instrument card++- Click on its header or body background selects it (selection ring as effects); clears an+ effect or rack-chain selection.+- Right-click menu, top to bottom:+ - header (name · "Instrument"), presets as today;+ - **Replace…** ▸ submenu: Instruments (built-ins), Racks (Instrument Rack, Drum Rack),+ Plug-ins (installed instrument plug-ins) — the Browser's instrument list;+ - **Copy** ⌘C · **Cut** ⌘X · **Paste** ⌘V (enabled when the clipboard holds an instrument);+ - **Move to track ▸** — instrument tracks other than this one, by name and colour;+ - **Delete track** (danger, Delete key) — the instrument's Delete.+- Delete / Backspace with the instrument selected = **Delete track**.+- Delete track, Cut and Move to track on the instrument show, when the source track has any+ clip (arrangement or Session):+ `ConfirmWindow("Delete track", "“<name>” has clips. Delete the track with its clips?", "Delete", "Cancel")`.+ Cut's and Move's wording: "Move the instrument and delete “<name>” with its clips?" / "Move".++## Device panel — effects (audio and MIDI)++- Menu gains **Move to track ▸** under Duplicate: the tracks that can take the device (audio+ effects: any track with a chain incl. returns and the master; MIDI effects: instrument+ tracks), the current track excluded.+- Paste with the clipboard holding an instrument → status: "Paste an instrument on an+ instrument card."++## Remove control (#110)++- Every card header (full and folded): an 18×18 `×` right of the power slot (at the foot of a+ folded strip); `TextTertiary` at rest, `TextPrimary` on hover, a `BorderStrong` seam ring while+ focused — never red, which DESIGN.md keeps for overload; tooltip "Remove device", on the+ instrument "Remove track".+- Click, Enter or Space → the same action as the card's Delete. Not on Utility cards.+- Rack chain compact cards (specs/040) get the same control in their header (not on the chain's+ instrument, which is replaced from its menu); the legacy `SlotDelBtn` is the same control.++## Drag a device out of the panel++- Header drag inside the panel: unchanged (drop bar, reorder).+- Leaving the panel turns it into a system drag. Valid targets:+ - Arrangement: track rows (header ring + lane wash, as Browser drops) and the return / master+ footer rows;+ - Session: column headers and the column's slots.+- A target lights only if it can take the device and is not the source track.+- Drop = move; ⌥ (Alt) held on drop = copy. Status: "Moved <device> to <track>" / "Copied …",+ plus " · sidechain cleared" / " · macro and modulation links left on <source>" when flagged.++## Session view — Browser instrument drops (#313)++| Drop on | Instrument / instrument preset does |+|---------|-------------------------------------|+| plain instrument track: header or slot | replaces its instrument |+| Instrument Rack / Drum Rack track | adds a chain / pad (as in the Arrangement) |+| audio, return or group column | new instrument track right after the column |+| right of the last column | new instrument track at the end |++The new track is selected; one undo step each. The old status "Drop instruments onto the+arrangement." is gone.++## Shortcuts pane++- Adds: "⌥-drag a device onto a track — copy it there" and "Drag a device onto a track — move it+ there" under Devices.diff --git a/specs/043-instrument-device-chain/data-model.md b/specs/043-instrument-device-chain/data-model.mdnew file mode 100644index 00000000..ce9666b7--- /dev/null+++ b/specs/043-instrument-device-chain/data-model.md@@ -0,0 +1,68 @@+# Data Model: The instrument as a first-class device in the chain++No persisted data changes. The entities below are runtime state (engine) and UI state (managed).++## Device clipboard (engine, `Engine`)++| Field | Type | Notes |+|-------|------|-------|+| `clipDevice_` | `shared_ptr<Device>` | existing (#238): an audio effect clone |+| `clipMidi_` | `shared_ptr<MidiDevice>` | existing: a MIDI effect clone |+| `clipInstrument_` | `shared_ptr<Instrument>` | **new**: an instrument clone (`cloneInstrument`), bypass copied |++- Exactly one is set; a copy of any family resets the other two.+- `deviceClipboardKind()`: 0 empty, 1 audio effect, 2 MIDI effect, **3 instrument**.+- Paste always inserts a fresh clone, so the clipboard can be pasted again and survives a cut+ (the source track's removal) and later edits of the source.+- Not persisted; not part of undo.++## Track instrument (engine, `Track::instrument`)++- Never null on an `Instrument` track (clarification Q1). Replace goes through+ `replaceTrackInstrument` (one snapshot). Deleting it is deleting the track.+- Allowed new instruments: built-in kinds incl. **3 Instrument Rack, 4 Drum Rack** (fresh,+ empty), hosted plug-ins, a clipboard / transfer clone.++## Device transfer (engine, one call → one snapshot)++| Input | Meaning |+|-------|---------|+| `srcTrack`, `family` (0 audio effect, 1 MIDI effect, 2 instrument), `index` | the device (index ignored for the instrument) |+| `dstTrack`, `atIndex` | target; −1 = end of the matching section; ignored for the instrument |+| `keepSource` | 0 move, 1 copy (⌥-drag) |++| Output (return / flags) | Meaning |+|-------------------------|---------|+| ≥ 0 | the device's index on the target (0 for the instrument) |+| −1 | bad address / same track |+| −2 | the target can't take this family (audio / return / group / master for an instrument or MIDI effect) |+| −3 | the clone failed (a plug-in that won't load a second instance) |+| flag `sidechainCleared` | the key pointed at the target and was cleared |+| flag `linksDropped` | CV links / rack macro mappings to the device stayed behind |+| flag `sourceTrackRemoved` | the instrument moved and its track was removed |++State transitions in the published graph (move):++```text+source.devices[index] → removed (lanes on it → handed over; later lanes shift down)+target.devices[atIndex] ← clone (target lanes at/after atIndex shift up; handed-over lanes rewritten to atIndex)+instrument: target.instrument ← clone; source track removed+```++Copy (`keepSource`): the target side only; no lanes handed over.++## UI selection (managed, `DeviceChainView`)++- `_selChainKind` ∈ {Effect, Midi, **Instrument**}; `_selDeviceIndex` = −1 for the instrument+ when selected (a separate `_instrumentSelected` flag keeps "nothing selected" distinct).+- Mutually exclusive with `_rackSel` (specs/042), as today.++## Out-of-panel drag payload (managed, new `DeviceDrag`)++| Field | Type | Notes |+|-------|------|-------|+| `Current` | `(int TrackId, ChainKind Kind, int Index)?` | set while a device header drag is outside the panel |+| `IsActive` | `bool` | `Current is not null` |++- Set just before `DragDrop.DoDragDropAsync`, cleared in `finally` (as `BrowserView.CurrentDrag`).+- A target accepts when `CanTake(targetTrack, Kind)` and `targetTrack != TrackId`.diff --git a/specs/043-instrument-device-chain/plan.md b/specs/043-instrument-device-chain/plan.mdnew file mode 100644index 00000000..ef3f486c--- /dev/null+++ b/specs/043-instrument-device-chain/plan.md@@ -0,0 +1,146 @@+# Implementation Plan: The instrument as a first-class device in the chain++**Branch**: `feat/instrument-device-chain` | **Date**: 2026-10-27 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/043-instrument-device-chain/spec.md`++## Summary++The track's instrument card becomes selectable and gets Replace…, Copy, Cut, Paste, Delete and+Move to track ▸; deleting it deletes the track (confirmed when the track has clips). Every+device header gets a visible Remove (×) control. Any device can move (or, with ⌥, copy) to+another track from its menu or by dragging its header onto a track header in the Arrangement+or Session view, in one undo step that carries its automation. Session view takes instrument+drops: on a column to replace, right of the last column to add a track.++Engine: the shared device clipboard gains an instrument family (reusing `cloneInstrument`), one+`replaceTrackInstrument` path (racks allowed as the new instrument), and a single-publish+`transferDevice` for cross-track moves. Managed: selection / menus / Remove control in+`DeviceChainView`, a `DeviceDrag` payload for drags out of the panel, drop targets in+`ArrangementView` and `SessionView`, `DeviceInsertService.DropOnSession` and a forced-replace+placement, two MCP tools. See [research.md](research.md).++## Nota: Read Before Planning++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-5 (each edit publishes one+ immutable graph), AR-6 (nothing new on the audio thread), AR-7 (only `nota_engine.h`).+- **UI work** → [`DESIGN.md`](../../DESIGN.md) and the `nota-design` skill (the Remove control,+ the instrument selection ring, drop rings on headers).+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).++## Technical Context++**Language/Version**: C++20 (engine), C# / .NET 10 + Avalonia (app, presentation, MCP)++**Primary Dependencies**: None new++**Storage**: None new — moved / pasted devices are saved like any other; the clipboard is not persisted++**Audio-Thread Impact**: None on the audio thread itself. Every edit builds a new graph on the+message thread and publishes it once (AR-5); a cross-track move publishes both tracks in the+same snapshot, so the device never plays on two tracks or none. Old instruments are released by+the existing snapshot reclamation, never on the audio thread (AR-6).++**Testing**: `tests/Nota.SmokeTest` (new `InstrumentChainTests.cs`, engine through the C ABI);+UI checked in the running app per [quickstart.md](quickstart.md)++**Target Platform**: macOS, Windows, Linux desktop++**Project Type**: Desktop app (native engine + managed UI)++**Performance Goals**: An instrument replace / move during playback: no dropout on other tracks+(SC-006); the edit itself under one UI frame plus the instrument's own construction time++**Constraints**: One undo step per user action (FR-008, SC-005); the macOS DnD single-item rule+(R5)++**Scale/Scope**: ~3 engine methods + 4 C ABI calls; ~8 managed files touched; 2 MCP tools; 1 smoke file++## Constitution Check++*GATE: Must pass before Phase 0 research. Re-check after Phase 1 design.*++| Principle | Status | Notes |+|-----------|--------|-------|+| I. Real-time audio safety | Pass | Message-thread graph edits, one publish each (R2, R4); no audio-thread code changes |+| II. Boundary discipline | Pass | Four new C functions in `nota_engine.h` (contracts/c-abi.md); no JUCE outside `pluginhost/` |+| III. Licensing hygiene | Pass | New files carry the SPDX header; no dependencies |+| IV. Verification gate | Pass | `InstrumentChainTests` covers every new C ABI call; `scripts/build.sh` before the PR |+| V. One logical change | Pass, noted | Four issues, one theme: the device chain's instrument and device lifecycle share one replace / transfer path |+| VI. Docs in sync | Planned | CHANGELOG `[Unreleased]`, FEATURES.md (nota-features), user docs (nota-docs), Shortcuts pane for ⌥-drag (nota-shortcuts) |+| VII. Spec-first | Pass | spec.md with clarifications, this plan, tasks.md next |+| VIII. Rules not weakened | Pass | — |++Post-design re-check (after Phase 1): unchanged — the contracts add no audio-thread work and+cross the boundary only through the C ABI.++## Project Structure++### Documentation (this feature)++```text+specs/043-instrument-device-chain/+├── spec.md+├── plan.md # this file+├── research.md # R1–R9+├── data-model.md # clipboard families, transfer, drag payload+├── quickstart.md # end-to-end checks in the app + smoke+├── contracts/+│ ├── c-abi.md # new nota_engine.h calls+│ ├── ui.md # menus, Remove control, drops, confirmation+│ └── mcp.md # set_track_instrument, move_device_to_track+├── checklists/requirements.md+└── tasks.md # /speckit-tasks+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # + copy/paste instrument, transfer device; set_builtin_instrument takes 3/4+└── src/+ ├── abi/nota_engine_device.cpp # C wrappers+ └── engine/+ ├── Engine.h # clipInstrument_, replaceTrackInstrument, transferDevice+ ├── Engine_Devices.cpp # clipboard family 3, replace path, transfer+ └── Engine_Automation.cpp # lane hand-over helper for transfer++src/managed/+├── Nota.Application/Engine/IAudioEngine.cs # + CopyInstrument, PasteInstrument, TransferDevice+├── Nota.Infrastructure/Interop/ # NativeMethods.Devices.cs, NotaEngine.Devices.cs+├── Nota.Presentation/DeviceInsertService.cs # InsertPlacement.ReplaceInstrument, DropOnSession+├── Nota.App/+│ ├── DeviceChainView.Clipboard.cs # instrument selectable, menu: Replace…, Move to track ▸, Delete → track+│ ├── DeviceChainView.Shell.cs # Remove control in the header+│ ├── DeviceChainView.Fold.cs # Remove control on the folded strip+│ ├── DeviceChainView.Instruments.cs # instrument card: CanDelete, selection ring, drag hook+│ ├── DeviceDrag.cs # new: the out-of-panel drag payload (R5)+│ ├── ArrangementView.cs # device drops on rows / footer+│ ├── SessionView.Grid.cs # instrument + device drops on headers, slots, the area right of the last column+│ ├── MainWindow.Dnd.cs # OnSessionDrop instruments, OnDeviceDropOnTrack, delete-track wiring+│ ├── DeviceCards/Rack/RackCardView.cs # SlotDelBtn restyled to match+│ └── PreferencesWindow (Shortcuts list) # ⌥-drag gesture+└── Nota.Mcp/Tools/ # InstrumentTools.cs (set_track_instrument), DeviceTools.cs (move_device_to_track)++tests/Nota.SmokeTest/+├── InstrumentChainTests.cs # new+└── Program.cs # run it; --instrument-chain+```++**Structure Decision**: The existing engine / managed split. Engine work stays in the device+files beside the #238 clipboard; UI work stays in the `DeviceChainView` partials plus the two+views that already take Browser drops.++## Phases (for /speckit-tasks)++1. **Engine foundation** — `replaceTrackInstrument`, racks in `setTrackBuiltinInstrument`,+ instrument clipboard family, `transferDevice` with lane hand-over; C ABI; interop; smoke tests.+2. **US1 (P1)** — instrument selectable; Replace…, Copy, Cut, Paste, Delete (→ track, confirmed).+3. **US2 (P1)** — Remove control on full and folded cards, rack compact cards restyled.+4. **US3 (P2)** — Session instrument drops (headers, slots, right of last column).+5. **US4 (P2)** — Move to track ▸ menu; drag onto Arrangement / Session headers, ⌥ = copy.+6. **MCP, docs, shortcuts, CHANGELOG, FEATURES; build + smoke.**++## Complexity Tracking++No constitution violations.diff --git a/specs/043-instrument-device-chain/quickstart.md b/specs/043-instrument-device-chain/quickstart.mdnew file mode 100644index 00000000..81a802d9--- /dev/null+++ b/specs/043-instrument-device-chain/quickstart.md@@ -0,0 +1,42 @@+# Quickstart: validating the feature++## Prerequisites++- `scripts/build.sh` (Release engine in `build/`, see the engine-build-dirs note in BUILD.md).+- Run the app with an isolated data dir: `NOTA_DATA_DIR=/tmp/nota-043 <app>`.++## Engine (smoke)++```bash+dotnet run --project tests/Nota.SmokeTest -- --instrument-chain+```++Expected: every `InstrumentChainTests` check passes (see [contracts/c-abi.md](contracts/c-abi.md)+§ Smoke coverage). `scripts/build.sh` runs it with the full suite.++## In the app++1. **Select / Replace (US1)** — New project, add a Nota Volt track with a MIDI clip. Click the+ Volt card: selection ring. Right-click → Replace… → Nota Keys: the clip plays Keys. ⌘Z: Volt+ back with its settings. Replace… → Instrument Rack: an empty rack card; ⌘Z.+2. **Copy / Paste instrument** — Tweak Volt's cutoff, ⌘C; select another instrument track's card,+ ⌘V: it is a Volt with the same cutoff; ⌘Z restores that track's own instrument.+3. **Delete → track** — Select the instrument, press Delete: confirmation (track has a clip) →+ Delete: track gone. ⌘Z: track, clip and instrument back. On a track without clips: no prompt.+4. **Remove control (US2)** — Add EQ-8, a plug-in effect, an Audio Effect Rack; fold one. Each+ header (and the folded strip) shows ×; Tab to it, Enter removes; three ⌘Z restore all.+ Rack chain compact cards show the same ×. Check all four themes.+5. **Session drops (US3)** — Session view: drop Nota Volt right of the last column → new track;+ drop Nota Keys on its header → replaced; drop a drum kit preset on an audio column → new+ track after it; drop an instrument on a Drum Rack column → a new pad. ⌘Z each.+6. **Move (US4)** — Automate a reverb's Mix on track 1. Menu → Move to track ▸ Track 2: it lands+ at the end of track 2's effects with its lane. ⌘Z: back on track 1 with the lane. Drag the+ reverb's header out onto track 3's header in the Arrangement: moved. ⌥-drag onto track 4 in+ Session: copied, track 3 keeps its own. Drag Volt's card onto another instrument track's+ header: that track now plays Volt, the source track is gone after the prompt; one ⌘Z+ restores both.+7. **Refusals** — Drag a MIDI effect over an audio track header: no highlight. Paste an+ instrument with an effect selected: status says why.+8. **MCP** — `set_track_instrument` and `move_device_to_track` against a running app do the same+ as steps 1 and 6.+9. **Playback** — Repeat 1 and 6 while the project plays: no dropout on other tracks.diff --git a/specs/043-instrument-device-chain/research.md b/specs/043-instrument-device-chain/research.mdnew file mode 100644index 00000000..8624a267--- /dev/null+++ b/specs/043-instrument-device-chain/research.md@@ -0,0 +1,138 @@+# Research: The instrument as a first-class device in the chain++Findings from the code on `develop` (a85331b), one decision per unknown in the plan's+Technical Context.++## R1. Copying an instrument with its full state++- **Decision**: Reuse `Engine::cloneInstrument(const Track&)` (Engine_Devices.cpp), the clone+ `duplicateTrack` / `deepCloneTrack` already use, and keep the result on the shared device+ clipboard as a third family: `clipInstrument_` beside `clipDevice_` / `clipMidi_`;+ `deviceClipboardKind()` returns 3 for it. Bypass is copied as `deepCloneTrack` does.+- **Rationale**: "Duplicate track keeps every built-in instrument's params + state" is already+ covered by `DeviceCopyTests.DuplicateInstruments`; racks and hosted plug-ins clone themselves+ through `Instrument::clone()`. One clipboard keeps the rule from #238 / specs/042 that a new+ copy replaces whatever was copied before.+- **Alternatives considered**: A managed-side state blob round-trip (`get_state` / `set_state`)+ — rejected: built-in synths keep part of their state in params, racks in children, and+ `cloneInstrument` already gets all of it right.++## R2. Replacing a track's instrument (Paste, Replace…, Session drop, move target)++- **Decision**: One engine path, `Engine::replaceTrackInstrument(trackId, std::shared_ptr<Instrument>)`:+ clone the track, swap `instrument`, close the old instrument's editor, `republishWithTrack`+ (one undo step), `recomputePdc`. `setTrackBuiltinInstrument`, `setTrackInstrumentPlugin` and+ the new paste call go through it. `setTrackBuiltinInstrument` also accepts kinds 3 / 4 and+ builds an empty `RackInstrument` / `DrumRack` the way `addInstrumentRackTrack` /+ `addDrumRackTrack` do, so **Replace… → Instrument Rack / Drum Rack** works.+- Managed: `DeviceInsertService.CanReplaceInstrument` refuses rack tracks today ("never swap an+ Instrument / Drum Rack in place") because a Browser drop on a rack adds a chain / pad. That+ stays the rule for **drops**; Replace…, Paste and a move target pass a new+ `InsertPlacement.ReplaceInstrument` that swaps even a rack.+- **Automation on the replaced instrument**: unchanged from today's Browser replace — lanes stay+ on the track (a built-in → built-in of the same kind keeps working; others read nothing). A+ moved instrument's own lanes are handled in R4.+- **Alternatives considered**: Building replace in managed code from remove + add — rejected:+ it would be two snapshots and lose the track's place in the chain.++## R3. Deleting the instrument = deleting the track++- **Decision**: Delete / Remove control / Cut on the instrument call the Arrangement's existing+ `DeleteTracks` path (`ArrangementView.Tracks.cs`, engine `remove_tracks`), reached through a+ new `DeviceChainView.TrackDeleteRequested` event that MainWindow wires to the Arrangement.+ Before it, a `ConfirmWindow` ("Delete track" / "Delete" / "Cancel") when the track has clips+ (arrangement or Session).+- **Rationale**: Clarification Q1. No new engine state; the selection and refresh logic of+ `DeleteTracks` stays the one place that knows how to drop a track.+- **Note**: Delete Track from the header menu stays unconfirmed (out of scope; the+ confirmation is for the device panel route, where removing a track is less expected).++## R4. Moving a device to another track in one undo step++- **Decision**: New engine call `transferDevice(srcTrack, family, index, dstTrack, atIndex,+ keepSource)` that builds **one** new graph with both tracks changed and publishes it once:+ - a move hands the device object itself over (a plug-in that won't load twice still moves, a+ Reverb keeps its tail); a copy, or a device whose settings must change on the way (a key on+ the target, an Arp's CC target), is cloned so the object in undo history is never edited;+ - audio effect / MIDI effect: insert on the target+ at `atIndex` (−1 = end), and unless `keepSource` remove it from the source+ (`remapAutomationAfterDeviceChange` + `remapCvLinksAfterDeviceChange` on the source, the+ same calls `removeDevice` makes);+ - the instrument: replace the target's instrument (R2), and unless `keepSource` drop the+ source track from the graph (as `removeTrack`, editors closed);+ - automation: when moving (not copying), the source lanes that target the device+ (`DeviceParam` / `PluginParam` with its index, `MidiDeviceParam`; for the instrument+ `PluginParam` with `deviceIndex < 0` and the instrument's params) move to the target with+ `deviceIndex` rewritten to the new position; the target's lanes after the insert point shift+ as in `insertDeviceClone`;+ - a sidechain key whose source is the target track is cleared (the device would key off+ itself); result flags tell the UI which status note to show;+ - CV links and rack macro mappings to the device stay behind (they belong to the source track)+ — `remapCvLinksAfterDeviceChange` drops them as it does for a removed device.+- **Rationale**: A managed undo group around copy + paste + remove would work for effects, but+ could not carry automation lanes, and two publishes of a moving instrument would briefly+ sound it on two tracks. One publish is atomic for the audio thread (AR-5).+- **Alternatives considered**: Managed `BeginUndoGroup` + existing calls — rejected for the+ reasons above; a dedicated "swap" — not needed (clarification Q2: replace).++## R5. Dragging a device card onto a track header++- **Decision**: Keep the in-panel drag as it is (pointer capture, drop bar). When the pointer+ leaves the device panel's bounds during a header drag, hand over to a system drag:+ `DragDrop.DoDragDropAsync` with the single native text sentinel and the payload in a static,+ the pattern `BrowserView.DragItemAsync` uses (one pasteboard item, so macOS's NSDragging+ session doesn't crash). The press args are kept from `PointerPressed`, as BrowserView does.+ A new `DeviceDrag` static (`Current`: track, family, index) is what targets check.+- Targets: Arrangement — `OnLaneDragOver` / `OnLaneDrop` (rows, with the existing+ `_headerDropRing`) and the footer (returns); Session — `ColumnHeader` and the slot grid of a+ column. A target lights only when it can take the family (instrument / MIDI effect →+ instrument tracks; audio effect → any track with a chain) and isn't the source track.+ ⌥ (Alt) on drop → `keepSource` (copy).+- **Rationale**: Avalonia's DnD is the only way across views; the in-process static avoids a+ custom data format (the macOS crash noted in BrowserView).+- **Alternatives considered**: Hit-testing the whole window during a captured pointer drag —+ rejected: the Arrangement / Session would need their own hover code paths for a second kind+ of drag.++## R6. Session view instrument drops++- **Decision**: `OnSessionDrop`'s `default` branch calls a new `DeviceInsertService.DropOnSession(item,+ trackId)`: on a plain instrument track → `TryReplaceInstrument`; on a rack → a chain / pad+ (same as `RouteToTrack` for racks); otherwise a new instrument track placed right after the+ column (`PlaceNewTrack`) or at the end when `trackId <= 0`. Presets keep their current routing+ (`ApplyPreset` with `InPlace`).+- Targets: the existing slot-grid handler (`SessionView.Grid.cs:358`), plus new drop handlers on+ `ColumnHeader` and on the empty area right of the last column (trackId = −1). The hover look is+ the grid's existing `_dropHover` wash; the header uses the same ring the Arrangement shows.+- The "Drop instruments onto the arrangement." strings in `MainWindow.Dnd.cs` and+ `DeviceInsertService.cs:295` go away.++## R7. The Remove control++- **Decision**: An 18×18 icon button (`GlyphKind.Close`, `TextTertiary` → `TextPrimary` on hover — not+ `Danger`: DESIGN.md keeps red for overload and makes a destructive key an ordinary one,+ tooltip "Remove device" / "Remove track" on the instrument) in the card header to the right of+ the power slot, built once in `BuildCardShell` (`DeviceChainView.Shell.cs`) and in+ `FoldedStrip` (`DeviceChainView.Fold.cs`), so built-ins, plug-ins and racks get it from the same+ code (`DeviceCardKit.RemoveButton`). It is `Focusable`, activates on Enter / Space, and is+ skipped for `Utility` cards. The rack chain compact cards get the same control; the legacy+ `SlotDelBtn` now returns it.+- **Rationale**: One place, every card type (SC-002). `DESIGN.md`: the accent stays for live /+ chosen state, so the control is neutral until hovered.++## R8. MCP++- **Decision**: New tools `set_track_instrument(trackId, kind)` (built-in replace, racks+ included — plug-ins keep `set_track_instrument_plugin`), `copy_instrument` / `paste_instrument`+ are not added (the AI has no clipboard workflow); `move_device_to_track(trackId, chain:+ "audio"|"midi"|"instrument", index, targetTrackId, atIndex = -1, copy = false)`. Deleting the+ instrument is `remove_track` (documented in the tool description).++## R9. Tests++- **Decision**: A new smoke file `tests/Nota.SmokeTest/InstrumentChainTests.cs` (run from+ `Program.cs` like `DeviceCopyTests`, also alone with `--instrument-chain`): instrument copy →+ paste across kinds keeps params; replace to and from racks; move audio effect / MIDI effect+ with an automation lane; move instrument removes the source and replaces the target, one undo+ restores both; `keepSource` leaves the source and carries no lanes; sidechain cleared when the+ target is the key. UI behaviour is checked in the app (quickstart).diff --git a/specs/043-instrument-device-chain/spec.md b/specs/043-instrument-device-chain/spec.mdnew file mode 100644index 00000000..eea07ad4--- /dev/null+++ b/specs/043-instrument-device-chain/spec.md@@ -0,0 +1,228 @@+# Feature Specification: The instrument as a first-class device in the chain++**Feature Branch**: `feat/instrument-device-chain`++**Created**: 2026-10-27++**Status**: Draft++**Input**: User description: "The instrument becomes a first-class device in the track's device chain (milestone 0.58.1, issues nota-daw/nota#146, #327, #110, #313). (1) #327 + #146 — The instrument card is selectable like audio/MIDI effects (accent border). Copy / cut / paste / delete work on it where they make sense. Its context menu gets Delete and Replace… (open question: does deleting the instrument leave an empty instrument track that a new instrument can be dropped onto, or remove the whole track?). Any selected device — instrument, audio effect or MIDI effect — can be moved to another track directly (e.g. "Move to track ▸" in the context menu and/or dragging the card onto another track), without a cut / switch track / paste round-trip; settings, automation and macro mappings travel where possible, each move is one undo step. (2) #110 — A compact, clearly labelled Remove device control in device headers, distinct from bypass and the plug-in window close; keyboard accessible; consistent across built-in devices, plug-ins and racks; removal is undoable with settings and connections preserved. (3) #313 — Session view: dropping an instrument (built-in or plug-in, also an instrument preset) onto a column header or the empty area right of the last column creates a new instrument track with it; dropping it onto a track's column/slots replaces that track's instrument. All of these share one path for removing and replacing a track's instrument, undoable in one step."++Issues: nota-daw/nota#146, nota-daw/nota#327, nota-daw/nota#110, nota-daw/nota#313.++## Clarifications++### Session 2026-10-27++- Q: What does Delete on the instrument do — leave an empty instrument track, or remove the whole track? → A: Remove the whole track (with a confirmation when the track has clips). Cut and Move of the instrument therefore also remove the source track.+- Q: When an instrument is moved or pasted onto a track that already has one, replace or swap? → A: Replace; the target's old instrument is gone and comes back on Undo.+- Q: Move to another track: menu only, or also by dragging? → A: Both — **Move to track ▸** in the device's menu, and dragging the card's header onto a track header in the Arrangement or Session view (⌥ while dropping copies instead of moving).++## 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+- [x] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++Today an instrument track always has an instrument: the engine can replace it (built-in or+plug-in), and the device clipboard copies only audio and MIDI effects. An instrument track+keeps that rule (deleting the instrument deletes the track, see Clarifications). Copying+and moving an instrument between tracks likely needs engine work (an instrument's full+state, rack contents and plug-in state, taken across tracks in one undo step). The plan+decides.++**Nota docs to keep in mind** *(links relative to `specs/<slug>/`, where this file lands)*:+[`ARCHITECTURE.md`](../../ARCHITECTURE.md) (AR rules),+[`CONTRIBUTING.md`](../../CONTRIBUTING.md) (licensing, dependency policy, PR+expectations), [`BUILD.md`](../../BUILD.md), [`DESIGN.md`](../../DESIGN.md),+[`FEATURES.md`](../../FEATURES.md).++## User Scenarios & Testing *(mandatory)*++### User Story 1 - Select, delete and replace the instrument (Priority: P1)++In a track's device chain the user clicks the instrument card and it is selected the same way+an effect is (accent border). Its right-click menu offers **Replace…** and **Delete**, and+Delete / Backspace work on it as on an effect. Replace… opens a picker of instruments+(built-in and plug-ins); the chosen one takes the old one's place in one undo step. Delete+removes the whole track (FR-005).++**Why this priority**: The instrument is the one device the user can't act on directly+today (#146, #327). Replacing or removing it means dragging from the Browser or deleting the+whole track.++**Independent Test**: On a Nota Volt track, click the Volt card: it shows as selected.+Pick **Replace… → Nota Keys**: the track now plays Keys; one Undo brings Volt back with its+settings. Press Delete with the instrument selected and confirm: the track is removed; one Undo+restores it with its clips.++**Acceptance Scenarios**:++1. **Given** an instrument track, **When** the user clicks the instrument card's header or empty body area, **Then** the card shows the selection border and any selected effect is deselected.+2. **Given** a selected instrument, **When** the user picks **Replace…** and chooses another instrument, **Then** the new instrument plays the track's clips and MIDI effects unchanged; one Undo restores the old instrument with its settings.+3. **Given** a selected instrument, **When** the user presses Delete or picks **Delete**, **Then** a confirmation appears if the track has clips, and on confirm the whole track is removed, as Delete Track does; one Undo restores the track with its instrument, settings, clips, automation and links. A track without clips is removed without asking.+4. **Given** the instrument is a Drum Rack or Instrument Rack, **When** it is replaced or deleted, **Then** its whole contents go with it and come back on Undo.+5. **Given** a selected instrument, **When** the user presses ⌘C then selects another instrument track's instrument and presses ⌘V, **Then** the target's instrument is replaced by a copy with identical settings, in one undo step.++---++### User Story 2 - A visible Remove control on every device header (Priority: P1)++Every removable device's header shows a small Remove (×) control, separate from the on/off+switch and from a plug-in's "open editor" control. Clicking it removes the device, the same+as Delete in its menu. It has a tooltip ("Remove device"), is reachable with the keyboard and+looks the same on built-in devices, plug-ins and racks, in every theme.++**Why this priority**: Requested on Discord (#110); today removal is hidden in the+right-click menu or behind selection + Delete, which new users don't find.++**Independent Test**: Add an EQ-8, a plug-in effect and an Audio Effect Rack to a track.+Each header shows the Remove control; clicking each removes that device; three Undos bring+all three back with their settings.++**Acceptance Scenarios**:++1. **Given** any audio effect, MIDI effect, rack or plug-in card, **When** the user clicks its Remove control, **Then** the device is removed and one Undo restores it with its settings, automation, sidechain key and macro / modulation links.+2. **Given** the instrument card, **When** the user clicks its Remove control, **Then** the result is the same as Delete in User Story 1 (the track is removed, with a confirmation when it has clips); its tooltip says "Remove track".+3. **Given** a folded device strip, **When** the user looks at it, **Then** the Remove control is still reachable (on the strip or its hover state).+4. **Given** keyboard navigation in the device panel, **When** the Remove control has focus and the user presses Enter or Space, **Then** the device is removed.+5. **Given** a device inside a rack chain, **When** the user looks at its compact card, **Then** it offers the same Remove control as the track chain's cards.++---++### User Story 3 - Drop an instrument in Session view (Priority: P2)++In Session view the user drags an instrument (built-in, plug-in, or an instrument preset)+from the Browser. Dropped on an instrument track's column header or any of its slots, it+replaces that track's instrument. Dropped on the empty area right of the last column (or on+an audio track's column), it creates a new instrument track with that instrument. Racks+follow the Arrangement's rules: dropping on a rack track adds a chain / pad instead of+replacing the rack.++**Why this priority**: A user report (#313). Session view only shows "Drop instruments onto+the arrangement.", so Session-first users have to switch views to build a set.++**Independent Test**: In Session view, drop Nota Volt right of the last column: a new+track appears with Volt. Drop Nota Keys on that column's header: the track now plays Keys.+Undo twice: back to the original set.++**Acceptance Scenarios**:++1. **Given** Session view, **When** the user drops a built-in instrument right of the last column, **Then** a new instrument track with that instrument is added at the end and selected; one Undo removes it.+2. **Given** an instrument track's column, **When** the user drops an instrument on its header or any of its slots, **Then** the track's instrument is replaced, its clips untouched; one Undo restores it.+3. **Given** an instrument preset (factory, user, Mosaic pack or drum kit), **When** dropped the same ways, **Then** the instrument arrives with the preset loaded.+4. **Given** a plug-in instrument, **When** dropped, **Then** it behaves as a built-in one; if the plug-in fails to load, nothing changes and the status line says so.+5. **Given** an audio track's column, **When** the user drops an instrument on it, **Then** a new instrument track is created right after it (an audio track can't take an instrument).+6. **Given** an Instrument Rack or Drum Rack track, **When** an instrument is dropped on its column, **Then** it is added as a chain / pad, as in the Arrangement.+7. **Given** a drag is in progress over Session view, **When** it hovers a valid target, **Then** the target is highlighted the same way as other Session drops.++---++### User Story 4 - Move a device to another track (Priority: P2)++The user moves the selected device — instrument, audio effect or MIDI effect — to another+track directly, without Cut, switching tracks and Paste. The device's menu has+**Move to track ▸** listing the tracks that can take it; picking one moves it there in one+undo step, with its settings. Dragging the card's header onto a track header in the+Arrangement or Session view does the same (FR-014); holding ⌥ on drop copies instead.++**Why this priority**: #327. Today it takes Cut, a track switch and Paste, and the+instrument can't be cut at all.++**Independent Test**: On track 1, pick a reverb's **Move to track ▸ Track 2**: it leaves+track 1 and lands at the end of track 2's effects with the same settings. One Undo puts it+back on track 1 in its old position.++**Acceptance Scenarios**:++1. **Given** a selected audio effect, **When** the user picks **Move to track ▸ X**, **Then** it is removed from its track and appended to X's audio effects with the same parameters and state; one Undo reverts both tracks.+2. **Given** a selected MIDI effect, **When** moved, **Then** only instrument tracks are offered and it lands at the end of the target's MIDI effects.+3. **Given** the selected instrument, **When** moved to instrument track X, **Then** X's instrument is replaced by it (FR-012) and the source track is removed (FR-005), after a confirmation when the source has clips; one Undo restores both tracks.+4. **Given** automation lanes on the moved device's parameters, **When** it moves, **Then** the lanes move with it to the target track.+5. **Given** a moved device with a sidechain key, **When** the target track is its own key source, **Then** the key is cleared and the status line says so.+6. **Given** a device that is mapped from a rack macro or a modulation source on the source track, **When** moved, **Then** those links are dropped (they belong to the source track) and come back on Undo.+7. **Given** a device card being dragged, **When** it hovers a track header in the Arrangement or Session view that can take it, **Then** the header highlights; on drop the device moves there (with ⌥ held, a copy lands there and the source is untouched). A header that can't take it offers no drop.++---++### Edge Cases++- **Audio, return, group and master tracks** take audio effects but no instrument or MIDI effects; Move to track ▸ lists only the tracks that can take the device.+- **A plug-in instrument copied or moved** carries its plug-in state; if it fails to load on the target, nothing changes and the status line says so.+- **Deleting / replacing the instrument while notes sound** stops those notes; nothing hangs.+- **The instrument is folded**: the folded strip is selectable and its Remove control works.+- **Cut on the instrument**: puts a copy on the clipboard and removes the track (confirmed when it has clips); Paste on another instrument track replaces its instrument.+- **The last track in the project**: deleting its instrument removes it, as Delete Track already does for the last track.+- **Dragging the instrument onto a track header without ⌥** from a track with clips: the same confirmation as the menu.+- **The Remove control in the instrument's nested Drum Rack window** removes pad devices, not the rack.+- **Typing in a rename box or value entry**: Delete / Backspace never remove a device.+- **Session drop on a frozen or bounced track**: same rule as the Arrangement (refused with a reason if the Arrangement refuses).+- **Instrument with MPE / per-note expression clips** replaced by one without: the clips stay; expression is ignored by the new instrument.+- **The clipboard holds an instrument and the user pastes onto an audio track or into a rack chain's effect slot**: refused with a status-line reason.+- **Paste an instrument onto an Instrument Rack chain** (outside scope of the track chain): handled by the rack's existing chain-instrument rules, or refused with a reason.++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: The instrument card MUST be selectable in the track's device chain, with the same selection look as effects, mutually exclusive with effect selection.+- **FR-002**: The instrument card's right-click menu MUST offer **Replace…**, **Copy**, **Cut** (moving it per FR-005 on the source), **Paste** (replace, FR-004), **Delete** and **Move to track ▸**.+- **FR-003**: **Replace…** MUST let the user pick any built-in instrument, rack or installed plug-in instrument and swap it in as one undo step; the track's clips, MIDI effects, audio effects and mixer state stay as they were.+- **FR-004**: The device clipboard MUST hold an instrument (with its full settings and state, including racks' contents and plug-in state). Pasting it onto an instrument track MUST replace that track's instrument in one undo step; pasting it anywhere that can't take an instrument MUST change nothing and say why.+- **FR-005**: Deleting the instrument (menu, Delete key, Remove control, Cut or Move) MUST remove the whole track, the same as Delete Track, asking for confirmation first when the track has clips. It is one undo step that restores the track with its instrument, settings, clips, automation and links. An instrument track never exists without an instrument.+- **FR-006**: Every removable device card (built-in audio effect, MIDI effect, plug-in, rack, instrument; on the track chain and in rack chains; full and folded) MUST show a Remove control in its header, visually distinct from the on/off switch and the plug-in editor control, with a "Remove device" tooltip.+- **FR-007**: The Remove control MUST be keyboard focusable and activate on Enter / Space, and MUST NOT take focus away from text entry.+- **FR-008**: Removing a device by any route MUST be one undo step that restores its position, parameters, state, automation, sidechain key and macro / modulation links.+- **FR-009**: In Session view, dropping an instrument (built-in, plug-in or instrument preset) on an instrument track's column header or slot MUST replace that track's instrument, using the same replace path as FR-003 (racks: add a chain / pad, as in the Arrangement).+- **FR-010**: In Session view, dropping an instrument right of the last column, or on an audio / return / group column, MUST create a new instrument track with it (at the end, or right after that column), selected, in one undo step.+- **FR-011**: Session view MUST highlight valid instrument drop targets (column headers, slots, the area right of the last column) during a drag, and the "Drop instruments onto the arrangement." message MUST no longer appear.+- **FR-012**: Moving or pasting an instrument onto an instrument track MUST replace that track's instrument; the old instrument is gone and comes back on Undo. A move's replace and the source track's removal are one undo step.+- **FR-013**: **Move to track ▸** MUST list only tracks that can take the device (instrument and MIDI effects: instrument tracks; audio effects: any track with a device chain), exclude the source track, and move the device with its parameters, state and automation lanes in one undo step; macro and modulation links on the source are dropped, a sidechain key pointing at the target itself is cleared, each with a status-line note.+- **FR-014**: Users MUST also be able to drag a device card's header onto a track header in the Arrangement or Session view: valid headers highlight, a drop moves the device as FR-013 (an instrument as FR-012 / FR-005), and holding ⌥ (Alt) on drop copies it instead, leaving the source untouched. Headers that can't take the device offer no drop.+- **FR-015**: The Preferences → Shortcuts list, `CHANGELOG.md`, `FEATURES.md` and the user docs MUST reflect the new commands and gestures.+- **FR-016**: The new controls and states MUST follow the Studio design language and draw correctly in all four themes.+- **FR-017**: The MCP device tools MUST be able to delete, replace and move the instrument and to move a device between tracks, matching the UI (see also existing instrument tools).++### Key Entities *(include if feature involves data)*++- **Track instrument**: the instrument slot of an instrument track — a built-in synth, a rack or a plug-in, never empty; its settings, state, automation lanes and links.+- **Device clipboard**: one shared clipboard that now holds an audio effect, a MIDI effect or an instrument, with full state.+- **Device move**: a device leaving one track and arriving on another as a single undoable edit, carrying parameters, state and automation lanes.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: Replacing a track's instrument takes at most 2 actions from the device panel (right-click → Replace… → pick), down from a Browser search and drag.+- **SC-002**: Removing any device takes 1 click on a visible control, on 100% of device card types (built-in, plug-in, rack, instrument; full and folded; track chain and rack chains).+- **SC-003**: Moving a device to another track takes 2 menu steps instead of 4 (cut, switch track, select position, paste), and one Undo reverts it fully on both tracks.+- **SC-004**: In Session view, adding a new instrument track or swapping a track's instrument needs no switch to the Arrangement; 100% of instrument kinds offered in the Browser drop there.+- **SC-005**: Every new edit (replace, delete, copy-paste, move, Session drop) round-trips: one Undo returns the project to a state that saves and reloads identically to before the edit.+- **SC-006**: No audible glitch or dropout on other tracks while an instrument is replaced, deleted or moved during playback.++## Assumptions++- "Move to track" moves a device to the end of the target's matching section (audio effects / MIDI effects); position on the target is adjusted afterwards by the existing in-chain drag.+- Macro mappings and modulation links belong to the track (or rack) they were made in and do not travel with a moved or pasted device, consistent with specs/042 ("a pasted device carries no macro mappings").+- Automation lanes do travel with a moved device (not with a copied one), since the user's intent is the same device on another track.+- The Remove control is always visible (not hover-only) so it is discoverable, as #110 asks; its exact look follows `DESIGN.md`.+- Replace… reuses the instrument list the Browser already shows (built-ins, racks, installed plug-ins); no new instrument kinds are added.+- Session drops reuse the Arrangement's instrument-drop rules (replace on an instrument track, chain / pad on a rack, new track otherwise) so both views behave the same.+- Moving / pasting into rack chains is unchanged from specs/042; this feature only adds the instrument to the track-level clipboard and the cross-track move.+- A copy by ⌥-drag carries no automation lanes, as a pasted device carries none.+- Multi-select of devices and "group a selection into a rack" (#328) are out of scope.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [ ] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [ ] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [ ] Audio-thread impact considered: no alloc / lock / I/O on the audio thread (AR-6), command queue for data in (AR-4), immutable snapshots for structural edits (AR-5)+- [ ] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`+- [ ] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`+- [ ] User-visible change → `CHANGELOG.md` `[Unreleased]` entry planned (and FEATURES.md / user docs via the nota-features / nota-docs skills when working with an agent that has them)+- [ ] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/043-instrument-device-chain/tasks.md b/specs/043-instrument-device-chain/tasks.mdnew file mode 100644index 00000000..17666f08--- /dev/null+++ b/specs/043-instrument-device-chain/tasks.md@@ -0,0 +1,214 @@+---++description: "Tasks for spec 043: the instrument as a first-class device in the chain"+---++# Tasks: The instrument as a first-class device in the chain++**Input**: Design documents from `specs/043-instrument-device-chain/`:+- [spec.md](spec.md), [plan.md](plan.md), [research.md](research.md), [data-model.md](data-model.md);+- the contracts [c-abi.md](contracts/c-abi.md), [ui.md](contracts/ui.md) and [mcp.md](contracts/mcp.md);+- [quickstart.md](quickstart.md).++**Tests**: The smoke test is the project's gate (constitution IV) and the plan asks for+`InstrumentChainTests`. Every new C ABI call gets smoke checks, written before its engine+implementation. UI is verified in the app per quickstart.md.++**Organization**: by user story — US1 select / replace / delete the instrument (P1), US2 the+Remove control (P1), US3 Session instrument drops (P2), US4 move a device to another track (P2).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: can run in parallel (different files, no dependency on an unfinished task)+- **[Story]**: US1 / US2 / US3 / US4++---++## Phase 1: Setup++- [X] T001 Create `tests/Nota.SmokeTest/InstrumentChainTests.cs`:+ - the AGPL-3.0-only SPDX two-line header and a file comment listing what it covers (follow `DeviceCopyTests.cs`);+ - `internal static class InstrumentChainTests` with `public static IEnumerable<(bool ok, string label)> Run()` that chains empty `Replace()`, `Clipboard()`, `Transfer()` sections;+ - in `tests/Nota.SmokeTest/Program.cs`: run it after `DeviceCopyTests.Run()` in the full suite (both call sites, lines ~435 and ~15140) and add a `--instrument-chain` mode next to `--device-copy` (line ~432).++---++## Phase 2: Foundational (engine + interop; blocks every story)++**Purpose**: the replace path, the instrument clipboard and the cross-track transfer of+contracts/c-abi.md, mirrored in `IAudioEngine`.++### Smoke checks first++- [X] T002 [P] In `InstrumentChainTests.Replace()` (`tests/Nota.SmokeTest/InstrumentChainTests.cs`): on a Volt track with a MIDI clip and an EQ-8, `SetTrackBuiltinInstrument(t, 3)` gives kind 3 with 0 chains, then `4` gives kind 4, then back to Volt (6); clip count, device chain and track count unchanged after each; each is one undo step (`Undo()` returns the previous kind); kind 3 / 4 on an audio track returns false.+- [X] T003 [P] In `InstrumentChainTests.Clipboard()`: for each built-in kind in `{ 0, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 }` (as `DeviceCopyTests.InstrumentKinds`) set a few params off default on track A, `CopyInstrument(A)`, `DeviceClipboardKind() == 3`, `PasteInstrument(B)` on a Synth track → B's kind and every param equal A's; the clipboard still pastes after `RemoveTrack(A)`; `PasteInstrument` on an audio track returns −2; with an effect copied it returns −1; an Instrument Rack with two chains and a macro mapping, and a Drum Rack with a pad sample, paste with chain / pad count and mapping count equal; one undo restores B's own instrument; copying an audio effect afterwards makes the kind 1 again.+- [X] T004 [P] In `InstrumentChainTests.Transfer()`:+ - audio effect: Reverb on track 1 with a Mix automation lane (2 points) and an EQ-8 after it → `TransferDevice(1, Audio, 0, 2, -1, keepSource:false)` returns track 2's last index; track 1 has only the EQ-8 and its lanes on the EQ are re-indexed to 0; track 2 has the lane on the new index with the same points; one `Undo()` restores both tracks exactly (device kinds, lane targets, points);+ - copy: the same with `keepSource:true` → track 1 unchanged, track 2 has the reverb and no new lane;+ - MIDI effect: Arp moved between instrument tracks; to an audio track → −2;+ - instrument: Volt (params set, one instrument-param lane) on track 1 with a clip, Keys on track 2 → transfer family 2 → track 2 is Volt with the same params and the lane, track 1 is gone, flags bit 2 set; one undo restores both tracks with track 1's clip; instrument onto an audio track → −2, nothing changed;+ - sidechain: a Compressor on track 2 keyed from track 3, moved to track 3 → flags bit 0 set and its sidechain source is −1;+ - `dst == src` → −1.++### Engine++- [X] T005 Add the instrument clipboard to `src/native/nota.engine/src/engine/Engine.h`: `std::shared_ptr<Instrument> clipInstrument_;` beside `clipDevice_` (line ~1301), and declarations `bool copyInstrument(int32_t trackId)`, `int32_t pasteInstrument(int32_t trackId)`, `bool replaceTrackInstrument(int32_t trackId, std::shared_ptr<Instrument> inst)`, `int32_t transferDevice(int32_t src, int32_t family, int32_t index, int32_t dst, int32_t atIndex, bool keepSource, int32_t* outFlags)` with comments quoting contracts/c-abi.md.+- [X] T006 In `src/native/nota.engine/src/engine/Engine_Devices.cpp`, add `replaceTrackInstrument`: find the authoring track, refuse unless `TrackType::Instrument`, close the old instrument's editor, `cloneTrack`, set the instrument (sample rate set), `republishWithTrack`, `recomputePdc`. Route `setTrackBuiltinInstrument` and `setTrackInstrumentPlugin` through it.+- [X] T007 In `Engine::setTrackBuiltinInstrument` (`Engine_Devices.cpp:733`), accept kind 3 → `std::make_shared<RackInstrument>()` and kind 4 → `std::make_shared<DrumRack>()`, sample rate set as in `addInstrumentRackTrack` / `addDrumRackTrack` (`Engine_Rack.cpp:72–95`); update the `nota_track_set_builtin_instrument` comment in `include/nota/nota_engine.h` (line ~1388) to say "kind 3 = an empty Instrument Rack, 4 = an empty Drum Rack".+- [X] T008 In `Engine_Devices.cpp` (the #238 clipboard section, line ~760): `copyInstrument` stores `cloneInstrument(track)` with bypass copied (as `deepCloneTrack`, `Engine_Tracks.cpp:3105`) and resets `clipDevice_` / `clipMidi_`; `copyDevice` / `copyMidiEffect` reset `clipInstrument_` too; `deviceClipboardKind()` returns 3 for an instrument; `pasteInstrument` returns −1 with no instrument on the clipboard, −2 for a non-instrument track, −3 when the clone fails, else clones the clipboard (a temporary `Track` holding `clipInstrument_` passed to `cloneInstrument`, or a helper `cloneInstrumentFrom(const Instrument&)` factored out of `cloneInstrument`) and calls `replaceTrackInstrument`, returning 0. Check the rack copy paths (`RackDeviceClipboard`, specs/042) that reset `clipDevice_` / `clipMidi_` also reset `clipInstrument_`.+- [X] T009 In `src/native/nota.engine/src/engine/Engine_Automation.cpp`, add a helper `std::vector<AutomationLane> takeDeviceLanes(Track& src, int32_t family, int32_t index)` that removes and returns the lanes on that device — family 0: `DeviceParam` or `PluginParam` with `deviceIndex == index`; 1: `MidiDeviceParam` with `deviceIndex == index`; 2: `PluginParam` with `deviceIndex < 0` and any other instrument-param target the track uses — keeping whatever clip-envelope / lane-index bookkeeping `remapAutomationAfterDeviceChange` (line 509) keeps consistent, then shifting later lanes down as that function does for a removal.+- [X] T010 In `Engine_Devices.cpp`, implement `transferDevice` per research R4 and the "Device transfer" table in data-model.md, building **one** `Graph` (`inheritGraphLevel`, replace both tracks; drop the source track for an instrument move) and calling `publish` once, then `remapCvLinksAfterDeviceChange` for the source and `recomputePdc`:+ - return −1 for an unknown track / index or `dst == src`; −2 when "the target can't take this family (audio / return / group / master for an instrument or MIDI effect)"; −3 when the clone fails;+ - audio / MIDI effect: clone (`cloneDevice` / `cloneMidiDevice`), insert at `atIndex` (−1 = end) shifting the target's lanes as `insertDeviceClone` does; unless `keepSource`, remove from the source with `remapAutomationAfterDeviceChange(..., removedIndex)` after taking its lanes (T009) and append them to the target with `deviceIndex` rewritten;+ - instrument: clone, set as the target's instrument (editor of the old one closed); unless `keepSource`, take the source's instrument lanes onto the target and drop the source track (editors closed as `removeTrack`, `Engine_Tracks.cpp:3172`), set flag bit 2;+ - a cloned audio effect whose `sidechainSourceTrackId() == dst` gets −1 and flag bit 0; flag bit 1 when the source had CV links or rack macro mappings to the moved device.+- [X] T011 Add the C wrappers in `src/native/nota.engine/src/abi/nota_engine_device.cpp` and the declarations with the contract comments in `include/nota/nota_engine.h` next to the device clipboard block (line ~1538): `nota_track_copy_instrument`, `nota_track_paste_instrument`, `nota_track_transfer_device` (`out_flags` may be NULL); update the `clipboard_kind` comment to "0 empty, 1 audio effect, 2 MIDI effect, 3 instrument".++### Managed interop++- [X] T012 [P] Add the P/Invokes in `src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs` and the wrappers in `NotaEngine.Devices.cs`; add to `src/managed/Nota.Application/Engine/IAudioEngine.cs` (by `CopyMidiEffect`, line ~514): `bool CopyInstrument(int trackId)`, `int PasteInstrument(int trackId)`, `int TransferDevice(int srcTrackId, DeviceFamily family, int index, int dstTrackId, int atIndex, bool keepSource, out TransferFlags flags)`, a `DeviceFamily { Audio = 0, Midi = 1, Instrument = 2 }` enum and `[Flags] TransferFlags { None = 0, SidechainCleared = 1, LinksDropped = 2, SourceTrackRemoved = 4 }`; update the `DeviceClipboardKind()` comment to include 3 = instrument.+- [X] T013 Build with `scripts/build.sh` and run `dotnet run --project tests/Nota.SmokeTest -- --instrument-chain`: T002–T004 pass.++**Checkpoint**: the engine does everything the stories need; UI work can start.++---++## Phase 3: User Story 1 — Select, delete and replace the instrument (P1) 🎯 MVP++**Goal**: the instrument card is selectable; its menu has Replace…, Copy, Cut, Paste, Delete+track; Delete on it deletes the track after a confirmation when it has clips.++**Independent Test**: spec US1 / quickstart steps 1–3.++- [X] T014 [US1] In `src/managed/Nota.Presentation/DeviceInsertService.cs`, add `InsertPlacement.ReplaceInstrument` (doc comment: "swap the track's instrument even when it is a rack") and handle it in `InsertCore`: a built-in or plug-in instrument (or an instrument preset with `InPlace`) on an instrument track replaces it through `SetTrackBuiltinInstrument` / `SetTrackInstrumentPlugin` without the `CanReplaceInstrument` rack refusal, sets `InstrumentReplaced`; status "Changed instrument to <name>". Drops keep `Default` (rack → chain / pad).+- [X] T015 [US1] In `src/managed/Nota.App/DeviceChainView.Clipboard.cs`: make the instrument selectable — `SelectableKind` includes `ChainKind.Instrument`; track it with `_selDeviceIndex = -1` plus a `bool _instrumentSelected` (data-model.md "UI selection") so `HasDeviceSelection` and `IsSelected(ChainKind.Instrument, -1)` work; `SelectRackDevice` clears it; Focus routes keys here as for effects. Update the comment at line 27 (the instrument is now selectable).+- [X] T016 [US1] In `src/managed/Nota.App/DeviceChainView.Instruments.cs` and `DeviceChainView.Shell.cs`: the instrument card (all routes in `InstrumentCard()`: strategy cards, plug-in card, rack cards, folded strip) gets the selection ring and the click-to-select handler the effect cards use (header and body background; not on controls); `CanDelete: true` for the instrument; header tooltip "Double-click to fold · right-click for replace, copy and delete".+- [X] T017 [US1] In `DeviceChainView.Clipboard.cs`, route Copy / Cut / Paste / Delete for the instrument: Copy → `CopyInstrument`, `_clipFromTrack` and `_clip` (preset label) as for effects; Paste with an instrument on the clipboard and the instrument (or nothing) selected → `PasteInstrument(_trackId)` then `ForgetInstrumentState` + rebuild + `Changed`; Paste of an instrument while an effect is selected → status "Paste an instrument on an instrument card."; Paste of an effect while the instrument is selected → append to the matching section as today. Delete → raise a new `public event Action<int, bool>? TrackDeleteRequested` (trackId, cut: false); Cut → Copy then `TrackDeleteRequested(trackId, true)`.+- [X] T018 [US1] In the device menu (`ShowDeviceMenu`, `DeviceChainView.Clipboard.cs:230`), for `ChainKind.Instrument`: add **Replace…** as a submenu built from the Browser's instrument list (built-ins, Racks: Instrument Rack / Drum Rack, installed plug-in instruments — reuse the catalog source the Browser / `DeviceInsertService` uses), invoking a new `public event Action<BrowserItem>? InstrumentReplaceRequested`; enable Copy / Cut / Paste (Paste when `DeviceClipboardKind() == 3`); hide Duplicate and Group into rack; the danger item reads **Delete track** with `MenuKit.DeleteKey`.+- [X] T019 [US1] In `src/managed/Nota.App/MainWindow.Dnd.cs` (or the partial that wires `_deviceChain`): handle `InstrumentReplaceRequested` with `ApplyInsertResult(Insertion.Insert(item, new InsertTarget(t, InsertPlacement.ReplaceInstrument)))`; handle `TrackDeleteRequested(trackId, cut)`: if the track has any arrangement or Session clip, `await new ConfirmWindow("Delete track", $"“{name}” has clips. Delete the track with its clips?", "Delete", "Cancel").ShowDialog<bool>(this)` (contracts/ui.md wording), then delete through the Arrangement's `DeleteTracks` path (expose `ArrangementView.DeleteTrack(int id)` in `ArrangementView.Tracks.cs` that calls the private `DeleteTracks`), refresh Session and the device panel (show the new selected track or clear); status "Deleted <name>" / "Cut <instrument> — deleted <name>".++**Checkpoint**: US1 works on its own (quickstart 1–3).++---++## Phase 4: User Story 2 — A visible Remove control on every device header (P1)++**Goal**: an 18×18 `×` in every card header and folded strip; click / Enter / Space removes,+one undo step.++**Independent Test**: spec US2 / quickstart step 4.++- [X] T020 [P] [US2] Add a shared `RemoveButton(string tip, Action onRemove)` in `src/managed/Nota.App/DeviceCardKit.cs` (or beside `BuildCardShell` in `DeviceChainView.Shell.cs` if DeviceCardKit has no such helpers): 18×18, `GlyphKind.Close`, `NotaPalette.TextTertiary` → the theme's danger colour on hover, `Focusable = true` with the theme's focus ring, `KeyDown` Enter / Space → `onRemove`, `PointerPressed` handled (no drag, no selection); `ToolTip` = tip; follow `DESIGN.md` (no accent).+- [X] T021 [US2] In `BuildCardShell` (`DeviceChainView.Shell.cs:130`), add the Remove control to the right of the power slot in the header grid for every non-Utility card with `CanDelete` (effects, MIDI effects, plug-ins, racks, the instrument): effects / MIDI effects → the existing delete for that card (select it, `DeleteSelectedDevice`); the instrument → `TrackDeleteRequested(_trackId, false)` with tip "Remove track"; others "Remove device".+- [X] T022 [US2] In `FoldedStrip` (`DeviceChainView.Fold.cs:42`), add the same control on the strip (below the power switch), same routing as T021.+- [X] T023 [P] [US2] In `src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs`, restyle `SlotDelBtn` (line ~117) to the T020 look (same glyph size, colours, focusability), keeping "Remove device"; check the rack chain compact cards of specs/040 (`RackCard.Chains.cs`) all show it.+- [X] T024 [US2] Check every card in all four themes (Studio Dark, Studio Light, Ember Graphite, Ember Paper) and with UI scale > 1: the × never overlaps the name, preset picker or badges on compact cards (shrink the name first, per the header's existing trimming).++**Checkpoint**: US2 works on its own (quickstart 4).++---++## Phase 5: User Story 3 — Drop an instrument in Session view (P2)++**Goal**: Browser instruments (and instrument presets) drop on Session columns and right of the+last column.++**Independent Test**: spec US3 / quickstart step 5.++- [X] T025 [US3] In `src/managed/Nota.Presentation/DeviceInsertService.cs`, add `public InsertResult DropOnSession(BrowserItem item, int trackId)` (one `Group`): an instrument on a plain instrument track → `TryReplaceInstrument`; on an Instrument / Drum Rack track → the chain / pad route `RouteToTrack` uses for racks; otherwise a new instrument track (`CreateInstrumentTrack(item, 0)`) with `CreatedTrack` and an `AfterTrackId = trackId` hint when `trackId > 0`; an instrument preset → `ApplyPreset(item, new InsertTarget(trackId, InPlace: true))` with the same fallbacks. Remove the "Drop instruments onto the arrangement." result at line ~295 (route instruments the same way there).+- [X] T026 [US3] In `src/managed/Nota.App/MainWindow.Dnd.cs` `OnSessionDrop`: the `default` (instrument) branch calls `Insertion.DropOnSession(item, trackId)` and `ApplyInsertResult`; when the result created a track after an anchor column, place it with `Timeline.PlaceNewTrack(newId, trackId)` inside the same undo group; select the new / replaced track's first slot. Instrument presets that today go through `RouteToTrack` keep doing so unless they are instrument presets (then `DropOnSession`).+- [X] T027 [US3] In `src/managed/Nota.App/SessionView.Grid.cs`: make `ColumnHeader` (line 214) a drop target (`DragDrop.SetAllowDrop`, DragOver accepting `BrowserView.IsAcceptableDrag`, drop → `OnItemDropped(item, c.TrackId, -1 /*scene*/, c.IsInstrument)`), with the header drop ring shown while hovered; add a drop target over the empty area right of the last column that calls `OnItemDropped(item, -1, -1, false)` with the grid's `_dropHover` wash; make `OnSessionDrop` treat `scene < 0` as "no slot" (no slot selection, select the track).+- [X] T028 [US3] Verify the Session slot-cell drop of an instrument (existing handler, `SessionView.Grid.cs:358`) now replaces / adds via T026, and a Sample / MIDI file drop on a header does nothing with a status line.++**Checkpoint**: US3 works on its own (quickstart 5).++---++## Phase 6: User Story 4 — Move a device to another track (P2)++**Goal**: Move to track ▸ in every device menu; dragging a card header onto a track header in+the Arrangement or Session moves it, ⌥ copies.++**Independent Test**: spec US4 / quickstart step 6.++- [X] T029 [US4] In `DeviceChainView.Clipboard.cs` `ShowDeviceMenu`: add **Move to track ▸** under Duplicate for effects, MIDI effects and the instrument: list the tracks from the engine track list that can take the family (audio effects: every track with a chain incl. returns and the master; MIDI effects and the instrument: instrument tracks), excluding `_trackId`, each with its name and colour swatch (`MenuKit` item with the track brush). Picking one raises a new `public event Action<DeviceMoveRequest>? MoveRequested` (`record DeviceMoveRequest(int SrcTrackId, DeviceFamily Family, int Index, int DstTrackId, bool Copy)`).+- [X] T030 [US4] In MainWindow (the partial that wires `_deviceChain`, e.g. `MainWindow.Dnd.cs`), add `OnDeviceMoveRequested(DeviceMoveRequest r)`: for an instrument move from a track with clips, the `ConfirmWindow` of contracts/ui.md ("Move the instrument and delete “<name>” with its clips?", "Move", "Cancel"); call `Engine.TransferDevice(..., atIndex: -1, keepSource: r.Copy, out var flags)`; on < 0 show the refusal ("<track> can't take <device>." / "Couldn't copy <device>."); on success refresh Arrangement, Session, the device panel (show the target track), select the moved device there, and set the status "Moved <device> to <track>" / "Copied …" plus " · sidechain cleared" / " · macro and modulation links left on <source>" from `flags`; when `SourceTrackRemoved`, drop the source from the Arrangement selection as `DeleteTracks` does.+- [X] T031 [US4] Create `src/managed/Nota.App/DeviceDrag.cs` (SPDX header; file comment pointing at research R5): `internal static class DeviceDrag` with `Current` `(int TrackId, DeviceChainView.ChainKind Kind, int Index)?`, `IsActive`, `CanTake(IAudioEngine e, int trackId)` (the family rules of T029, `trackId != Current.TrackId`), and `static async Task DragAsync(PointerPressedEventArgs press, (int, ChainKind, int) payload)` that adds a single `DataFormat.Text` sentinel ("nota-device-drag"), sets `Current`, awaits `DragDrop.DoDragDropAsync(press, data, DragDropEffects.Move | DragDropEffects.Copy)`, clears `Current` in `finally` — the `BrowserView.DragItemAsync` pattern (`BrowserView.cs:60`).+- [X] T032 [US4] In `HookDeviceDrag` (`DeviceChainView.Clipboard.cs`, the header drag) and the instrument card's header: keep the press args; in `PointerMoved`, when the pointer leaves the `DeviceChainView` bounds during a drag, end the in-panel drag (opacity, drop bar, capture released) and start `DeviceDrag.DragAsync(press, (_trackId, kind, di))`; the in-panel reorder is unchanged otherwise. Make the instrument card's header draggable this way too (no in-panel reorder for it).+- [X] T033 [US4] In `src/managed/Nota.App/ArrangementView.cs`: in `OnLaneDragOver` (line 1427) accept `DeviceDrag.IsActive` when `DeviceDrag.CanTake(row track)` (Move, or Copy with Alt), showing `SetDropTrack(row)`; in `OnLaneDrop` call a new `public event Action<int, bool>? DeviceDroppedOnTrack` (trackId, copy = `e.KeyModifiers.HasFlag(KeyModifiers.Alt)`); same for the footer rows (`OnFooterDragOver` / `OnFooterDrop`, returns and master for audio effects).+- [X] T034 [US4] In `SessionView.Grid.cs`: the column header and slot-grid drop targets (T027 and the existing grid handler) also accept `DeviceDrag` with `CanTake`, highlighting the column, and raise `DeviceDroppedOnTrack(trackId, alt)` (new event on `SessionView`).+- [X] T035 [US4] In MainWindow, wire both `DeviceDroppedOnTrack` events to `OnDeviceMoveRequested(new DeviceMoveRequest(DeviceDrag.Current.TrackId, family, index, trackId, copy))`, mapping `ChainKind` → `DeviceFamily`.++**Checkpoint**: US4 works on its own (quickstart 6–7).++---++## Phase 7: Polish & cross-cutting++- [X] T036 [P] MCP per contracts/mcp.md: `set_track_instrument(trackId, kind)` in `src/managed/Nota.Mcp/Tools/InstrumentTools.cs` and `move_device_to_track(trackId, chain, index, targetTrackId, atIndex = -1, copy = false)` in `src/managed/Nota.Mcp/Tools/DeviceTools.cs` (through `Mutate`, as the neighbouring tools), with the descriptions the contract gives; mention in `remove_track`'s description that it is how an instrument is deleted.+- [X] T037 [P] Shortcuts pane: add "Drag a device onto a track — move it there" and "⌥-drag a device onto a track — copy it there" under Devices in `src/managed/Nota.App/PreferencesWindow.cs` (run the `nota-shortcuts` skill to check nothing else drifted).+- [X] T038 [P] `CHANGELOG.md` `[Unreleased]`: Added — instrument card select / Replace… / copy-paste (nota-daw/nota#327, nota-daw/nota#146), Remove control on device headers (nota-daw/nota#110), Move to track and drag a device onto a track (nota-daw/nota#327), instrument drops in Session view (nota-daw/nota#313); Changed — Delete on the instrument deletes its track after a confirmation; `set_track_instrument` / `move_device_to_track` MCP tools.+- [X] T039 Run the `nota-features` skill (FEATURES.md) and the `nota-docs` skill (Devices and Session pages, EN + RU, screenshots of the instrument menu and the Remove control).+- [ ] T040 Run quickstart.md steps 1–9 in the app (macOS), incl. all four themes for step 4 and playback for step 9; fix what fails.+ - 2026-10-27, headless harness (/tmp/h043, real MainWindow): steps 1, 3, 4, 5, 6 (menu route) and 7+ (sample on a header) pass; screenshots in all four themes. Not yet checked: the drag of a+ device header out of the panel onto a track (needs a real pointer), step 8 (MCP against a+ running app), step 9 (playback).+- [ ] T041 `scripts/build.sh` green (smoke incl. `InstrumentChainTests`); then `/speckit-converge`.+ - 2026-10-27: build + full smoke pass except `RenderPoolTests` "overloaded" late-block budgets,+ which also fail on a clean develop on this machine under load (16 → 286 late blocks between+ two runs) — environmental, re-run on a quiet machine. `/speckit-converge` not run yet.++---++## Dependencies & execution order++- **Phase 1 → Phase 2** (T001 before T002–T004; T002–T004 before T005–T011; T011 before T012; T013 last in Phase 2).+- **US1** (T014–T019) needs Phase 2. **US2** (T020–T024) needs only T017's `TrackDeleteRequested` for the instrument's ×; effects' × is independent. **US3** (T025–T028) needs only T014 (`InsertPlacement` exists) — otherwise independent of US1 / US2. **US4** (T029–T035) needs Phase 2 and T019's confirmation helper.+- Within US4: T031 before T032–T034; T033 / T034 before T035.+- Polish after the stories it documents.++## Parallel opportunities++- Phase 2: T002, T003, T004 (one file, separate sections — write together or in sequence); T012 alongside T005–T011 once the C signatures in T011 are fixed.+- After Phase 2: US2's T020 / T023, US3's T025–T027 and US1 can proceed side by side (different files: `DeviceChainView.Shell/Fold`, `RackCardView`, `SessionView.Grid` / `DeviceInsertService`, `DeviceChainView.Clipboard`).+- Polish: T036, T037, T038 in parallel.++### Example (after Phase 2)++```text+US1: T014 DeviceInsertService.ReplaceInstrument → T015–T019 DeviceChainView + MainWindow+US2: T020 RemoveButton + T023 RackCardView → T021–T022 Shell / Fold+US3: T025 DropOnSession → T026–T028 MainWindow.Dnd / SessionView.Grid+```++## Implementation strategy++1. **MVP**: Phase 1 + Phase 2 + US1 — the instrument is selectable, replaceable, copyable,+ deletable (quickstart 1–3, smoke green).+2. **+ US2**: the Remove control (#110) — small, ships with the MVP.+3. **+ US3**: Session drops (#313).+4. **+ US4**: Move to track and drag-to-track (#327's second half).+5. Polish, `scripts/build.sh`, `/speckit-converge`, then the PR (`nota-pr` skill) with+ before / after screenshots of the device header and the Session drop.++## Nota compliance (re-check before the PR)++- [X] New files (`InstrumentChainTests.cs`, `DeviceDrag.cs`) carry the AGPL-3.0-only SPDX header+- [X] No new dependency+- [X] No audio-thread change; every edit is one published graph (AR-5 / AR-6)+- [X] New calls only through `nota_engine.h` (AR-7), all covered by `InstrumentChainTests`+- [X] CHANGELOG, FEATURES.md, user docs, Shortcuts pane updated+- [X] UI follows `DESIGN.md` in all four themes++---++## Phase 8: Convergence++> 2026-10-27: the user chose to ship without T042–T046 (all LOW/MEDIUM polish); they stay open as follow-ups.++- [ ] T042 Select the instrument card with a click on its body background (not on its controls), as the header click does, in `src/managed/Nota.App/DeviceChainView.Shell.cs` (`BuildCardShell`, instrument cards only) per US1/AC1 (partial)+- [ ] T043 Refuse an instrument pasted into a rack chain with a reason ("An instrument pastes on an instrument card — replace a chain's instrument from its menu.") instead of "Nothing to paste here." in `src/managed/Nota.App/DeviceCards/Rack/RackCard.Clipboard.cs` (`RcPaste`, clipboard kind 3) per spec Edge Cases (partial)+- [ ] T044 Show each track's colour swatch beside its name in **Move to track ▸** in `src/managed/Nota.App/DeviceChainView.Move.cs` (`MoveToTrackGroup`, the track brush the Arrangement uses) per contracts/ui.md + T029 (partial)+- [ ] T045 Make Cut on the instrument ask with the contract's wording ("Move the instrument and delete “<name>” with its clips?" · **Move**) — or amend contracts/ui.md to the current "Delete the track with its clips?" — in `src/managed/Nota.App/MainWindow.DeviceMoves.cs` (`OnTrackDeleteRequestedAsync`, cut = true) per contracts/ui.md + T019 (contradicts)+- [ ] T046 Record in contracts/ui.md that rack chain compact effect cards drop the "Nota " prefix to fit the Remove control (`src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs`), or revert it, per contracts/ui.md (unrequested)diff --git a/src/managed/Nota.App/ArrangementView.Tracks.cs b/src/managed/Nota.App/ArrangementView.Tracks.csindex c60b4f80..68919ed9 100644--- a/src/managed/Nota.App/ArrangementView.Tracks.cs+++ b/src/managed/Nota.App/ArrangementView.Tracks.cs@@ -133,6 +133,10 @@ public sealed partial class ArrangementViewreturn true;}+ /// <summary>Deletes one track the way the header's Delete does (selection and refresh+ /// included) — the Devices panel's route for deleting a track with its instrument (specs/043).</summary>+ public bool DeleteTrack(int trackId) => DeleteTracks(new[] { trackId });+private bool DeleteTracks(IReadOnlyList<int> ids){if (_engine is null || ids.Count == 0 || !_engine.RemoveTracks(ids.ToArray())) return false;diff --git a/src/managed/Nota.App/ArrangementView.cs b/src/managed/Nota.App/ArrangementView.csindex 4430d163..0cc2e1d1 100644--- a/src/managed/Nota.App/ArrangementView.cs+++ b/src/managed/Nota.App/ArrangementView.cs@@ -1427,6 +1427,7 @@ public sealed partial class ArrangementView : UserControlprivate void OnLaneDragOver(object? sender, DragEventArgs e){if (BrowserView.IsClipDrag) { OnClipDragOverLanes(e); return; }+ if (DeviceDrag.IsActive) { OnDeviceDragOver(e); return; }bool ok = BrowserView.IsAcceptableDrag(e);e.DragEffects = ok ? DragDropEffects.Copy : DragDropEffects.None;SetDropTrack(ok ? RowAtY(e.GetPosition(_lanes).Y) : -1);@@ -1459,6 +1460,14 @@ public sealed partial class ArrangementView : UserControlprivate void OnFooterDragOver(object? sender, DragEventArgs e){+ if (DeviceDrag.IsActive) // returns and the master take audio effects+ {+ int id = FooterRowTrackId(FooterRowAt(e.GetPosition(_footerHeaders).Y));+ bool can = id > 0 && _engine is not null && DeviceDrag.CanTake(_engine, id);+ e.DragEffects = !can ? DragDropEffects.None : (e.KeyModifiers & KeyModifiers.Alt) != 0 ? DragDropEffects.Copy : DragDropEffects.Move;+ SetFooterDropRow(can ? FooterRowAt(e.GetPosition(_footerHeaders).Y) : -1);+ return;+ }bool ok = IsBusDrop();e.DragEffects = ok ? DragDropEffects.Copy : DragDropEffects.None;SetFooterDropRow(ok ? FooterRowAt(e.GetPosition(_footerHeaders).Y) : -1);@@ -1468,6 +1477,13 @@ public sealed partial class ArrangementView : UserControl{int row = FooterRowAt(e.GetPosition(_footerHeaders).Y);SetFooterDropRow(-1);+ if (DeviceDrag.IsActive)+ {+ int id = FooterRowTrackId(row);+ if (id > 0 && _engine is not null && DeviceDrag.CanTake(_engine, id) && DeviceDrag.RequestFor(id, e.KeyModifiers) is { } r)+ { DeviceDropped?.Invoke(r); e.Handled = true; }+ return;+ }if (!IsBusDrop() || BrowserView.CurrentDrag is not { } item) return;int trackId = FooterRowTrackId(row);if (trackId <= 0) return;@@ -1487,9 +1503,32 @@ public sealed partial class ArrangementView : UserControl_footerDropRing.Height = FooterRowH;}+ // A device card dragged out of the Devices panel (specs/043): the row it is over lights when+ // that track can take it; the drop moves it there (⌥ copies).+ private void OnDeviceDragOver(DragEventArgs e)+ {+ int ti = RowAtY(e.GetPosition(_lanes).Y);+ bool ok = ti >= 0 && ti < _tracks.Count && _engine is not null && DeviceDrag.CanTake(_engine, _tracks[ti].Id);+ e.DragEffects = !ok ? DragDropEffects.None : (e.KeyModifiers & KeyModifiers.Alt) != 0 ? DragDropEffects.Copy : DragDropEffects.Move;+ SetDropTrack(ok ? ti : -1);+ }++ private void OnDeviceDrop(DragEventArgs e)+ {+ SetDropTrack(-1);+ int ti = RowAtY(e.GetPosition(_lanes).Y);+ if (ti < 0 || ti >= _tracks.Count || _engine is null || !DeviceDrag.CanTake(_engine, _tracks[ti].Id)) return;+ if (DeviceDrag.RequestFor(_tracks[ti].Id, e.KeyModifiers) is { } r) DeviceDropped?.Invoke(r);+ e.Handled = true;+ }++ /// <summary>A device card was dropped on a track row or footer row (specs/043).</summary>+ public event Action<DeviceMoveRequest>? DeviceDropped;+private void OnLaneDrop(object? sender, DragEventArgs e){if (BrowserView.IsClipDrag) { OnClipDropOnLanes(e); return; }+ if (DeviceDrag.IsActive) { OnDeviceDrop(e); return; }SetDropTrack(-1);var items = BrowserView.DroppedItems(e);if (items.Count == 0) return;diff --git a/src/managed/Nota.App/BrowserView.cs b/src/managed/Nota.App/BrowserView.csindex 011140ee..931cb24a 100644--- a/src/managed/Nota.App/BrowserView.cs+++ b/src/managed/Nota.App/BrowserView.cs@@ -80,7 +80,8 @@ public sealed class BrowserView : UserControl/// or an external drag that carries file(s). Lenient by design — used in DragOver,/// where some backends don't expose the file list yet; the drop re-checks.</summary>public static bool IsAcceptableDrag(DragEventArgs e)- => IsBrowserDrag || e.DataTransfer.Contains(DataFormat.File) || HasPathText(e.DataTransfer);+ => !DeviceDrag.IsActive // a device card's drag carries text too, but isn't a file+ && (IsBrowserDrag || e.DataTransfer.Contains(DataFormat.File) || HasPathText(e.DataTransfer));// A drag that may name files without Avalonia's file list (#300): plain text or a// file manager's own URI list. The drop parses it and ignores anything else.@@ -129,6 +130,7 @@ public sealed class BrowserView : UserControlpublic static IReadOnlyList<BrowserItem> DroppedItems(DragEventArgs e){if (CurrentDrag is { } item) return new[] { item };+ if (DeviceDrag.IsActive) return Array.Empty<BrowserItem>(); // a device card, not filesvar list = new List<BrowserItem>();foreach (var p in ExternalFiles(e))list.Add(new BrowserItemdiff --git a/src/managed/Nota.App/DeviceCardKit.cs b/src/managed/Nota.App/DeviceCardKit.csindex eb9e0203..3a66b80a 100644--- a/src/managed/Nota.App/DeviceCardKit.cs+++ b/src/managed/Nota.App/DeviceCardKit.cs@@ -397,4 +397,39 @@ internal static class DeviceCardKit};static Control At(Control c, int col) { Grid.SetColumn(c, col); return c; }}++ /// <summary>The Remove control on a device header or folded strip (#110, specs/043): an 18 × 18+ /// × in muted ink that brightens on hover and shows a seam ring while focused. Not red —+ /// red means overload in Nota; a destructive key says what it does (DESIGN.md). Click, Enter+ /// or Space runs <paramref name="onRemove"/>; the press never reaches the header (no drag,+ /// no selection, no fold).</summary>+ internal static Border RemoveButton(string tip, Action onRemove)+ {+ var glyph = new Glyph(GlyphKind.Close, 8) { Foreground = TextTertiary, IsHitTestVisible = false };+ var b = new Border+ {+ Width = 18, Height = 18, CornerRadius = NotaRadius.Control, Background = Brushes.Transparent,+ BorderBrush = Brushes.Transparent, BorderThickness = new Thickness(1),+ VerticalAlignment = VerticalAlignment.Center, HorizontalAlignment = HorizontalAlignment.Center,+ Cursor = new Cursor(StandardCursorType.Hand), Focusable = true, IsTabStop = true, Child = glyph,+ };+ ToolTip.SetTip(b, tip);+ Avalonia.Automation.AutomationProperties.SetName(b, tip);+ b.PointerEntered += (_, _) => glyph.Foreground = TextPrimary;+ b.PointerExited += (_, _) => glyph.Foreground = b.IsFocused ? TextPrimary : TextTertiary;+ b.GotFocus += (_, _) => { b.BorderBrush = BorderStrong; glyph.Foreground = TextPrimary; };+ b.LostFocus += (_, _) => { b.BorderBrush = Brushes.Transparent; glyph.Foreground = TextTertiary; };+ b.PointerPressed += (_, e) =>+ {+ e.Handled = true;+ if (e.GetCurrentPoint(b).Properties.IsLeftButtonPressed) onRemove();+ };+ b.KeyDown += (_, e) =>+ {+ if (e.Key is not (Key.Enter or Key.Space)) return;+ e.Handled = true;+ onRemove();+ };+ return b;+ }}diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.csindex 4c43448b..c3e628b9 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCard.Chains.cs@@ -387,6 +387,10 @@ internal sealed partial class RackCardViewDropEffectOnChain(a, c, it);}+ /// <summary>A Browser item dropped on the rack from outside the card (a Session column,+ /// specs/043): the same as a drop on the card's empty chain area.</summary>+ internal void DropAsNewChain(BrowserItem it) => RcDropAsNewChain(it);+private void RcDropAsNewChain(BrowserItem it){if (!RcAccepts(it, out var why)) { _ctx.Status(why); return; }@@ -608,14 +612,35 @@ internal sealed partial class RackCardViewDeferRebuild();};}- var nameTb = RcName(name, NotaPalette.TextPrimary, NotaType.KnobLabel);+ // An effect's card also holds the Remove control: like a compact track card it drops the+ // family prefix ("Nota Reverb" → "Reverb") so the name still reads.+ string label = slot != RcSlot.Instrument && name.StartsWith("Nota ", StringComparison.Ordinal) ? name[5..] : name;+ var nameTb = RcName(label, NotaPalette.TextPrimary, NotaType.KnobLabel);+ ToolTip.SetTip(nameTb, name);var tagTb = RcMono(tag, NotaPalette.TextTertiary, 7);dot.Margin = new Thickness(0, 0, 4, 0);tagTb.Margin = new Thickness(3, 0, 0, 0);+ var headRow = new DockPanel { LastChildFill = true };+ headRow.Children.Add(RcDock(dot, Dock.Left));+ // The Remove control (#110), as on the track chain's cards; a chain's instrument is+ // replaced from its menu, not removed.+ if (slot != RcSlot.Instrument)+ {+ var remove = DeviceCardKit.RemoveButton("Remove device", () =>+ {+ if (RcSelOf(c, slot, idx) is { } sel) { RcDelete(sel); return; }+ if (slot == RcSlot.Midi) a.RemoveChainMidi(c, idx); else a.RemoveChainDevice(c, idx);+ DeferRebuild();+ });+ remove.Margin = new Thickness(2, 0, -4, 0);+ headRow.Children.Add(RcDock(remove, Dock.Right));+ }+ headRow.Children.Add(RcDock(tagTb, Dock.Right));+ headRow.Children.Add(nameTb);var head = new Border{Height = 18, Padding = new Thickness(5, 0), BorderBrush = NotaPalette.Rule, BorderThickness = new Thickness(0, 0, 0, 1),- Child = new DockPanel { LastChildFill = true, Children = { RcDock(dot, Dock.Left), RcDock(tagTb, Dock.Right), nameTb } },+ Child = headRow,};// Parameters: the key ones at rest, every one while mapping (so any can be mapped).diff --git a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.csindex e5f4b6d0..6e8c6824 100644--- a/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs+++ b/src/managed/Nota.App/DeviceCards/Rack/RackCardView.cs@@ -113,17 +113,8 @@ internal sealed partial class RackCardView(DeviceCardContext ctx)return slotCard;}- // Small borderless ✕ in a device slot header that removes that device from the chain.- private Border SlotDelBtn(Action onDelete)- {- var glyph = new Glyph(GlyphKind.Close, 8) { Foreground = IrMuted };- var b = new Border { Width = 13, Background = Brushes.Transparent, Cursor = new Cursor(StandardCursorType.Hand), VerticalAlignment = VerticalAlignment.Stretch, Child = glyph };- ToolTip.SetTip(b, "Remove device");- b.PointerEntered += (_, _) => glyph.Foreground = IrRed;- b.PointerExited += (_, _) => glyph.Foreground = IrMuted;- b.PointerPressed += (_, e) => { e.Handled = true; onDelete(); };- return b;- }+ // The Remove control in a device slot header (#110): the same one as the track chain's cards.+ private static Border SlotDelBtn(Action onDelete) => DeviceCardKit.RemoveButton("Remove device", onDelete);private int MacrosOnTarget(IRackAccess a, int sc, int dev){diff --git a/src/managed/Nota.App/DeviceChainView.Clipboard.cs b/src/managed/Nota.App/DeviceChainView.Clipboard.csindex 1254c178..d4cf06c3 100644--- a/src/managed/Nota.App/DeviceChainView.Clipboard.cs+++ b/src/managed/Nota.App/DeviceChainView.Clipboard.cs@@ -23,11 +23,16 @@ public sealed partial class DeviceChainView// ---- selection --------------------------------------------------------private ChainKind _selChainKind;private int _selDeviceIndex = -1; // -1 = nothing selected. Paired with _selChainKind.+ // The track's instrument card is selected (specs/043); _selDeviceIndex stays -1 then, as the+ // instrument is device -1 to the engine.+ private bool _instrumentSelected;- // Only audio effects and MIDI effects participate in copy/cut/paste/delete (the- // instrument is the track's, not a movable device; sends/add aren't devices).- private bool SelectableKind(ChainKind k) => k == ChainKind.Effect || k == ChainKind.Midi;- private bool HasDeviceSelection => _selDeviceIndex >= 0 && SelectableKind(_selChainKind);+ // Audio effects, MIDI effects and the instrument take copy/cut/paste/delete (sends/add+ // aren't devices). The instrument's Delete and Cut take its track (specs/043).+ private static bool SelectableKind(ChainKind k) => k is ChainKind.Effect or ChainKind.Midi or ChainKind.Instrument;+ private bool HasDeviceSelection => _instrumentSelected || (_selDeviceIndex >= 0 && _selChainKind is ChainKind.Effect or ChainKind.Midi);+ // An effect or MIDI effect (not the instrument) is selected: what ⌘D, ⌘G and an indexed paste need.+ private bool HasEffectSelection => !_instrumentSelected && _selDeviceIndex >= 0 && _selChainKind is ChainKind.Effect or ChainKind.Midi;private void SelectDevice(ChainKind kind, int index){@@ -35,11 +40,14 @@ public sealed partial class DeviceChainViewFocus(); // route Ctrl+C/X/V + Delete herebool hadRack = _rackSel != null;_rackSel = null; _rackCmds = null; // one selection on the panel (specs/042)- if (_selChainKind == kind && _selDeviceIndex == index && !hadRack) return;- _selChainKind = kind; _selDeviceIndex = index;+ bool inst = kind == ChainKind.Instrument;+ if (!hadRack && _selChainKind == kind && (inst ? _instrumentSelected : !_instrumentSelected && _selDeviceIndex == index)) return;+ _selChainKind = kind; _selDeviceIndex = inst ? -1 : index; _instrumentSelected = inst;Rebuild();}+ private void ClearDeviceSelection() { _selDeviceIndex = -1; _instrumentSelected = false; }+// A device in a rack chain (specs/042): the rack card selects it and hands over what the// keys do to it; the track chain's selection clears.private RackDeviceSel? _rackSel;@@ -50,9 +58,9 @@ public sealed partial class DeviceChainViewif (sel != null) Focus();_rackSel = sel;_rackCmds = sel != null ? cmds : null;- if (sel != null && _selDeviceIndex >= 0)+ if (sel != null && (_selDeviceIndex >= 0 || _instrumentSelected)){- _selDeviceIndex = -1;+ ClearDeviceSelection();foreach (var r in _selRings) r.IsVisible = false; // no rebuild: the rack card may be mid-drag}}@@ -61,7 +69,8 @@ public sealed partial class DeviceChainViewprivate readonly System.Collections.Generic.List<Border> _selRings = new();private bool IsSelected(ChainKind kind, int index)- => HasDeviceSelection && _selChainKind == kind && _selDeviceIndex == index;+ => kind == ChainKind.Instrument ? _instrumentSelected+ : HasEffectSelection && _selChainKind == kind && _selDeviceIndex == index;// ---- clipboard --------------------------------------------------------// The device itself is copied by the engine (#238): a full clone with every parameter,@@ -81,40 +90,62 @@ public sealed partial class DeviceChainViewprivate ChainKind ClipKind => _engine.DeviceClipboardKind() switch { 1 => ChainKind.Effect, 2 => ChainKind.Midi, _ => ChainKind.Instrument };private bool CanPaste => _trackId > 0 && _engine.DeviceClipboardKind() != 0;- private void CopySelectedDevice()+ private void CopySelectedDevice() => TryCopySelectedDevice();++ // False when nothing was copied (a plug-in that won't open a second instance): Cut stops then.+ private bool TryCopySelectedDevice(){- if (!HasDeviceSelection) return;+ if (!HasDeviceSelection) return false;int di = _selDeviceIndex;- bool ok = _selChainKind switch+ bool ok = _instrumentSelected ? _engine.CopyInstrument(_trackId) : _selChainKind switch{ChainKind.Effect => _engine.CopyDevice(_trackId, di),ChainKind.Midi => _engine.CopyMidiEffect(_trackId, di),_ => false,};- if (!ok) return;+ if (!ok) return false;_clipFromTrack = true;var ex = Extra(_selChainKind, di);_clip = new DeviceClip { Kind = _selChainKind, Preset = ex.Preset, PresetId = ex.PresetId };+ return true;}private void DeleteSelectedDevice(){if (!HasDeviceSelection) return;- int di = _selDeviceIndex; var k = _selChainKind;+ RemoveDeviceAt(_instrumentSelected ? ChainKind.Instrument : _selChainKind, _selDeviceIndex);+ }++ // Delete, the menu's Delete and the header's Remove control (#110). An instrument track never+ // stands without its instrument: removing it takes the track (specs/043), which the host asks about.+ private void RemoveDeviceAt(ChainKind k, int di)+ {+ if (k == ChainKind.Instrument) { TrackDeleteRequested?.Invoke(_trackId, false); return; }if (k == ChainKind.Effect) _engine.RemoveDevice(_trackId, di);else if (k == ChainKind.Midi) _engine.RemoveMidiEffect(_trackId, di);else return;ExtrasRemoved(k, di);- _selDeviceIndex = -1;+ if (HasEffectSelection && _selChainKind == k) // the selection stays on its own device+ _selDeviceIndex = _selDeviceIndex == di ? -1 : _selDeviceIndex > di ? _selDeviceIndex - 1 : _selDeviceIndex;Rebuild(); Changed?.Invoke();}- private void CutSelectedDevice() { CopySelectedDevice(); DeleteSelectedDevice(); }+ private void CutSelectedDevice()+ {+ // Nothing removed unless the copy landed: a cut device must stay pasteable.+ if (!TryCopySelectedDevice())+ {+ if (HasDeviceSelection) StatusMessage?.Invoke("This device can't be copied, so it wasn't cut.");+ return;+ }+ if (_instrumentSelected) TrackDeleteRequested?.Invoke(_trackId, true);+ else DeleteSelectedDevice();+ }// ⌘D: a copy right after the selected device, the clipboard untouched (specs/042).private void DuplicateSelectedDevice(){- if (!HasDeviceSelection) return;+ if (!HasEffectSelection) return;int di = _selDeviceIndex; var k = _selChainKind;int end = k == ChainKind.Midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);int newIdx = k == ChainKind.Midi ? _engine.DuplicateMidiEffect(_trackId, di) : _engine.DuplicateDevice(_trackId, di);@@ -131,9 +162,10 @@ public sealed partial class DeviceChainView{if (!CanPaste) return;var c = _clipFromTrack && _clip is { } own && own.Kind == ClipKind ? own : new DeviceClip { Kind = ClipKind };+ if (c.Kind == ChainKind.Instrument) { PasteInstrument(c); return; }if (c.Kind != ChainKind.Effect && c.Kind != ChainKind.Midi) return;// Drop it right after the selected device of the same domain, else at the end.- int at = _selChainKind == c.Kind && _selDeviceIndex >= 0 ? _selDeviceIndex + 1 : -1;+ int at = HasEffectSelection && _selChainKind == c.Kind ? _selDeviceIndex + 1 : -1;int end = c.Kind == ChainKind.Midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);if (at > end) at = -1;int newIdx = c.Kind == ChainKind.Midi ? _engine.PasteMidiEffect(_trackId, at) : _engine.PasteDevice(_trackId, at);@@ -143,7 +175,22 @@ public sealed partial class DeviceChainViewTrackExtras().Remove(ExtraKey(c.Kind, newIdx));var pasted = Extra(c.Kind, newIdx); pasted.Preset = c.Preset; pasted.PresetId = c.PresetId;_selChainKind = c.Kind;- _selDeviceIndex = newIdx;+ _selDeviceIndex = newIdx; _instrumentSelected = false;+ Rebuild(); Changed?.Invoke();+ }++ // An instrument on the clipboard replaces this track's instrument (specs/043): with the+ // instrument card or nothing selected; with an effect selected it would read as "paste here".+ private void PasteInstrument(DeviceClip c)+ {+ if (HasEffectSelection) { StatusMessage?.Invoke("Paste an instrument on an instrument card."); return; }+ int r = _engine.PasteInstrument(_trackId);+ if (r == -2) { StatusMessage?.Invoke("Only an instrument track takes an instrument."); return; }+ if (r < 0) { StatusMessage?.Invoke("Couldn't paste the instrument."); return; }+ ForgetInstrumentState(_trackId);+ var ex = Extra(ChainKind.Instrument, -1); ex.Preset = c.Preset; ex.PresetId = c.PresetId;+ _selChainKind = ChainKind.Instrument; _selDeviceIndex = -1; _instrumentSelected = true;+ StatusMessage?.Invoke($"Pasted {_engine.DeviceName(_trackId, -1)}");Rebuild(); Changed?.Invoke();}@@ -155,7 +202,7 @@ public sealed partial class DeviceChainViewprivate void GroupSelectedDevice(){- if (!HasDeviceSelection) { StatusMessage?.Invoke("Select an audio effect to put it in a rack"); return; }+ if (!HasEffectSelection) { StatusMessage?.Invoke("Select an audio effect to put it in a rack"); return; }if (_selChainKind == ChainKind.Midi) { StatusMessage?.Invoke("MIDI effects can't go in a rack"); return; }int di = _selDeviceIndex;string name = _engine.DeviceName(_trackId, di);@@ -216,7 +263,7 @@ public sealed partial class DeviceChainViewif (mod && e.Key == Key.C && HasDeviceSelection) { CopySelectedDevice(); e.Handled = true; return; }if (mod && e.Key == Key.X && HasDeviceSelection) { CutSelectedDevice(); e.Handled = true; return; }if (mod && e.Key == Key.V && CanPaste) { PasteDevice(); e.Handled = true; return; }- if (mod && e.Key == Key.D && HasDeviceSelection) { DuplicateSelectedDevice(); e.Handled = true; return; }+ if (mod && e.Key == Key.D && HasEffectSelection) { DuplicateSelectedDevice(); e.Handled = true; return; }if (!mod && (e.Key == Key.Delete || e.Key == Key.Back) && HasDeviceSelection) { DeleteSelectedDevice(); e.Handled = true; return; }base.OnKeyDown(e);}@@ -243,6 +290,24 @@ public sealed partial class DeviceChainViewflyout.Items.Add(MenuKit.Header(name.Length > 0 ? name : "Device", null, badge));flyout.Items.Add(new Separator());header?.Invoke(flyout); // ends with its own separator+ if (kind == ChainKind.Instrument)+ {+ // The instrument (specs/043): swap it, copy it to another instrument track, or take+ // its track away — an instrument track never stands without one.+ MenuKit.AddGroups(flyout.Items,+ new Control[] { ReplaceInstrumentMenu() },+ new Control[] { MenuKit.Item("Save preset", GlyphKind.Save, () => PresetSaveRequested?.Invoke(-1)) },+ new Control[]+ {+ MenuKit.Item("Copy", GlyphKind.Copy, CopySelectedDevice, MenuKit.CopyKey),+ MenuKit.Item("Cut", GlyphKind.Cut, CutSelectedDevice, MenuKit.CutKey),+ MenuKit.Item("Paste", GlyphKind.Paste, PasteDevice, MenuKit.PasteKey, _engine.DeviceClipboardKind() == 3),+ },+ MoveToTrackGroup(kind, di),+ new Control[] { MenuKit.Danger("Delete track", GlyphKind.Trash, DeleteSelectedDevice, MenuKit.DeleteKey) });+ flyout.ShowAt(anchor, showAtPointer: true);+ return;+ }bool selectable = SelectableKind(kind);MenuKit.AddGroups(flyout.Items,new Control[] { MenuKit.Item("Save preset", GlyphKind.Save, () => PresetSaveRequested?.Invoke(kind == ChainKind.Midi ? PresetService.MidiEffectBase - di : di)) },@@ -253,6 +318,7 @@ public sealed partial class DeviceChainViewMenuKit.Item("Paste", GlyphKind.Paste, PasteDevice, MenuKit.PasteKey, CanPaste),MenuKit.Item("Duplicate", GlyphKind.Duplicate, DuplicateSelectedDevice, MenuKit.DuplicateKey, selectable),},+ MoveToTrackGroup(kind, di),kind == ChainKind.Effect? new Control[]{@@ -284,27 +350,45 @@ public sealed partial class DeviceChainViewprivate System.Collections.Generic.List<Control> DomainCards(ChainKind kind)=> _row.Children.OfType<Control>().Where(c => c.Tag is DevTag t && t.Kind == kind).ToList();+ // The instrument card drags too, but only out of the panel (onto a track header): it has no+ // slot to reorder into. Its index is -1 while dragging (_devDragFrom holds -2 for "the instrument").private void HookDeviceDrag(Control handle, Control card, ChainKind kind, int di){- card.Tag = new DevTag(kind, di);+ bool inst = kind == ChainKind.Instrument;+ if (!inst) card.Tag = new DevTag(kind, di);handle.PointerPressed += (_, e) =>{- if (!e.GetCurrentPoint(handle).Properties.IsLeftButtonPressed) return;- _devDragKind = kind; _devDragFrom = di; _devDragging = false; _devDragCard = card;+ if (!e.GetCurrentPoint(handle).Properties.IsLeftButtonPressed || e.ClickCount > 1) return;+ _devDragKind = kind; _devDragFrom = inst ? -2 : di; _devDragging = false; _devDragCard = card;_devDragStart = e.GetPosition(_row);- e.Pointer.Capture(handle); e.Handled = true;+ _devDragPress = e; // a drag out of the panel needs the press (DoDragDropAsync)+ e.Pointer.Capture(handle);+ if (!inst) e.Handled = true; // the instrument's header still selects on this press};handle.PointerMoved += (_, e) =>{- if (_devDragFrom < 0) return;+ if (_devDragFrom == -1) return;+ // A release that never arrived (the card was rebuilt under the click) leaves no drag.+ if (!e.GetCurrentPoint(handle).Properties.IsLeftButtonPressed) { EndDeviceDrag(e.Pointer); return; }var p = e.GetPosition(_row);- if (!_devDragging && Math.Abs(p.X - _devDragStart.X) < 5) return;+ if (!_devDragging && Math.Abs(p.X - _devDragStart.X) < 5 && Math.Abs(p.Y - _devDragStart.Y) < 5) return;+ // Out of the panel: hand over to a system drag the track headers take (specs/043).+ var q = e.GetPosition(this);+ if ((q.X < 0 || q.Y < 0 || q.X > Bounds.Width || q.Y > Bounds.Height) && _devDragPress is { } press)+ {+ var k = _devDragKind; int from = _devDragFrom == -2 ? -1 : _devDragFrom;+ EndDeviceDrag(e.Pointer);+ _ = DeviceDrag.DragAsync(press, _trackId, k, from);+ return;+ }+ if (inst) return;_devDragging = true;if (_devDragCard != null) _devDragCard.Opacity = 0.55;PositionDropBar(GapAt(p.X));};handle.PointerReleased += (_, e) =>{+ if (inst) { EndDeviceDrag(e.Pointer); return; }if (_devDragFrom < 0) return;var kindL = _devDragKind; int from = _devDragFrom; bool dragged = _devDragging;int gap = _devDragging ? GapAt(e.GetPosition(_row).X) : -1;@@ -320,11 +404,22 @@ public sealed partial class DeviceChainViewif (kindL == ChainKind.Midi) _engine.MoveMidiEffect(_trackId, from, to);else _engine.MoveDevice(_trackId, from, to);ExtrasMoved(kindL, from, to);- _selChainKind = kindL; _selDeviceIndex = to;+ _selChainKind = kindL; _selDeviceIndex = to; _instrumentSelected = false;Rebuild(); Changed?.Invoke();};}+ private PointerPressedEventArgs? _devDragPress;++ // Ends an in-panel header drag without dropping: the card, the drop bar and the capture go back.+ private void EndDeviceDrag(IPointer pointer)+ {+ if (_devDragCard != null) _devDragCard.Opacity = 1.0;+ _devDragFrom = -1; _devDragging = false; _devDragCard = null; _devDragPress = null;+ _row.Children.Remove(_devDropBar);+ pointer.Capture(null);+ }+// Insertion gap (0..m) among the dragged domain's cards for a pointer X in _row space.private int GapAt(double x){diff --git a/src/managed/Nota.App/DeviceChainView.Drop.cs b/src/managed/Nota.App/DeviceChainView.Drop.csindex 2a89b0d0..c4e2aa49 100644--- a/src/managed/Nota.App/DeviceChainView.Drop.cs+++ b/src/managed/Nota.App/DeviceChainView.Drop.cs@@ -174,7 +174,7 @@ public sealed partial class DeviceChainViewif (trackId != _trackId) return; // only the shown chain has moved cards to followif (final != added) ExtrasMoved(k, added, final);if (replaced) ExtrasRemoved(k, final + 1);- _selChainKind = k; _selDeviceIndex = final;+ _selChainKind = k; _selDeviceIndex = final; _instrumentSelected = false;Rebuild(); Changed?.Invoke();}@@ -183,7 +183,7 @@ public sealed partial class DeviceChainViewinternal Nota.Application.Palette.InsertPoint CurrentInsertPoint(){if (_trackId <= 0) return Nota.Application.Palette.InsertPoint.None;- if (HasDeviceSelection)+ if (HasEffectSelection){bool midi = _selChainKind == ChainKind.Midi;int n = midi ? _engine.TrackMidiEffectCount(_trackId) : _engine.TrackDeviceCount(_trackId);diff --git a/src/managed/Nota.App/DeviceChainView.Fold.cs b/src/managed/Nota.App/DeviceChainView.Fold.csindex aac70c71..4da2465f 100644--- a/src/managed/Nota.App/DeviceChainView.Fold.cs+++ b/src/managed/Nota.App/DeviceChainView.Fold.cs@@ -70,12 +70,15 @@ public sealed partial class DeviceChainViewHorizontalAlignment = HorizontalAlignment.Center, VerticalAlignment = VerticalAlignment.Top,};DockPanel.SetDock(power, Dock.Top);+ // The Remove control (#110) at the strip's foot; on the instrument it takes the track.+ var remove = RemoveButton(k == ChainKind.Instrument ? "Remove track" : "Remove device", () => RemoveDeviceAt(k, di));+ DockPanel.SetDock(remove, Dock.Bottom);var strip = new Border{Background = ShellHdr, BorderBrush = BorderDef, BorderThickness = new Thickness(1),CornerRadius = NotaRadius.Body, ClipToBounds = true,- Padding = new Thickness(0, 0, 0, 8),- Child = new DockPanel { LastChildFill = true, Children = { power, rotated } },+ Padding = new Thickness(0, 0, 0, 4),+ Child = new DockPanel { LastChildFill = true, Children = { power, remove, rotated } },Cursor = movable ? new Cursor(StandardCursorType.SizeAll) : null,};strip.BindResource(Border.BoxShadowProperty, "Shadow.Raised");@@ -104,7 +107,7 @@ public sealed partial class DeviceChainViewif (e.ClickCount == 2) { e.Handled = true; SetFolded(k, di, false); return; }SelectDevice(k, di);};- if (movable) HookDeviceDrag(strip, card, k, di);+ HookDeviceDrag(strip, card, k, di); // the instrument's strip drags onto other tracks onlyreturn card;}}diff --git a/src/managed/Nota.App/DeviceChainView.Instruments.cs b/src/managed/Nota.App/DeviceChainView.Instruments.csindex 90aa25b2..35edd831 100644--- a/src/managed/Nota.App/DeviceChainView.Instruments.cs+++ b/src/managed/Nota.App/DeviceChainView.Instruments.cs@@ -33,7 +33,7 @@ public sealed partial class DeviceChainViewdouble width = strategy.WidthFor(_engine, _trackId);var spec = new ShellSpec(Name: _engine.DeviceName(_trackId, -1), Subtitle: strategy.Subtitle, DeviceIndex: -1, Count: 1,- Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: false,+ Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: true,PresetKind: kind, IsInstrument: true, Width: width, Kind: ChainKind.Instrument,VoiceLabel: strategy.VoiceLabel,Presets: kind == Nota.Application.RhythmModel.Kind ? KitPresets() : kind == Nota.Application.MosaicModel.Kind ? MosaicPresets() : null,@@ -93,10 +93,11 @@ public sealed partial class DeviceChainView// The Instrument Rack in the shared shell; the badge counts its chains.private Control InstrumentRackCard(){- var body = new RackCardView(NewCardContext()).BuildInstrumentRackBody(out int chains);+ var view = _instrumentRackView = new RackCardView(NewCardContext());+ var body = view.BuildInstrumentRackBody(out int chains);var spec = new ShellSpec(Name: _engine.DeviceName(_trackId, -1), Subtitle: $"Rack · {chains} chain{(chains == 1 ? "" : "s")}", DeviceIndex: -1, Count: 1,- Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: false,+ Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: true,PresetKind: 3, IsInstrument: true, Width: 700, Kind: ChainKind.Instrument);return BuildCardShell(spec, body);}@@ -109,7 +110,7 @@ public sealed partial class DeviceChainViewvar kits = KitPresets();var spec = new ShellSpec(Name: _engine.DeviceName(_trackId, -1), Subtitle: $"Drums · {pads} pad{(pads == 1 ? "" : "s")}", DeviceIndex: -1, Count: 1,- Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: false,+ Bypassed: _engine.DeviceBypassed(_trackId, -1), Bypassable: true, CanMove: false, CanDelete: true,PresetKind: 4, IsInstrument: true, Width: 700, Kind: ChainKind.Instrument, Presets: kits);return BuildCardShell(spec, body);}diff --git a/src/managed/Nota.App/DeviceChainView.Move.cs b/src/managed/Nota.App/DeviceChainView.Move.csnew file mode 100644index 00000000..43002a31--- /dev/null+++ b/src/managed/Nota.App/DeviceChainView.Move.cs@@ -0,0 +1,148 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Detail · Devices — the instrument as a device in the chain (specs/043): the Replace… list+// in the instrument's menu, and Move to track ▸ for every device.++using System;+using System.Collections.Generic;+using System.Linq;+using Avalonia.Controls;+using Nota.Application;+using Nota.Presentation;++namespace Nota.App;++public sealed partial class DeviceChainView+{+ // The instruments the Browser lists, as a submenu: built-ins, the two racks, then installed+ // plug-in instruments. Picking one hands it to the host, which swaps it in place.+ private MenuItem ReplaceInstrumentMenu()+ {+ var menu = MenuKit.Item("Replace…", GlyphKind.Device);+ void Add(ItemsControl into, BrowserItem item, GlyphKind glyph)+ => into.Items.Add(MenuKit.Item(item.Name, glyph, () => InstrumentReplaceRequested?.Invoke(item)));++ var builtins = BuiltinDeviceCatalog.OfType(BuiltinDeviceType.Instrument).OrderBy(d => d.Name).ToList();+ foreach (var d in builtins.Where(d => d.Kind is not (3 or 4)))+ Add(menu, new BrowserItem { Name = d.Name, Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = d.Kind }, GlyphKind.Device);+ menu.Items.Add(new Separator());+ foreach (var d in builtins.Where(d => d.Kind is 3 or 4))+ Add(menu, new BrowserItem { Name = d.Name, Kind = BrowserItemKind.BuiltinInstrument, BuiltinKind = d.Kind }, GlyphKind.Device);++ var plugins = PluginInstruments();+ if (plugins.Count > 0)+ {+ menu.Items.Add(new Separator());+ var sub = MenuKit.Item("Plug-ins", GlyphKind.Plug);+ foreach (var p in plugins) Add(sub, p, GlyphKind.Plug);+ menu.Items.Add(sub);+ }+ return menu;+ }++ // Installed plug-in instruments, by name (the catalog line reads "Name | Format | inst | Vendor | …").+ private List<BrowserItem> PluginInstruments()+ {+ var list = new List<BrowserItem>();+ if (_catalog is not { } catalog) return list;+ for (int i = 0; i < catalog.Count; i++)+ {+ string? desc = catalog.Description(i);+ if (desc is null || !desc.Contains("| inst |")) continue;+ var parts = desc.Split('|');+ string name = parts[0].Trim(), fmt = parts.Length > 1 ? parts[1].Trim() : "";+ list.Add(new BrowserItem { Name = fmt.Length > 0 ? $"{name} ({fmt})" : name, Kind = BrowserItemKind.PluginInstrument, CatalogIndex = i });+ }+ return list.OrderBy(p => p.Name, StringComparer.OrdinalIgnoreCase).ToList();+ }++ // The shown track's Instrument Rack card, for drops that come from elsewhere (a Session column).+ private RackCardView? _instrumentRackView;++ /// <summary>Hands an instrument preset to the shown track's Instrument Rack card, which adds it+ /// as a new chain. A folded rack has no card on screen: one is built for the drop. False when+ /// the shown track has no Instrument Rack.</summary>+ internal bool DropOnInstrumentRack(BrowserItem item)+ {+ if (_engine.TrackInstrumentKind(_trackId) != 3) return false;+ var v = _instrumentRackView;+ if (v is null)+ {+ v = new RackCardView(NewCardContext());+ v.BuildInstrumentRackBody(out _);+ }+ v.DropAsNewChain(item);+ return true;+ }++ /// <summary>After a device moved or was copied to another track (specs/043): on the source the+ /// cards after it close the gap (a moved instrument's track is gone), on the target the cards+ /// after the insert shift up, and the device's own preset label and A/B slots follow it — a+ /// copy takes only the label, as a paste does. Call before the panel rebuilds.</summary>+ internal void DeviceTransferred(DeviceMoveRequest r, int newIndex)+ {+ var k = r.Family switch { DeviceFamily.Midi => ChainKind.Midi, DeviceFamily.Instrument => ChainKind.Instrument, _ => ChainKind.Effect };+ int srcIdx = k == ChainKind.Instrument ? -1 : r.Index, dstIdx = k == ChainKind.Instrument ? -1 : newIndex;+ TrackExtras(r.SrcTrackId).TryGetValue(ExtraKey(k, srcIdx), out var own);+ // A moved instrument's track is gone; its card state stays under it for an undo.+ if (!r.Copy && k != ChainKind.Instrument) RemapExtras(r.SrcTrackId, k, i => i == srcIdx ? -1 : i > srcIdx ? i - 1 : i);+ if (k != ChainKind.Instrument)+ {+ int last = (k == ChainKind.Midi ? _engine.TrackMidiEffectCount(r.DstTrackId) : _engine.TrackDeviceCount(r.DstTrackId)) - 1;+ if (dstIdx != last) RemapExtras(r.DstTrackId, k, i => i >= dstIdx ? i + 1 : i);+ }+ var dst = TrackExtras(r.DstTrackId);+ // The instrument it replaced keeps its card state aside: an undo brings that instrument+ // back (another id, so ExtraFor swaps the two), a redo this one.+ dst.Remove(ExtraKey(k, dstIdx), out var displaced);+ if (own is null) { if (displaced != null && k == ChainKind.Instrument) dst[ExtraKey(k, dstIdx)] = new CardExtra { Sig = CardSig(r.DstTrackId, k, dstIdx), Wrapped = displaced }; return; }+ string sig = CardSig(r.DstTrackId, k, dstIdx);+ var landed = r.Copy ? new CardExtra { Sig = sig, Preset = own.Preset, PresetId = own.PresetId } : own;+ if (!r.Copy) own.Sig = sig;+ if (k == ChainKind.Instrument) landed.Wrapped = displaced;+ dst[ExtraKey(k, dstIdx)] = landed;+ }++ // Move to track ▸: every track that can take the device, this one left out — audio effects+ // go on any chain (returns and the master too), MIDI effects and the instrument only on+ // instrument tracks. The host does the move (one undo step) and asks before a track goes.+ private IEnumerable<Control> MoveToTrackGroup(ChainKind kind, int di)+ {+ var menu = MenuKit.Item("Move to track", GlyphKind.Track);+ foreach (var (id, name) in TracksThatTake(_engine, kind, _trackId))+ menu.Items.Add(MenuKit.Item(name, null, () => MoveRequested?.Invoke(new DeviceMoveRequest(_trackId, FamilyOf(kind), di, id, false))));+ menu.IsEnabled = menu.Items.Count > 0;+ return new Control[] { menu };+ }++ internal static DeviceFamily FamilyOf(ChainKind k)+ => k switch { ChainKind.Midi => DeviceFamily.Midi, ChainKind.Instrument => DeviceFamily.Instrument, _ => DeviceFamily.Audio };++ /// <summary>The tracks a device of <paramref name="kind"/> can move to, in track order, without+ /// <paramref name="exceptTrackId"/>: (id, name).</summary>+ internal static List<(int Id, string Name)> TracksThatTake(IAudioEngine engine, ChainKind kind, int exceptTrackId)+ {+ var list = new List<(int, string)>();+ for (int i = 0; i < engine.TrackCount; i++)+ {+ if (!engine.TryGetTrackInfo(i, out var ti) || ti.Id == exceptTrackId) continue;+ if (kind != ChainKind.Effect && !(ti.IsInstrument)) continue;+ list.Add((ti.Id, TrackNames.Of(engine, ti))); // as the Arrangement names it+ }+ if (kind == ChainKind.Effect && engine.MasterTrackId != exceptTrackId) list.Add((engine.MasterTrackId, "Master"));+ return list;+ }++ internal static bool CanTake(IAudioEngine engine, ChainKind kind, int trackId, int exceptTrackId)+ {+ if (trackId == exceptTrackId || trackId == 0) return false;+ if (kind == ChainKind.Effect) return true;+ for (int i = 0; i < engine.TrackCount; i++)+ if (engine.TryGetTrackInfo(i, out var ti) && ti.Id == trackId) return ti.IsInstrument;+ return false;+ }+}++/// <summary>Move (or, <paramref name="Copy"/>, copy) a device to another track (specs/043).</summary>+public sealed record DeviceMoveRequest(int SrcTrackId, DeviceFamily Family, int Index, int DstTrackId, bool Copy);diff --git a/src/managed/Nota.App/DeviceChainView.Plugin.cs b/src/managed/Nota.App/DeviceChainView.Plugin.csindex afce7c74..99acc36c 100644--- a/src/managed/Nota.App/DeviceChainView.Plugin.cs+++ b/src/managed/Nota.App/DeviceChainView.Plugin.cs@@ -24,7 +24,7 @@ public sealed partial class DeviceChainViewvar spec = new ShellSpec(Name: info.Name, Subtitle: info.Format, DeviceIndex: di, Count: count,Bypassed: _engine.DeviceBypassed(_trackId, effect ? di : -1), Bypassable: true,- CanMove: effect, CanDelete: effect, PresetKind: -1, IsInstrument: !effect, Width: width, Kind: k,+ CanMove: effect, CanDelete: true, PresetKind: -1, IsInstrument: !effect, Width: width, Kind: k,HeaderExtra: toggle, Compact: state.Mini);return BuildCardShell(spec, new Border { Padding = new Thickness(NotaSpace.DeviceInset), Child = body });}diff --git a/src/managed/Nota.App/DeviceChainView.Shell.cs b/src/managed/Nota.App/DeviceChainView.Shell.csindex 23d21fdb..8bf5548c 100644--- a/src/managed/Nota.App/DeviceChainView.Shell.cs+++ b/src/managed/Nota.App/DeviceChainView.Shell.cs@@ -46,7 +46,9 @@ public sealed partial class DeviceChainViewprivate static int KeyIndex(int key) => key >= 0 ? key : key == -1 ? -1 : -1000 - key;private string CardSig(int t, ChainKind k, int di) => k switch{- ChainKind.Instrument => $"{_engine.TrackInstrumentKind(t)}|{_engine.DeviceName(t, -1)}",+ // The instrument's id too: undo can bring back another instrument of the same kind and+ // name (one moved away, one replaced), and its card must not take this one's A/B.+ ChainKind.Instrument => $"{_engine.TrackInstrumentKind(t)}|{_engine.DeviceName(t, -1)}|{_engine.TrackInstrumentId(t)}",ChainKind.Midi => $"{_engine.MidiEffectKind(t, di)}|{_engine.MidiEffectName(t, di)}",_ => $"{_engine.TrackDeviceBuiltinKind(t, di)}|{_engine.DeviceName(t, di)}",};@@ -74,10 +76,11 @@ public sealed partial class DeviceChainView// Keep each card's extra glued to its device when this view reorders / removes devices.// map: old index → new index, or -1 when the device is gone.- private void RemapExtras(ChainKind k, Func<int, int> map)+ private void RemapExtras(ChainKind k, Func<int, int> map) => RemapExtras(_trackId, k, map);+ private void RemapExtras(int t, ChainKind k, Func<int, int> map){- if (k != ChainKind.Instrument) DevicesRemapped?.Invoke(_trackId, k == ChainKind.Midi, map);- if (k == ChainKind.Instrument || !_cardExtra.TryGetValue(_trackId, out var d)) return;+ if (k != ChainKind.Instrument) DevicesRemapped?.Invoke(t, k == ChainKind.Midi, map);+ if (k == ChainKind.Instrument || !_cardExtra.TryGetValue(t, out var d)) return;var domain = d.Where(kv => KeyKind(kv.Key) == k).ToList();foreach (var kv in domain) d.Remove(kv.Key);foreach (var kv in domain) { int ni = map(KeyIndex(kv.Key)); if (ni >= 0) d[ExtraKey(k, ni)] = kv.Value; }@@ -195,10 +198,21 @@ public sealed partial class DeviceChainViewright.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));right.Children.Add(badges);Grid.SetColumn(power, 1); right.Children.Add(power);+ // The Remove control (#110) after the power slot; on the instrument it takes the track.+ if (!s.Utility && s.CanDelete)+ {+ right.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));+ var remove = RemoveButton(s.IsInstrument ? "Remove track" : "Remove device", () => RemoveDeviceAt(s.Kind, di));+ remove.Margin = new Thickness(-4, 0, -6, 0); // tucked against the card's right inset+ Grid.SetColumn(remove, 2); right.Children.Add(remove);+ }var headerGrid = new Grid { ColumnSpacing = 8 };headerGrid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));headerGrid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Auto));- headerGrid.ColumnDefinitions.Add(new ColumnDefinition(GridLength.Star));+ // A compact card has no room for equal halves: the right side (S / L, the power switch,+ // the Remove control) takes what it needs and the name trims instead of the switches+ // overlapping.+ headerGrid.ColumnDefinitions.Add(new ColumnDefinition(s.Compact ? GridLength.Auto : GridLength.Star));headerGrid.Children.Add(name);Grid.SetColumn(right, 2); headerGrid.Children.Add(right);var headerBar = new Border@@ -208,7 +222,8 @@ public sealed partial class DeviceChainViewCursor = s.CanMove && SelectableKind(s.Kind) ? new Cursor(StandardCursorType.SizeAll) : null,};headerBar.BindResource(Border.BoxShadowProperty, "Shadow.Raised"); // the raised strip's top bevel- if (!s.Utility) ToolTip.SetTip(headerBar, s.CanMove ? "Drag to reorder · double-click to fold · right-click for A/B, move and delete" : "Double-click to fold · right-click for more");+ if (!s.Utility) ToolTip.SetTip(headerBar, s.CanMove ? "Drag to reorder · double-click to fold · right-click for A/B, move and delete"+ : s.IsInstrument ? "Click to select · double-click to fold · right-click to replace, copy or move" : "Double-click to fold · right-click for more");// Factory presets for this device (or the card's own list), and applying one in place.List<(string Id, string Name)> presets;@@ -390,7 +405,7 @@ public sealed partial class DeviceChainView// Bypassed: the body takes the inactive look but stays playable (no opacity for state).if (s.Bypassed) card.AttachedToVisualTree += (_, _) => Inactive.Set(bodyHost, true, interactive: true);// The whole header drags the card to a new slot within its domain (audio FX / MIDI FX).- if (s.CanMove && SelectableKind(s.Kind)) HookDeviceDrag(headerBar, card, s.Kind, di);+ if ((s.CanMove || s.IsInstrument) && SelectableKind(s.Kind)) HookDeviceDrag(headerBar, card, s.Kind, di); // the instrument drags onto other tracks onlyreturn card;}diff --git a/src/managed/Nota.App/DeviceChainView.cs b/src/managed/Nota.App/DeviceChainView.csindex 0e80eb54..4fe952c2 100644--- a/src/managed/Nota.App/DeviceChainView.cs+++ b/src/managed/Nota.App/DeviceChainView.cs@@ -74,6 +74,15 @@ public sealed partial class DeviceChainView : UserControl/// <summary>A one-line message for the status bar (e.g. a kit that loaded incompletely).</summary>public event Action<string>? StatusMessage;+ /// <summary>The instrument's Delete / Cut / Remove (specs/043): the host deletes the track+ /// (trackId), asking first when it has clips. <c>cut</c>: the instrument was copied first.</summary>+ public event Action<int, bool>? TrackDeleteRequested;+ /// <summary>Replace… in the instrument's menu: the host swaps the shown track's instrument+ /// for this one (racks included), one undo step.</summary>+ public event Action<BrowserItem>? InstrumentReplaceRequested;+ /// <summary>Move to track ▸ (and a card dragged onto a track header): the host moves the+ /// device, one undo step, asking first when an instrument's move takes a track with clips.</summary>+ public event Action<DeviceMoveRequest>? MoveRequested;/// <summary>The "+" at the end of the chain was clicked: MainWindow opens the browser on/// Audio effects with the keyboard in its search.</summary>@@ -118,7 +127,7 @@ public sealed partial class DeviceChainView : UserControlHookBrowserDrop();}- public void Show(int trackId) { _trackId = trackId; _rackSelChain = 0; _selDeviceIndex = -1; _rackSel = null; _rackCmds = null; Rebuild(); }+ public void Show(int trackId) { _trackId = trackId; _rackSelChain = 0; _selDeviceIndex = -1; _instrumentSelected = false; _rackSel = null; _rackCmds = null; Rebuild(); }/// <summary>Forgets every card's remembered preset label + A/B slots (a project was/// opened / created, so track ids no longer mean the same tracks).</summary>@@ -181,6 +190,7 @@ public sealed partial class DeviceChainView : UserControl_row.Children.Clear();_selRings.Clear();_instrumentCard = null;+ _instrumentRackView = null;_instLiveViz = null; _instFaders.Clear(); // rebuilt only when a built-in instrument card is shown_deviceLiveRefreshers.Clear(); // compressor GR meter/curve_rackParamRefreshers.Clear(); // rack chain param faders (macro live-follow)diff --git a/src/managed/Nota.App/DeviceDrag.cs b/src/managed/Nota.App/DeviceDrag.csnew file mode 100644index 00000000..089be04f--- /dev/null+++ b/src/managed/Nota.App/DeviceDrag.cs@@ -0,0 +1,43 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// A device card dragged out of the Devices panel onto a track header (specs/043, research R5).+// Inside the panel a header drag reorders with a drop bar; once the pointer leaves the panel it+// becomes a system drag that the Arrangement and Session headers take. Like the Browser's drag+// (BrowserView.DragItemAsync), it carries one native text item — macOS wants exactly one+// pasteboard item per drag image — and the payload rides this static, in-process.++using System.Threading.Tasks;+using Avalonia.Input;+using Nota.Application;++namespace Nota.App;++internal static class DeviceDrag+{+ private const string Sentinel = "nota-device-drag";++ /// <summary>The device being dragged out of the panel, or null.</summary>+ public static (int TrackId, DeviceChainView.ChainKind Kind, int Index)? Current { get; private set; }++ public static bool IsActive => Current is not null;++ /// <summary>The dragged device can land on <paramref name="trackId"/>: not its own track, and+ /// a track that takes its kind (MIDI effects and the instrument need an instrument track).</summary>+ public static bool CanTake(IAudioEngine engine, int trackId)+ => Current is { } c && DeviceChainView.CanTake(engine, c.Kind, trackId, c.TrackId);++ /// <summary>The move (or ⌥ copy) the drop asks for.</summary>+ public static DeviceMoveRequest? RequestFor(int trackId, KeyModifiers mods)+ => Current is { } c ? new DeviceMoveRequest(c.TrackId, DeviceChainView.FamilyOf(c.Kind), c.Index, trackId, (mods & KeyModifiers.Alt) != 0) : null;++ /// <summary>Runs the system drag from the header press; completes on drop or cancel.</summary>+ public static async Task DragAsync(PointerPressedEventArgs press, int trackId, DeviceChainView.ChainKind kind, int index)+ {+ var data = new DataTransfer();+ data.Add(DataTransferItem.Create(DataFormat.Text, Sentinel));+ Current = (trackId, kind, index);+ try { await DragDrop.DoDragDropAsync(press, data, DragDropEffects.Move | DragDropEffects.Copy); }+ finally { Current = null; }+ }+}diff --git a/src/managed/Nota.App/MainWindow.DeviceMoves.cs b/src/managed/Nota.App/MainWindow.DeviceMoves.csnew file mode 100644index 00000000..c35338b1--- /dev/null+++ b/src/managed/Nota.App/MainWindow.DeviceMoves.cs@@ -0,0 +1,102 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The instrument as a device in the chain (specs/043): Replace… and Delete on the instrument+// card, and moving a device to another track (menu or drag onto a track header). An instrument+// track never stands without its instrument, so deleting it — or moving it away — takes the track.++using System.Threading.Tasks;+using Nota.Application;+using Nota.Presentation;++namespace Nota.App;++public partial class MainWindow+{+ private void HookDeviceMoves()+ {+ if (_deviceChain is null) return;+ _deviceChain.InstrumentReplaceRequested += OnInstrumentReplaceRequested;+ _deviceChain.TrackDeleteRequested += (t, cut) => _ = OnTrackDeleteRequestedAsync(t, cut);+ _deviceChain.MoveRequested += r => _ = OnDeviceMoveRequestedAsync(r);+ Timeline.DeviceDropped += r => _ = OnDeviceMoveRequestedAsync(r); // a card dragged onto a track row+ }++ // Session view is built later than the device chain; it hooks its own drops here.+ private void HookSessionDeviceMoves(SessionView session)+ => session.DeviceDropped += r => _ = OnDeviceMoveRequestedAsync(r);++ private void OnInstrumentReplaceRequested(BrowserItem item)+ {+ int t = _deviceChain?.TrackId ?? -1;+ if (t <= 0) return;+ ApplyInsertResult(Insertion.Insert(item, new InsertTarget(t, InsertPlacement.ReplaceInstrument)));+ }++ // Any clip on the track, in the arrangement or a Session slot.+ private bool TrackHasClips(int trackId)+ {+ for (int i = 0; i < Engine.TrackCount; i++)+ if (Engine.TryGetTrackInfo(i, out var ti) && ti.Id == trackId && ti.ClipCount > 0) return true;+ for (int s = 0; s < Engine.SceneCount; s++)+ if (Engine.SessionSlotState(trackId, s) != 0) return true;+ return false;+ }++ // The track's name as the Arrangement shows it (an unnamed instrument track reads as its instrument).+ private string TrackLabel(int trackId)+ => trackId == Engine.MasterTrackId ? "Master" : TrackNames.Of(Engine, trackId);++ // Asks before a device-panel action takes a track that has clips; a track without clips goes+ // without asking (one undo brings it back either way).+ private async Task<bool> ConfirmTrackGoesAsync(int trackId, string message, string affirmative)+ {+ if (!TrackHasClips(trackId)) return true;+ return await new ConfirmWindow("Delete track", message, affirmative, "Cancel").ShowDialog<bool>(this);+ }++ private async Task OnTrackDeleteRequestedAsync(int trackId, bool cut)+ {+ if (_vm is null || trackId <= 0) return;+ string name = TrackLabel(trackId), inst = Engine.DeviceName(trackId, -1);+ if (!await ConfirmTrackGoesAsync(trackId, $"“{name}” has clips. Delete the track with its clips?", "Delete")) return;+ if (!Timeline.DeleteTrack(trackId)) return;+ if (_deviceChain?.TrackId == trackId) ShowDevices(-1, takeOverPanel: false); // its cards would edit a removed track+ _session?.Refresh();+ _vm.StatusText = cut ? $"Cut {inst} — deleted {name}" : $"Deleted {name}";+ }++ // Move to track ▸, or a device card dropped on a track header (⌥ = copy). One undo step; an+ // instrument's move takes its track away, so a track with clips asks first.+ private async Task OnDeviceMoveRequestedAsync(DeviceMoveRequest r)+ {+ if (_vm is null) return;+ string src = TrackLabel(r.SrcTrackId), dst = TrackLabel(r.DstTrackId);+ string device = r.Family switch+ {+ DeviceFamily.Instrument => Engine.DeviceName(r.SrcTrackId, -1),+ DeviceFamily.Midi => Engine.MidiEffectName(r.SrcTrackId, r.Index),+ _ => Engine.DeviceName(r.SrcTrackId, r.Index),+ };+ if (r.Family == DeviceFamily.Instrument && !r.Copy+ && !await ConfirmTrackGoesAsync(r.SrcTrackId, $"Move {device} to “{dst}” and delete “{src}” with its clips?", "Move"))+ return;+ int at = Engine.TransferDevice(r.SrcTrackId, r.Family, r.Index, r.DstTrackId, -1, r.Copy, out var flags);+ if (at < 0)+ {+ _vm.StatusText = at == -2 ? $"“{dst}” can't take {device}." : at == -3 ? $"Couldn't copy {device}." : $"Couldn't move {device}.";+ return;+ }+ _deviceChain?.DeviceTransferred(r, at); // card state (preset label, A/B) follows the device+ Timeline.Refresh(); // a moved instrument took its source track with it+ _session?.Refresh();+ // The device panel follows the device to its new track.+ if (r.DstTrackId != Engine.MasterTrackId) Timeline.Select(r.DstTrackId, -1);+ ShowDevices(r.DstTrackId);+ string msg = $"{(r.Copy ? "Copied" : "Moved")} {device} to {dst}";+ if (flags.HasFlag(TransferFlags.SidechainCleared)) msg += " · sidechain cleared";+ if (flags.HasFlag(TransferFlags.LinksDropped)) msg += $" · modulation links left on {src}";+ if (flags.HasFlag(TransferFlags.SourceTrackRemoved)) msg += $" · deleted {src}";+ _vm.StatusText = msg;+ }+}diff --git a/src/managed/Nota.App/MainWindow.Dnd.cs b/src/managed/Nota.App/MainWindow.Dnd.csindex 828d4664..dcd7760f 100644--- a/src/managed/Nota.App/MainWindow.Dnd.cs+++ b/src/managed/Nota.App/MainWindow.Dnd.cs@@ -61,6 +61,12 @@ public partial class MainWindowtry{bool landed = false; // the drop's slot (and so its track) becomes the selection+ // A column header or the empty grid has no slot for a clip.+ if (scene < 0 && item.Kind is BrowserItemKind.Sample or BrowserItemKind.MidiFile)+ {+ _vm.StatusText = "Drop samples and MIDI files onto a slot.";+ return;+ }switch (item.Kind){case BrowserItemKind.Sample:@@ -78,20 +84,39 @@ public partial class MainWindowcase BrowserItemKind.BuiltinEffect:case BrowserItemKind.PluginEffect:case BrowserItemKind.BuiltinMidiEffect:- case BrowserItemKind.Preset:+ if (trackId <= 0) { _vm.StatusText = "Drop effects onto a column."; break; }var r = Insertion.RouteToTrack(item, trackId); // a session column is a trackApplyInsertResult(r);landed = r.Ok;break;- default: // instruments- _vm.StatusText = "Drop instruments onto the arrangement.";+ default: // instruments and presets (#313): replace, add a chain / pad, or start a track+ {+ InsertResult ir;+ Engine.BeginUndoGroup();+ try+ {+ ir = Insertion.DropOnSession(item, trackId);+ // A new track goes right after the column it was dropped on.+ if (ir.Ok && ir.CreatedTrack && trackId > 0) Timeline.PlaceNewTrack(ir.TrackId, trackId);+ }+ finally { Engine.EndUndoGroup(); }+ if (ir.ToRackCard) // an instrument preset on an Instrument Rack: a new chain, from its card+ {+ ShowDevices(ir.TrackId);+ if (_deviceChain?.DropOnInstrumentRack(item) != true) _vm.StatusText = $"Couldn't add {item.Name} to the rack.";+ }+ else ApplyInsertResult(ir, revealDevices: !ir.CreatedTrack);+ if (ir.Ok && ir.TrackId > 0) { trackId = ir.TrackId; landed = true; }break;+ }}_session?.Refresh();Timeline.Refresh();if (landed && trackId > 0){- _session?.SelectSlot(trackId, scene); // the arrangement follows to the same track+ // The drop's slot (and so its track) becomes the selection; a header or the empty+ // grid has no slot, so the track's first scene stands in.+ _session?.SelectSlot(trackId, Math.Max(0, scene)); // the arrangement follows to the same trackif (Timeline.SelectedTrackId != trackId) Timeline.Select(trackId, -1);}}diff --git a/src/managed/Nota.App/MainWindow.axaml.cs b/src/managed/Nota.App/MainWindow.axaml.csindex 55dc9f95..64e3f676 100644--- a/src/managed/Nota.App/MainWindow.axaml.cs+++ b/src/managed/Nota.App/MainWindow.axaml.cs@@ -421,6 +421,7 @@ public partial class MainWindow : Window_deviceChain.ItemDropped += OnDevicePanelDrop; // browser drag onto the device panel_deviceChain.StatusMessage += msg => { if (_vm is not null) _vm.StatusText = msg; };_deviceChain.AddDeviceRequested += Browser.FocusEffectSearch; // the chain's "+" (#97)+ HookDeviceMoves(); // Replace… / Delete track on the instrument, Move to track (specs/043)Timeline.TrackSelected += OnTrackSelected;Timeline.ClipGeometryChanged += OnClipGeometryChanged; // clip trimmed/moved → follow it in the open editorTimeline.ClipsMoved += OnClipsMoved; // a block move can re-index the open editor's clips@@ -436,6 +437,7 @@ public partial class MainWindow : Window};_session.SlotEditRequested += OpenSessionClipEditor;_session.ItemDropped += OnSessionDrop; // browser drag & drop (M7-5)+ HookSessionDeviceMoves(_session); // a device card dropped on a column (specs/043)_session.ArrangementChanged += () => Timeline.Refresh(); // M5-6_session.Status += msg => vm.StatusText = msg;// Session context menus add tracks through the same path as the arrangement's.diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex 6709d5c9..3e64918a 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1201,11 +1201,13 @@ public sealed partial class PreferencesWindow : NotaWindow}),("Devices (after a click on a device)", new[]{- ("⌘C ⌘X ⌘V", "Copy / cut / paste the device with all its settings · paste lands after the selected device, on any track or rack chain"),+ ("⌘C ⌘X ⌘V", "Copy / cut / paste the device with all its settings · paste lands after the selected device, on any track or rack chain · a copied instrument replaces the instrument it is pasted on"),("⌘D", "Duplicate the selected device"),("⌘G", "Wrap the selected audio effect in an Audio Effect Rack"),("⌘⇧G", "Take the devices out of a selected one-chain rack"),- ("Delete", "Delete the selected device"),+ ("Delete", "Delete the selected device · on the instrument, its track"),+ ("Drag a device onto a track", "Move it there (out of the panel, onto a track row or Session column) · the instrument replaces that track's and its own track goes"),+ ("⌥-drag a device onto a track", "Copy it there"),}),("Racks", new[]{diff --git a/src/managed/Nota.App/SessionView.Grid.cs b/src/managed/Nota.App/SessionView.Grid.csindex 876182ac..bad5b21e 100644--- a/src/managed/Nota.App/SessionView.Grid.cs+++ b/src/managed/Nota.App/SessionView.Grid.cs@@ -273,6 +273,24 @@ public sealed partial class SessionViewvar stack = new StackPanel { Spacing = 4, VerticalAlignment = VerticalAlignment.Center, Margin = new Thickness(8, 3, 8, 0), Children = { top, kind } };Child = new Panel { Children = { stripe, stack } };+ // A Browser drop on the header (#313): an instrument replaces this track's (or, on an+ // audio / return column, starts a track after it); effects and presets go on the track.+ DragDrop.SetAllowDrop(this, true);+ DragDrop.AddDragOverHandler(this, (_, e) =>+ {+ e.DragEffects = o.DragEffectFor(e, c, header: true);+ BorderBrush = e.DragEffects != DragDropEffects.None ? NotaPalette.Accent : BorderBrush;+ e.Handled = true;+ });+ DragDrop.AddDragLeaveHandler(this, (_, _) => Sync());+ DragDrop.AddDropHandler(this, (_, e) =>+ {+ Sync();+ if (o.TryDeviceDrop(e, c)) return;+ var items = BrowserView.DroppedItems(e);+ if (items.Count > 0 && c.Kind != ColKind.Master) { o.RaiseDrop(items[0], c.TrackId, -1, c.IsInstrument); e.Handled = true; }+ });+PointerPressed += (_, e) =>{var pp = e.GetCurrentPoint(this).Properties;@@ -356,12 +374,13 @@ public sealed partial class SessionView}DragDrop.SetAllowDrop(this, true);- DragDrop.AddDragOverHandler(this, (_, e) => e.DragEffects = BrowserView.IsAcceptableDrag(e) ? DragDropEffects.Copy : DragDropEffects.None);- DragDrop.AddDragEnterHandler(this, (_, e) => { if (BrowserView.IsAcceptableDrag(e)) { _dropHover = true; InvalidateVisual(); } });+ DragDrop.AddDragOverHandler(this, (_, e) => { e.DragEffects = o.DragEffectFor(e, c, header: false); e.Handled = true; });+ DragDrop.AddDragEnterHandler(this, (_, e) => { if (o.DragEffectFor(e, c, header: false) != DragDropEffects.None) { _dropHover = true; InvalidateVisual(); } });DragDrop.AddDragLeaveHandler(this, (_, _) => { _dropHover = false; InvalidateVisual(); });DragDrop.AddDropHandler(this, (_, e) =>{_dropHover = false; InvalidateVisual();+ if (o.TryDeviceDrop(e, c)) return;var items = BrowserView.DroppedItems(e);if (items.Count > 0) { _o.RaiseDrop(items[0], c.TrackId, scene, c.IsInstrument); e.Handled = true; }});diff --git a/src/managed/Nota.App/SessionView.cs b/src/managed/Nota.App/SessionView.csindex 024e4c2c..b1ba79ee 100644--- a/src/managed/Nota.App/SessionView.cs+++ b/src/managed/Nota.App/SessionView.cs@@ -98,6 +98,37 @@ public sealed partial class SessionView : UserControlprivate void RaiseDrop(BrowserItem item, int trackId, int scene, bool instrument)=> ItemDropped?.Invoke(item, trackId, scene, instrument);+ /// <summary>A device card dropped on a column (specs/043): the host moves it there.</summary>+ public event Action<DeviceMoveRequest>? DeviceDropped;++ // What a drag over a column's header or slot may do: a Browser drag copies in (a header takes+ // anything but the master; a slot what BrowserView accepts), a device card moves (⌥ copies)+ // onto a track that can take it.+ private DragDropEffects DragEffectFor(DragEventArgs e, Column c, bool header)+ {+ if (DeviceDrag.IsActive)+ {+ int id = c.Kind == ColKind.Master ? _engine.MasterTrackId : c.TrackId;+ if (!DeviceDrag.CanTake(_engine, id)) return DragDropEffects.None;+ return (e.KeyModifiers & KeyModifiers.Alt) != 0 ? DragDropEffects.Copy : DragDropEffects.Move;+ }+ if (header) return BrowserView.IsBrowserDrag && c.Kind != ColKind.Master ? DragDropEffects.Copy : DragDropEffects.None;+ return BrowserView.IsAcceptableDrag(e) ? DragDropEffects.Copy : DragDropEffects.None;+ }++ private bool TryDeviceDrop(DragEventArgs e, Column c)+ {+ if (!DeviceDrag.IsActive) return false;+ int id = c.Kind == ColKind.Master ? _engine.MasterTrackId : c.TrackId;+ if (DeviceDrag.CanTake(_engine, id) && DeviceDrag.RequestFor(id, e.KeyModifiers) is { } r) DeviceDropped?.Invoke(r);+ e.Handled = true;+ return true;+ }++ // What can start a track from a drop off the columns: an instrument or an instrument preset.+ private static bool StartsTrack(BrowserItem item)+ => item.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument or BrowserItemKind.Preset;+public SessionView(IAudioEngine engine){ValueEntry.SetScope(this, true); // Tab in a value box walks the values shown here@@ -121,7 +152,23 @@ public sealed partial class SessionView : UserControlHorizontalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Auto,VerticalScrollBarVisibility = Avalonia.Controls.Primitives.ScrollBarVisibility.Disabled,};- var gridArea = new Border { Background = NotaPalette.BgSunken, Child = hScroll };+ var gridArea = new Border { Background = NotaPalette.BgSunken, Child = hScroll, BorderThickness = new Thickness(1), BorderBrush = Brushes.Transparent };+ // A Browser drop on the empty part of the grid — right of the last column, under the+ // scenes — starts a new track (#313); cells and headers take their own drops first.+ DragDrop.SetAllowDrop(gridArea, true);+ DragDrop.AddDragOverHandler(gridArea, (_, e) =>+ {+ bool ok = BrowserView.IsBrowserDrag && BrowserView.CurrentDrag is { } it && StartsTrack(it);+ e.DragEffects = ok ? DragDropEffects.Copy : DragDropEffects.None;+ gridArea.BorderBrush = ok ? NotaPalette.AccentDim : Brushes.Transparent;+ });+ DragDrop.AddDragLeaveHandler(gridArea, (_, _) => gridArea.BorderBrush = Brushes.Transparent);+ DragDrop.AddDropHandler(gridArea, (_, e) =>+ {+ gridArea.BorderBrush = Brushes.Transparent;+ var items = BrowserView.DroppedItems(e);+ if (items.Count > 0 && StartsTrack(items[0])) { RaiseDrop(items[0], -1, -1, false); e.Handled = true; }+ });// Right-click on the empty part of the grid: add a track (cells and headers handle their own).gridArea.PointerPressed += (_, e) =>{diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex 6c01c3d0..5078ee9e 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -251,6 +251,14 @@ public struct NotaMeter/// <summary>What a parameter-automation lane drives (M9). Matches native AutomationTarget.</summary>public enum AutomationTarget { Volume = 0, Pan = 1, DeviceParam = 2, PluginParam = 3, MidiDeviceParam = 4 }+/// <summary>What a device transfer (specs/043) moves: an audio effect, a MIDI effect or the+/// track's instrument. Matches nota_track_transfer_device's family.</summary>+public enum DeviceFamily { Audio = 0, Midi = 1, Instrument = 2 }++/// <summary>What a device transfer did besides moving the device (nota_track_transfer_device's out_flags).</summary>+[Flags]+public enum TransferFlags { None = 0, SidechainCleared = 1, LinksDropped = 2, SourceTrackRemoved = 4 }+/// <summary>Project pan law (specs/006). Matches NOTA_PAN_LAW_*: Balance drops the far/// channel as a track pans, Stereo folds it into the near side.</summary>public enum PanLaw { Balance = 0, Stereo = 1 }diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex 35fc0c16..07840e23 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -512,13 +512,21 @@ public interface IAudioEngine : IDisposable// Device clipboard (#238): a full clone held by the engine; paste is one undo step.bool CopyDevice(int trackId, int deviceIndex);bool CopyMidiEffect(int trackId, int index);- int DeviceClipboardKind(); // 0 empty, 1 audio effect, 2 MIDI effect+ int DeviceClipboardKind(); // 0 empty, 1 audio effect, 2 MIDI effect, 3 instrumentbool DeviceClipboardSidechain(); // the copied audio effect is keyed from another trackint PasteDevice(int trackId, int atIndex); // atIndex -1 = end; new index or -1int PasteMidiEffect(int trackId, int atIndex);// A full clone right after the device / MIDI effect, one undo step; clipboard untouched.int DuplicateDevice(int trackId, int deviceIndex);int DuplicateMidiEffect(int trackId, int index);+ // The instrument on the same clipboard (specs/043). Paste replaces the track's instrument:+ // 0 done, -1 nothing to paste, -2 not an instrument track, -3 the clone failed.+ bool CopyInstrument(int trackId);+ int PasteInstrument(int trackId);+ // Move (or, keepSource, copy) a device to another track, both tracks in one undo step: the+ // new index (0 for the instrument), -1 bad address, -2 the target can't take it, -3 the+ // clone failed. A move takes the device's automation; the instrument's removes its track.+ int TransferDevice(int srcTrackId, DeviceFamily family, int index, int dstTrackId, int atIndex, bool keepSource, out TransferFlags flags);// ⌘G / ⌘⇧G on a device (#257): wrap an audio effect in an Audio Effect Rack (its index or// -1: keyed / automated / CV-linked devices stay out), unwrap a one-chain rack (count or -1).int WrapDeviceInRack(int trackId, int deviceIndex);@@ -1050,6 +1058,9 @@ public interface IAudioEngine : IDisposable// --- Project load (M7-6) -----------------------------------------------void Reset();int TrackInstrumentKind(int trackId);+ /// <summary>Which instrument the track holds (specs/043): the same while it is edited, moved or+ /// brought back by undo; another for a new, replaced or pasted one. 0 = none. Compare only.</summary>+ long TrackInstrumentId(int trackId);/// <summary>The track's instrument responds to per-note expression (MPE).</summary>bool TrackInstrumentSupportsMpe(int trackId);int TrackDeviceBuiltinKind(int trackId, int deviceIndex);diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.csindex beb09e36..cf2b3c23 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.Devices.cs@@ -61,6 +61,16 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_track_duplicate_midi_effect")]internal static partial int DuplicateMidiEffect(IntPtr engine, int trackId, int index);+ [LibraryImport(Lib, EntryPoint = "nota_track_copy_instrument")]+ internal static partial int CopyInstrument(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_track_paste_instrument")]+ internal static partial int PasteInstrument(IntPtr engine, int trackId);++ [LibraryImport(Lib, EntryPoint = "nota_track_transfer_device")]+ internal static partial int TransferDevice(IntPtr engine, int srcTrackId, int family, int index, int dstTrackId,+ int atIndex, int keepSource, out int flags);+[LibraryImport(Lib, EntryPoint = "nota_track_wrap_device_in_rack")]internal static partial int WrapDeviceInRack(IntPtr engine, int trackId, int deviceIndex);@@ -255,6 +265,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_track_instrument_kind")]internal static partial int TrackInstrumentKind(IntPtr engine, int trackId);+ [LibraryImport(Lib, EntryPoint = "nota_track_instrument_id")]+ internal static partial long TrackInstrumentId(IntPtr engine, int trackId);+[LibraryImport(Lib, EntryPoint = "nota_track_instrument_supports_mpe")]internal static partial int TrackInstrumentSupportsMpe(IntPtr engine, int trackId);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.csindex 080bc491..1ec86a3b 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Devices.cs@@ -96,6 +96,23 @@ public sealed partial class NotaEnginepublic int DuplicateMidiEffect(int trackId, int index){ ThrowIfDisposed(); return NativeMethods.DuplicateMidiEffect(_handle, trackId, index); }+ /// <summary>The track's instrument on the device clipboard (specs/043), a full clone.</summary>+ public bool CopyInstrument(int trackId)+ { ThrowIfDisposed(); return NativeMethods.CopyInstrument(_handle, trackId) == 1; }+ /// <summary>Replaces the track's instrument with a clone of the copied one, one undo step.+ /// 0 done, -1 nothing to paste, -2 not an instrument track, -3 the clone failed.</summary>+ public int PasteInstrument(int trackId)+ { ThrowIfDisposed(); return NativeMethods.PasteInstrument(_handle, trackId); }+ /// <summary>Moves (or copies) a device to another track in one undo step (specs/043). The new+ /// index (0 for the instrument), -1 bad address, -2 the target can't take it, -3 the clone failed.</summary>+ public int TransferDevice(int srcTrackId, DeviceFamily family, int index, int dstTrackId, int atIndex, bool keepSource, out TransferFlags flags)+ {+ ThrowIfDisposed();+ int r = NativeMethods.TransferDevice(_handle, srcTrackId, (int)family, index, dstTrackId, atIndex, keepSource ? 1 : 0, out int f);+ flags = (TransferFlags)f;+ return r;+ }+/// <summary>Wraps an audio effect in a new Audio Effect Rack in its place (#257). The rack's index, or -1.</summary>public int WrapDeviceInRack(int trackId, int deviceIndex){ ThrowIfDisposed(); return NativeMethods.WrapDeviceInRack(_handle, trackId, deviceIndex); }@@ -331,6 +348,7 @@ public sealed partial class NotaEngine/// <summary>Instrument identity: 0=Synth, 1=Sampler, -1=plugin/unknown, -2=no instrument.</summary>public int TrackInstrumentKind(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackInstrumentKind(_handle, trackId); }+ public long TrackInstrumentId(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackInstrumentId(_handle, trackId); }public bool TrackInstrumentSupportsMpe(int trackId) { ThrowIfDisposed(); return NativeMethods.TrackInstrumentSupportsMpe(_handle, trackId) != 0; }/// <summary>Built-in device kind (0=EQ,1=Comp,2=Reverb,3=Delay,4=Utility) or -1 for a plugin.</summary>diff --git a/src/managed/Nota.Mcp/Tools/DeviceTools.cs b/src/managed/Nota.Mcp/Tools/DeviceTools.csindex a98b5164..014eaf4e 100644--- a/src/managed/Nota.Mcp/Tools/DeviceTools.cs+++ b/src/managed/Nota.Mcp/Tools/DeviceTools.cs@@ -48,6 +48,31 @@ public sealed class DeviceTools(IAudioEngine engine, IEngineDispatch dispatch, I[McpServerTool(Name = "move_device"), Description("Reorder a device within a track's chain.")]public Task MoveDevice(int trackId, int fromIndex, int toIndex) => Mutate(() => E.MoveDevice(trackId, fromIndex, toIndex));+ public sealed record DeviceMoveResult(int Index, bool SidechainCleared, bool LinksDropped, bool SourceTrackRemoved);++ [McpServerTool(Name = "move_device_to_track"), Description("Move (or, with copy, copy) a device to another track in one undo step. chain: \"audio\" (an audio effect at index), \"midi\" (a MIDI effect at index) or \"instrument\" (the track's instrument; index is ignored). It lands at atIndex of the target's matching section (-1 = the end); an instrument replaces the target's instrument. A move takes the device's automation along and a moved instrument removes its source track; a copy carries no automation. MIDI effects and instruments go only to instrument tracks. Modulation links to the device stay on the source; a sidechain key on the target itself is cleared. Returns the new index and what else happened.")]+ public Task<DeviceMoveResult> MoveDeviceToTrack(+ [Description("Source track id")] int trackId,+ [Description("\"audio\", \"midi\" or \"instrument\"")] string chain,+ [Description("Device index in that chain (ignored for the instrument)")] int index,+ [Description("Target track id")] int targetTrackId,+ [Description("Position on the target, -1 = the end")] int atIndex = -1,+ [Description("Copy instead of move: the source keeps its device")] bool copy = false) => Mutate(() =>+ {+ var family = chain switch+ {+ "audio" => DeviceFamily.Audio,+ "midi" => DeviceFamily.Midi,+ "instrument" => DeviceFamily.Instrument,+ _ => throw new ArgumentException("chain must be 'audio', 'midi' or 'instrument'."),+ };+ int r = E.TransferDevice(trackId, family, index, targetTrackId, atIndex, copy, out var f);+ if (r == -2) throw new InvalidOperationException($"Track {targetTrackId} can't take that device (MIDI effects and instruments need an instrument track).");+ if (r == -3) throw new InvalidOperationException("The device couldn't be copied (a plug-in that won't load a second time).");+ if (r < 0) throw new ArgumentException("No such device or track, or the target is the source track.");+ return new DeviceMoveResult(r, f.HasFlag(TransferFlags.SidechainCleared), f.HasFlag(TransferFlags.LinksDropped), f.HasFlag(TransferFlags.SourceTrackRemoved));+ });+[McpServerTool(Name = "set_device_bypass"), Description("Bypass or enable a device. deviceIndex -1 is the track's instrument: bypassed, it makes no sound (its MIDI effects and audio effects keep running).")]public Task SetDeviceBypass(int trackId, int deviceIndex, bool bypassed) => Mutate(() => E.SetDeviceBypassed(trackId, deviceIndex, bypassed));diff --git a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs b/src/managed/Nota.Mcp/Tools/InstrumentTools.csindex c5a3941c..048a68bb 100644--- a/src/managed/Nota.Mcp/Tools/InstrumentTools.cs+++ b/src/managed/Nota.Mcp/Tools/InstrumentTools.cs@@ -31,6 +31,14 @@ public sealed class InstrumentTools(IAudioEngine engine, IEngineDispatch dispatc[McpServerTool(Name = "list_instrument_kinds"), Description("List the built-in instrument kinds (kind id + name) you can add.")]public InstrumentKind[] ListInstrumentKinds() => Array.ConvertAll(Kinds, k => new InstrumentKind(k.Kind, k.Name));+ [McpServerTool(Name = "set_track_instrument"), Description("Replace an instrument track's instrument with a fresh built-in kind (see list_instrument_kinds; 3 = an empty Instrument Rack, 4 = an empty Drum Rack). Clips, MIDI effects, audio effects and the mixer stay; one undo step. Plug-ins use set_track_instrument_plugin. An instrument track always has an instrument: to delete it, remove_track.")]+ public Task<bool> SetTrackInstrument([Description("Instrument track id")] int trackId, [Description("Instrument kind id from list_instrument_kinds")] int kind) => Mutate(() =>+ {+ if (!E.SetTrackBuiltinInstrument(trackId, kind))+ throw new InvalidOperationException($"Track {trackId} isn't an instrument track, or kind {kind} isn't a built-in instrument.");+ return true;+ });+[McpServerTool(Name = "add_instrument_track"), Description("Add an instrument track with the given built-in kind (see list_instrument_kinds). Returns the track id.")]public Task<int> AddInstrumentTrack([Description("Instrument kind id from list_instrument_kinds")] int kind) => Mutate(() =>{diff --git a/src/managed/Nota.Mcp/Tools/TrackTools.cs b/src/managed/Nota.Mcp/Tools/TrackTools.csindex 359488c0..876c6a2b 100644--- a/src/managed/Nota.Mcp/Tools/TrackTools.cs+++ b/src/managed/Nota.Mcp/Tools/TrackTools.cs@@ -23,7 +23,7 @@ public sealed class TrackTools(IAudioEngine engine, IEngineDispatch dispatch, IA[McpServerTool(Name = "add_group_track"), Description("Add an empty group (submix) track. Returns its track id.")]public Task<int> AddGroupTrack() => Mutate(() => E.AddGroupTrack());- [McpServerTool(Name = "remove_track"), Description("Remove a track by id.")]+ [McpServerTool(Name = "remove_track"), Description("Remove a track by id. This is also how an instrument is deleted: an instrument track never stands without one (set_track_instrument swaps it).")]public Task<bool> RemoveTrack([Description("Track id")] int trackId) => Mutate(() => E.RemoveTrack(trackId));[McpServerTool(Name = "rename_track"), Description("Set a track's display name.")]diff --git a/src/managed/Nota.Presentation/DeviceInsertService.cs b/src/managed/Nota.Presentation/DeviceInsertService.csindex d849edf4..03f94989 100644--- a/src/managed/Nota.Presentation/DeviceInsertService.cs+++ b/src/managed/Nota.Presentation/DeviceInsertService.cs@@ -22,6 +22,10 @@ public enum InsertPlacementInsert,/// <summary>The effect at <see cref="InsertTarget.Index"/> is swapped for the new one.</summary>Replace,+ /// <summary>An instrument swaps the track's instrument even when it is a rack — Replace…+ /// in the instrument's menu (specs/043). A drop never asks for this: on a rack it adds a+ /// chain / pad.</summary>+ ReplaceInstrument,}/// <summary>Where an item goes. <paramref name="Midi"/>: the index refers to the MIDI-effect chain.@@ -43,6 +47,9 @@ public sealed record InsertResultpublic bool CreatedTrack { get; init; }/// <summary>The track's instrument was swapped in place — its card state is stale.</summary>public bool InstrumentReplaced { get; init; }+ /// <summary>An instrument preset dropped on an Instrument Rack (specs/043): the rack card adds+ /// it as a new chain, as a drop on the card does — the caller hands it over.</summary>+ public bool ToRackCard { get; init; }/// <summary>The views should reveal the track's device chain.</summary>public bool ShowDevices { get; init; }/// <summary>An effect was appended at <c>Added</c> and then moved to <c>Final</c>@@ -110,6 +117,13 @@ public sealed class DeviceInsertService=> item.Kind == BrowserItemKind.Preset&& (item.Path.StartsWith(KitPrefix, StringComparison.Ordinal) || item.Path.StartsWith(RhythmKitPrefix, StringComparison.Ordinal));+ /// <summary>A preset that brings an instrument: a kit, a factory instrument preset, or a user /+ /// pack preset of a built-in or plug-in instrument.</summary>+ public bool IsInstrumentPreset(BrowserItem item)+ => item.Kind == BrowserItemKind.Preset+ && (IsKit(item) || FactoryInfo(item) is { IsInstrument: true }+ || _presets?.Describe(item.Path) is { Type: "builtin-instrument" or "plugin-instrument" });+/// <summary>The factory preset behind a row, or null for a user preset / kit / non-preset.</summary>public FactoryPresetInfo? FactoryInfo(BrowserItem item){@@ -156,9 +170,9 @@ public sealed class DeviceInsertService}/// <summary>Swaps a plain instrument track's instrument. False — nothing changed — when it can't.</summary>- public bool TryReplaceInstrument(BrowserItem item, int trackId)+ public bool TryReplaceInstrument(BrowserItem item, int trackId, bool evenRack = false){- if (!CanReplaceInstrument(trackId)) return false;+ if (evenRack ? !(TryTrackInfo(trackId, out var ti) && ti.IsInstrument && !ti.IsReturn && !ti.IsGroup) : !CanReplaceInstrument(trackId)) return false;if (item.Kind == BrowserItemKind.BuiltinInstrument){if (!_engine.SetTrackBuiltinInstrument(trackId, item.BuiltinKind)) return false;@@ -209,6 +223,44 @@ public sealed class DeviceInsertServicereturn Group(() => RouteToTrack(item, trackId));}+ /// <summary>A Browser drop in Session view (#313, specs/043) on a column (<paramref name="trackId"/>)+ /// or right of the last one (≤ 0). An instrument replaces a plain instrument track's, adds a+ /// chain / pad to a rack, and otherwise (an audio, return or group column, or no column) starts+ /// a new instrument track — the caller places it after the column. An instrument preset loads+ /// in place the same way; effects and other presets route to the track. One undo step.</summary>+ public InsertResult DropOnSession(BrowserItem item, int trackId)+ {+ bool hostsInstrument = trackId > 0 && TryTrackInfo(trackId, out var ti) && ti.IsInstrument && !ti.IsGroup && !ti.IsReturn;+ if (item.Kind is BrowserItemKind.BuiltinInstrument or BrowserItemKind.PluginInstrument)+ return TagPlugin(item, Group(() =>+ {+ if (hostsInstrument)+ {+ if (_engine.TrackInstrumentKind(trackId) is 3 or 4) return AddToTrack(item, trackId);+ return TryReplaceInstrument(item, trackId)+ ? new InsertResult { Ok = true, TrackId = trackId, InstrumentReplaced = true, Status = $"Changed instrument to {item.Name} (track {trackId})" }+ : InsertResult.Fail($"Couldn't load {item.Name}.");+ }+ int t = CreateInstrumentTrack(item, 0);+ return t > 0 ? new InsertResult { Ok = true, TrackId = t, CreatedTrack = true, Status = $"Added {item.Name} (track {t})" }+ : InsertResult.Fail($"Couldn't load {item.Name}.");+ }));+ // A preset: in place on an instrument track; on another column an instrument preset+ // spawns its own track and an effect preset lands on the column.+ // On a rack an instrument preset becomes a chain (Instrument Rack) or, a kit, the pads+ // (Drum Rack) — never a track of its own.+ if (item.Kind == BrowserItemKind.Preset && hostsInstrument && IsInstrumentPreset(item)+ && _engine.TrackInstrumentKind(trackId) is int rk and (3 or 4))+ {+ if (rk == 3) return new InsertResult { Ok = true, TrackId = trackId, ToRackCard = true, ShowDevices = true };+ if (!IsKit(item)) return InsertResult.Fail("A Drum Rack takes kits and instruments; load an instrument preset on a pad from its card.");+ }+ if (item.Kind == BrowserItemKind.Preset)+ return hostsInstrument ? ApplyPreset(item, new InsertTarget(trackId, InPlace: true))+ : trackId > 0 ? Group(() => RouteToTrack(item, trackId)) : ApplyPreset(item, new InsertTarget(-1));+ return Group(() => RouteToTrack(item, trackId));+ }+/// <summary>Drag & drop onto the Devices panel, the Modular canvas, or the palette's/// default: the item goes onto <paramref name="target"/>'s track — an effect into the/// gap or in place of the card the target names, an instrument in place of the track's@@ -230,6 +282,10 @@ public sealed class DeviceInsertService}if (item.Kind == BrowserItemKind.Preset) return ApplyPreset(item, target);if (t <= 0) return InsertResult.Fail("Select a track first.");+ if (isInstrument && target.Placement == InsertPlacement.ReplaceInstrument)+ return TryReplaceInstrument(item, t, evenRack: true)+ ? new InsertResult { Ok = true, TrackId = t, InstrumentReplaced = true, ShowDevices = true, Status = $"Changed instrument to {item.Name}" }+ : InsertResult.Fail($"Couldn't load {item.Name}.");if (target.Placement != InsertPlacement.Default)switch (item.Kind)@@ -292,7 +348,7 @@ public sealed class DeviceInsertServicecase BrowserItemKind.PluginInstrument:if (TryReplaceInstrument(item, t))return new InsertResult { Ok = true, TrackId = t, InstrumentReplaced = true, Status = $"Changed instrument to {item.Name} (track {t})" };- return InsertResult.Fail("Drop instruments onto the arrangement.");+ return InsertResult.Fail($"Couldn't load {item.Name}.");case BrowserItemKind.Sample when kind == 4: // sample → drum pad (Sampler){int note = NextFreeDrumPad(t);diff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex fb9a499d..bedf1f4e 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -992,6 +992,11 @@ NOTA_API void nota_engine_reset(NotaEngine* engine);/* Instrument identity for save: 0=Synth, 1=Sampler, -1=plugin/unknown,* -2=no instrument (audio/return track). */NOTA_API int32_t nota_track_instrument_kind(const NotaEngine* engine, int32_t track_id);+/* Which instrument the track holds (specs/043), for UI state kept per instrument: the same value+ * while it is edited (a rack edit included) and when it moves to another track or comes back by+ * undo; a new, replaced, pasted or copied instrument has another. 0 = no instrument. Compare it,+ * don't decode it. */+NOTA_API int64_t nota_track_instrument_id(const NotaEngine* engine, int32_t track_id);/* 1 if the track's instrument responds to per-note expression (MPE), else 0. */NOTA_API int32_t nota_track_instrument_supports_mpe(const NotaEngine* engine, int32_t track_id);/* Built-in device kind (0=EQ,1=Comp,2=Reverb,3=Delay,4=Utility) or -1 for a@@ -1385,8 +1390,9 @@ NOTA_API int32_t nota_engine_add_plugin_instrument_track(NotaEngine* engine, int/* Replace the instrument on an existing instrument track with a hosted plugin. */NOTA_API NotaResult nota_track_set_instrument_plugin(NotaEngine* engine, int32_t track_id, int32_t catalog_index);-/* Replace the instrument on an existing instrument track with a fresh built-in synth `kind`.- * Returns NOTA_ERR_UNKNOWN for Racks / unknown kinds or non-instrument tracks. */+/* Replace the instrument on an existing instrument track with a fresh built-in synth `kind`;+ * kind 3 = an empty Instrument Rack, 4 = an empty Drum Rack (specs/043). One undo step.+ * Returns NOTA_ERR_UNKNOWN for unknown kinds or non-instrument tracks. */NOTA_API NotaResult nota_track_set_builtin_instrument(NotaEngine* engine, int32_t track_id, int32_t kind);/* Append catalog plugin `catalog_index` as an insert effect on the track's@@ -1538,7 +1544,7 @@ NOTA_API NotaResult nota_track_remove_device(NotaEngine* engine, int32_t track_/* Device clipboard (#238). Copy keeps a full clone of an audio effect (every param, its* state blob, bypass, sidechain key; a rack or plug-in copies itself) or a MIDI effect;* paste inserts a clone of it at at_index (-1 = the end) as one undo step and returns the- * new index, or <0. clipboard_kind: 0 empty, 1 audio effect, 2 MIDI effect. */+ * new index, or <0. clipboard_kind: 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument. */NOTA_API NotaResult nota_track_copy_device(NotaEngine* engine, int32_t track_id, int32_t device_index);NOTA_API NotaResult nota_track_copy_midi_effect(NotaEngine* engine, int32_t track_id, int32_t index);NOTA_API int32_t nota_device_clipboard_kind(const NotaEngine* engine);@@ -1548,6 +1554,29 @@ NOTA_API int32_t nota_track_paste_midi_effect(NotaEngine* engine, int32_t tr* alone. Returns the clone's index or -1. */NOTA_API int32_t nota_track_duplicate_device(NotaEngine* engine, int32_t track_id, int32_t device_index);NOTA_API int32_t nota_track_duplicate_midi_effect(NotaEngine* engine, int32_t track_id, int32_t index);+/* The track's instrument on the shared device clipboard (specs/043): a full clone — every+ * param, its state, a rack's chains / pads and macros, a plug-in's state, bypass. Replaces+ * whatever the clipboard held. 1 = copied, 0 = no instrument (not an instrument track). */+NOTA_API int32_t nota_track_copy_instrument(NotaEngine* engine, int32_t track_id);+/* Replace track_id's instrument with a fresh clone of the clipboard's instrument; one undo+ * step, the clipboard kept. 0 = done, -1 nothing to paste (the clipboard holds no+ * instrument), -2 not an instrument track, -3 the clone failed (a plug-in that won't load). */+NOTA_API int32_t nota_track_paste_instrument(NotaEngine* engine, int32_t track_id);+/* Move (keep_source 0) or copy (keep_source 1) a device to another track, both tracks in one+ * undo step (specs/043). family: 0 audio effect at `index`, 1 MIDI effect at `index`, 2 the+ * instrument (index ignored). at_index: position on the target, -1 = the end of its section+ * (ignored for the instrument, which replaces the target's).+ * A move takes the device's automation lanes along (index rewritten); a copy takes none. A move+ * of the instrument removes the source track. CV links to the device stay with the source, and+ * a moved MIDI effect's CC target is cleared. A sidechain key whose source is the target track+ * is cleared.+ * Returns the new index (>= 0; 0 for the instrument), -1 bad address or dst == src, -2 the+ * target can't take the family (an instrument / MIDI effect onto an audio, return, group or+ * master track), -3 the clone failed. *out_flags (may be NULL): bit 0 sidechain cleared,+ * bit 1 links dropped, bit 2 source track removed. */+NOTA_API int32_t nota_track_transfer_device(NotaEngine* engine, int32_t src_track_id, int32_t family,+ int32_t index, int32_t dst_track_id, int32_t at_index,+ int32_t keep_source, int32_t* out_flags);/* ⌘G on a device (#257): wrap the audio effect at device_index in a new Audio Effect Rack* in its place (one undo step). Returns the rack's index, or <0 when the device can't move* into a rack chain (not an effect; a sidechain key, automation or a CV link on it).diff --git a/src/native/nota.engine/src/abi/nota_engine_device.cpp b/src/native/nota.engine/src/abi/nota_engine_device.cppindex ce7cae74..e8a00c62 100644--- a/src/native/nota.engine/src/abi/nota_engine_device.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_device.cpp@@ -68,6 +68,13 @@ NotaResult nota_track_copy_midi_effect(NotaEngine* e, int32_t track_id, int32_treturn ENG(e)->copyMidiEffect(track_id, index) ? NOTA_OK : NOTA_ERR_INVALID_ARG;}int32_t nota_device_clipboard_kind(const NotaEngine* e) { return e ? CENG(e)->deviceClipboardKind() : 0; }+int32_t nota_track_copy_instrument(NotaEngine* e, int32_t track_id) { return e && ENG(e)->copyInstrument(track_id) ? 1 : 0; }+int32_t nota_track_paste_instrument(NotaEngine* e, int32_t track_id) { return e ? ENG(e)->pasteInstrument(track_id) : -1; }+int32_t nota_track_transfer_device(NotaEngine* e, int32_t src_track_id, int32_t family, int32_t index, int32_t dst_track_id,+ int32_t at_index, int32_t keep_source, int32_t* out_flags) {+ if (out_flags) *out_flags = 0;+ return e ? ENG(e)->transferDevice(src_track_id, family, index, dst_track_id, at_index, keep_source != 0, out_flags) : -1;+}int32_t nota_device_clipboard_sidechain(const NotaEngine* e) { return (e && CENG(e)->deviceClipboardSidechain()) ? 1 : 0; }int32_t nota_track_paste_device(NotaEngine* e, int32_t track_id, int32_t at_index) {return e ? ENG(e)->pasteDevice(track_id, at_index) : -1;@@ -489,6 +496,9 @@ int32_t nota_pdc_selftest(void) {// ---- Plugin / device kind & id introspection (M7-6) -----------------------+int64_t nota_track_instrument_id(const NotaEngine* e, int32_t track_id) {+ return e ? CENG(e)->trackInstrumentId(track_id) : 0;+}int32_t nota_track_instrument_kind(const NotaEngine* e, int32_t track_id) {return e ? CENG(e)->trackInstrumentKind(track_id) : -2;}diff --git a/src/native/nota.engine/src/devices/Instrument.h b/src/native/nota.engine/src/devices/Instrument.hindex 3569bf7e..320635c4 100644--- a/src/native/nota.engine/src/devices/Instrument.h+++ b/src/native/nota.engine/src/devices/Instrument.h@@ -235,8 +235,19 @@ class Instrument {// copied state). Returns nullptr if the engine should handle it. Message thread.virtual std::shared_ptr<Instrument> clone() const { return nullptr; }+ // Which instrument this is, for the UI's per-card state (specs/043): every new instrument+ // (added, swapped in, copied, cloned) gets a fresh value; an edit that forks the object (a+ // rack) keeps it with adoptUid, and undo brings back the object with its own. Message thread.+ uint64_t uid() const { return uid_; }+ void adoptUid(const Instrument& from) { uid_ = from.uid_; }+private:+ static uint64_t nextUid() {+ static std::atomic<uint64_t> next{1};+ return next.fetch_add(1, std::memory_order_relaxed);+ }std::atomic<bool> bypassed_{false};+ uint64_t uid_ = nextUid();};} // namespace notadiff --git a/src/native/nota.engine/src/engine/CommandQueue.h b/src/native/nota.engine/src/engine/CommandQueue.hindex 2a4faa44..99faab65 100644--- a/src/native/nota.engine/src/engine/CommandQueue.h+++ b/src/native/nota.engine/src/engine/CommandQueue.h@@ -36,6 +36,9 @@ enum class CommandType : uint32_t {// Loop record replace (#29): release a pitch on a track — a note just removed from the take// may still be sounding (played back from an earlier pass). i0 = track id, i1 = pitch.ReleaseNote,+ // A device moved between tracks (specs/043): silence one track's instrument and flush its+ // MIDI effects on the audio thread, which owns their voices. i0 = track id.+ TrackNotesOff,};struct Command {diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex dc0a3a59..6e23348d 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -609,6 +609,7 @@ class Engine {// Instrument identity for save: 0=Synth, 1=Sampler, -1=plugin/unknown,// -2=track has no instrument (audio/return). Message thread only.int32_t trackInstrumentKind(int32_t trackId) const;+ int64_t trackInstrumentId(int32_t trackId) const; // nota_track_instrument_id (specs/043)bool trackInstrumentSupportsMpe(int32_t trackId) const; // per-note expression (MPE)// Built-in device kind for save (see Device::builtinKind), or -1 for a// hosted plugin. Message thread only.@@ -735,7 +736,7 @@ class Engine {// Device clipboard (#238): copy a full clone of an audio / MIDI effect (every param, its// state blob, bypass, sidechain key; a rack or plug-in copies itself), paste a clone of it// into a chain at atIndex (-1 = the end) as one undo step. Paste returns the new index or- // -1. deviceClipboardKind: 0 empty, 1 audio effect, 2 MIDI effect.+ // -1. deviceClipboardKind: 0 empty, 1 audio effect, 2 MIDI effect, 3 instrument (below).bool copyDevice(int32_t trackId, int32_t deviceIndex);bool copyMidiEffect(int32_t trackId, int32_t index);int32_t deviceClipboardKind() const;@@ -744,6 +745,26 @@ class Engine {// A clone of the device right after it (one undo step), clipboard untouched. Returns its index or -1.int32_t duplicateDevice(int32_t trackId, int32_t deviceIndex);int32_t duplicateMidiEffect(int32_t trackId, int32_t index);+ // The instrument on the same clipboard (specs/043): copy keeps a full clone (cloneInstrument:+ // params, state, a rack's chains / pads / macros, a plug-in's state, bypass) and empties the+ // other two families; deviceClipboardKind() is 3 then. Paste replaces the track's instrument+ // with a fresh clone, one undo step: 0 done, -1 nothing to paste, -2 not an instrument+ // track, -3 the clone failed.+ bool copyInstrument(int32_t trackId);+ int32_t pasteInstrument(int32_t trackId);+ // The one place a track's instrument is swapped (Replace, Paste, the built-in / plug-in+ // setters): the old instrument's editor closes, one undo step.+ bool replaceTrackInstrument(int32_t trackId, std::shared_ptr<Instrument> inst);+ // Move (keepSource false) or copy a device to another track, both tracks in one published+ // graph and one undo step (specs/043). family: 0 audio effect, 1 MIDI effect, 2 the+ // instrument (index ignored; it replaces dst's and a move removes the source track).+ // atIndex: -1 = the end of dst's section. A move takes the device's automation lanes along;+ // a copy takes none. Returns the new index (0 for the instrument), -1 bad address or+ // dst == src, -2 dst can't take the family, -3 the clone failed. outFlags (may be null):+ // kTransferSidechainCleared / kTransferLinksDropped / kTransferSourceRemoved.+ static constexpr int32_t kTransferSidechainCleared = 1, kTransferLinksDropped = 2, kTransferSourceRemoved = 4;+ int32_t transferDevice(int32_t srcTrackId, int32_t family, int32_t index, int32_t dstTrackId, int32_t atIndex,+ bool keepSource, int32_t* outFlags);const char* deviceName(int32_t trackId, int32_t deviceIndex) const;int32_t deviceScope(int32_t trackId, int32_t deviceIndex, float* out, int32_t maxSamples) const;// Interactive-device command channel + per-layer waveform (the looper).@@ -1264,7 +1285,9 @@ class Engine {Modulator* modulatorPtr(Track& t, int32_t modId);// Keep CV-link targetDevice indices valid after a device on `track` was removed// (removedIndex>=0) or moved (from/to). Clones the affected owner tracks + republishes.- void remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex, int32_t from, int32_t to);+ // midi: the edit was on the MIDI-effect chain — fix up MidiFx-target links (param sources+ // name insert effects, so they stay); otherwise Device-target links and param sources.+ void remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex, int32_t from, int32_t to, bool midi = false);// Keep automation-lane deviceIndex valid after an effect (midi=false) or MIDI effect// (midi=true) on `nt` was removed (removedIndex>=0; its lanes are dropped) or moved// (from/to). Edits `nt` in place before it is published, so it shares the device@@ -1296,10 +1319,15 @@ class Engine {void reapplyRackMacros(); // after undo/redo: racks drive their shared children againstatic int32_t trackLatency(const Track& t);std::shared_ptr<Instrument> cloneInstrument(const Track& src) const; // duplicateTrack helper+ std::shared_ptr<Instrument> cloneInstrumentFrom(const Instrument& src) const;+ // Copies of the automation lanes on one device of `t` (family as transferDevice; for the+ // instrument, PluginParam lanes with deviceIndex < 0), in lane order.+ std::vector<AutomationLane> deviceLanes(const Track& t, int32_t family, int32_t index) const;std::shared_ptr<Device> cloneDevice(const Device& src) const;std::shared_ptr<MidiDevice> cloneMidiDevice(const MidiDevice& src) const;std::shared_ptr<Device> clipDevice_; // device clipboard (#238): a clone of the copied audio effectstd::shared_ptr<MidiDevice> clipMidi_;+ std::shared_ptr<Instrument> clipInstrument_; // the instrument on the device clipboard (specs/043)int32_t insertDeviceClone(int32_t trackId, std::shared_ptr<Device> dev, int32_t atIndex);int32_t insertMidiEffectClone(int32_t trackId, std::shared_ptr<MidiDevice> md, int32_t atIndex); // ... or of the copied MIDI effect (one of the two at a time)void recomputePdc(); // message thread: realign all tracks@@ -1668,6 +1696,9 @@ class Engine {// live is skipped.int32_t releaseTrack_ = -1;uint32_t releasePitches_[4] = {};+ // Tracks whose voices go silent at the next block (TrackNotesOff command, audio thread).+ int32_t notesOffTracks_[8] = {};+ int32_t notesOffCount_ = 0;// session-slot recording target (M5-4). recordSessionScene_ >= 0 selects slot// mode; recordSlotPlayer_/recordSlotLen_ are read on the audio thread to timediff --git a/src/native/nota.engine/src/engine/Engine_Automation.cpp b/src/native/nota.engine/src/engine/Engine_Automation.cppindex 09edda43..e132ce2f 100644--- a/src/native/nota.engine/src/engine/Engine_Automation.cpp+++ b/src/native/nota.engine/src/engine/Engine_Automation.cpp@@ -564,6 +564,26 @@ void Engine::remapAutomationAfterDeviceChange(Track& nt, bool midi, int32_t remostd::erase_if(overrides_, [&](OverrideTarget& o) { return o.trackId == trackId && laneGone(o.laneIndex); });}+std::vector<AutomationLane> Engine::deviceLanes(const Track& t, int32_t family, int32_t index) const {+ std::vector<AutomationLane> out;+ for (const auto& l : t.automation) {+ bool on = false;+ switch (family) {+ case 0:+ on = (l.target == AutomationTarget::DeviceParam || l.target == AutomationTarget::PluginParam) && l.deviceIndex == index;+ break;+ case 1: on = l.target == AutomationTarget::MidiDeviceParam && l.deviceIndex == index; break;+ case 2: on = l.target == AutomationTarget::PluginParam && l.deviceIndex < 0; break;+ default: break;+ }+ if (on) {+ out.push_back(l);+ out.back().suppressRead = false; // a gesture on the old track doesn't follow it+ }+ }+ return out;+}+bool Engine::automationDeviceRemapSelfTest() {// Two effects, a lane on each: reordering the chain keeps every lane on its own// device; removing a device drops its lanes and shifts the rest.diff --git a/src/native/nota.engine/src/engine/Engine_Devices.cpp b/src/native/nota.engine/src/engine/Engine_Devices.cppindex 764daeb6..8ce90f6a 100644--- a/src/native/nota.engine/src/engine/Engine_Devices.cpp+++ b/src/native/nota.engine/src/engine/Engine_Devices.cpp@@ -6,6 +6,8 @@#include "Engine.h"#include "devices/DeviceFactory.h"#include "devices/racks/MidiRack.h"+#include "devices/racks/RackInstrument.h"+#include "devices/racks/DrumRack.h"#include "devices/effects/Amp.h"#include "devices/effects/AutoFilter.h"#include "media/AudioFile.h"@@ -445,11 +447,7 @@ bool Engine::setTrackInstrumentPlugin(int32_t trackId, int32_t catalogIndex) {const double sr = transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0;auto inst = createPluginInstrument(catalogIndex, sr, kMaxBlock);if (!inst) return false;- auto nt = cloneTrack(*old);- nt->instrument = inst;- republishWithTrack(trackId, nt);- recomputePdc();- return true;+ return replaceTrackInstrument(trackId, std::move(inst));}int32_t Engine::addTrackEffectPlugin(int32_t trackId, int32_t catalogIndex) {@@ -574,13 +572,16 @@ int32_t Engine::addTrackBuiltinDevice(int32_t trackId, int32_t kind) {}std::shared_ptr<Instrument> Engine::cloneInstrument(const Track& src) const {- if (!src.instrument) return nullptr;+ return src.instrument ? cloneInstrumentFrom(*src.instrument) : nullptr;+}++std::shared_ptr<Instrument> Engine::cloneInstrumentFrom(const Instrument& src) const {const double sr = transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0;- if (auto c = src.instrument->clone()) {+ if (auto c = src.clone()) {c->setSampleRate(sr);return c;} // hosted plugin- switch (src.instrument->kind()) { // built-ins+ switch (src.kind()) { // built-inscase 0: {auto s = std::make_shared<Synth>();s->setSampleRate(sr);@@ -589,7 +590,7 @@ std::shared_ptr<Instrument> Engine::cloneInstrument(const Track& src) const {case 1: {auto sm = std::make_shared<Sampler>();sm->setSampleRate(sr);- if (auto* srcSm = dynamic_cast<Sampler*>(src.instrument.get()))+ if (auto* srcSm = dynamic_cast<const Sampler*>(&src))sm->setSample(srcSm->sample(), srcSm->rootNote(), srcSm->loopEnabled());return sm;}@@ -729,15 +730,33 @@ Device* Engine::deviceAt(int32_t trackId, int32_t deviceIndex) const {// Fresh built-in factories live in devices/DeviceFactory.cpp.// Replace an instrument track's instrument with a fresh built-in of `kind` (browser drag onto-// an existing track). Racks and unknown kinds return false so the caller can add a new track.+// an existing track, Replace… in the instrument's menu). 3 and 4 are an empty Instrument Rack /+// Drum Rack (specs/043), as a new rack track starts. Unknown kinds return false so the caller+// can add a new track.bool Engine::setTrackBuiltinInstrument(int32_t trackId, int32_t kind) {auto old = findTrackAuthoring(trackId);if (!old || old->type() != TrackType::Instrument) return false;- auto inst = makeBuiltinInstrument(kind);+ std::shared_ptr<Instrument> inst;+ if (kind == 3) inst = std::make_shared<RackInstrument>();+ else if (kind == 4) inst = std::make_shared<DrumRack>();+ else inst = makeBuiltinInstrument(kind);if (!inst) return false;inst->setSampleRate(transport_.sampleRate() > 0 ? transport_.sampleRate() : 44100.0);+ return replaceTrackInstrument(trackId, std::move(inst));+}++int64_t Engine::trackInstrumentId(int32_t trackId) const {+ auto t = findTrackAuthoring(trackId);+ return t && t->instrument ? static_cast<int64_t>(t->instrument->uid()) : 0;+}++bool Engine::replaceTrackInstrument(int32_t trackId, std::shared_ptr<Instrument> inst) {+ auto old = findTrackAuthoring(trackId);+ if (!old || old->type() != TrackType::Instrument || !inst) return false;+ // The old instrument survives in undo history, so only its window goes.+ if (old->instrument) old->instrument->closeEditor();auto nt = cloneTrack(*old);- nt->instrument = inst;+ nt->instrument = std::move(inst);republishWithTrack(trackId, nt);recomputePdc();return true;@@ -771,6 +790,7 @@ bool Engine::copyDevice(int32_t trackId, int32_t deviceIndex) {if (!c) return false;clipDevice_ = std::move(c);clipMidi_.reset();+ clipInstrument_.reset();return true;}@@ -780,10 +800,191 @@ bool Engine::copyMidiEffect(int32_t trackId, int32_t index) {if (!c) return false;clipMidi_ = std::move(c);clipDevice_.reset();+ clipInstrument_.reset();+ return true;+}++bool Engine::copyInstrument(int32_t trackId) {+ auto t = findTrackAuthoring(trackId);+ if (!t || t->type() != TrackType::Instrument || !t->instrument) return false;+ auto c = cloneInstrumentFrom(*t->instrument);+ if (!c) return false;+ c->setBypassed(t->instrument->bypassed());+ clipInstrument_ = std::move(c);+ clipDevice_.reset();+ clipMidi_.reset();return true;}-int32_t Engine::deviceClipboardKind() const { return clipDevice_ ? 1 : clipMidi_ ? 2 : 0; }+int32_t Engine::pasteInstrument(int32_t trackId) {+ if (!clipInstrument_) return -1;+ auto t = findTrackAuthoring(trackId);+ if (!t || t->type() != TrackType::Instrument) return -2;+ auto c = cloneInstrumentFrom(*clipInstrument_);+ if (!c) return -3;+ c->setBypassed(clipInstrument_->bypassed());+ return replaceTrackInstrument(trackId, std::move(c)) ? 0 : -2;+}++// ---- device transfer between tracks (specs/043) ----------------------------+// Both tracks change in one published graph, so the device never plays on two tracks (or+// none) and one undo puts both back. A move hands the device itself over (a plug-in that won't+// load twice still moves, a Reverb keeps its tail); a copy, or a device whose settings must+// change on the way (a key on the target itself, an Arp's CC target), gets a clone, so the+// object the undo history holds is never edited.+int32_t Engine::transferDevice(int32_t srcId, int32_t family, int32_t index, int32_t dstId, int32_t atIndex,+ bool keepSource, int32_t* outFlags) {+ if (outFlags) *outFlags = 0;+ if (srcId == dstId || family < 0 || family > 2) return -1;+ auto src = findTrackAuthoring(srcId), dst = findTrackAuthoring(dstId);+ if (!src || !dst) return -1;+ const bool midi = family == 1, inst = family == 2;+ if (inst) {+ if (src->type() != TrackType::Instrument || !src->instrument) return -1;+ } else {+ const auto n = midi ? src->midiEffects.size() : src->devices.size();+ if (index < 0 || index >= static_cast<int32_t>(n)) return -1;+ }+ if ((midi || inst) && dst->type() != TrackType::Instrument) return -2;+ if (inst && !keepSource && srcId == kMasterTrackId) return -1;++ int32_t flags = 0;+ // A link to the moved device stays behind: CV links that target it or read it.+ if (!keepSource && !inst) {+ const auto tk = static_cast<int32_t>(midi ? CvTargetKind::MidiFx : CvTargetKind::Device);+ for (auto& ot : authoring_->tracks)+ for (auto& l : ot->cvLinks) {+ const int32_t tgt = l.targetTrack < 0 ? ot->id() : l.targetTrack;+ if ((tgt == srcId && l.targetKind == tk && l.targetDevice == index)+ || (!midi && ot->id() == srcId && l.sourceKind == static_cast<int32_t>(CvSourceKind::Param) && l.sourceDevice == index))+ flags |= kTransferLinksDropped;+ }+ }++ auto ns = (keepSource || inst) ? nullptr : cloneTrack(*src);+ auto nd = cloneTrack(*dst);+ std::vector<AutomationLane> lanes;+ if (!keepSource) lanes = deviceLanes(*src, family, index);+ int32_t at = 0;++ if (family == 0) {+ auto& sd = src->devices[index];+ std::shared_ptr<Device> dev = keepSource ? cloneDevice(*sd) : sd;+ if (!dev) return -3;+ if (dev->sidechainSourceTrackId() == dstId) {+ if (dev == sd) dev = cloneDevice(*sd);+ if (!dev) return -3;+ dev->setSidechainSourceTrackId(-1);+ flags |= kTransferSidechainCleared;+ }+ if (ns) {+ ns->devices.erase(ns->devices.begin() + index);+ remapAutomationAfterDeviceChange(*ns, false, index, -1, -1);+ // An Arp's CC lane addresses the chain by index: drop it from the moved device,+ // shift it past the gap.+ for (auto& m : ns->midiEffects) {+ const int32_t d = m->ccDestDevice();+ if (d < index) continue;+ auto c = cloneMidiDevice(*m);+ if (!c) continue;+ if (d == index) {+ c->setCcDest(-1, -1);+ flags |= kTransferLinksDropped;+ } else+ c->setCcDest(d - 1, m->ccDestParam());+ m = c;+ }+ }+ const int32_t end = static_cast<int32_t>(nd->devices.size());+ at = (atIndex < 0 || atIndex > end) ? end : atIndex;+ nd->devices.insert(nd->devices.begin() + at, dev);+ if (at != end) remapAutomationAfterDeviceChange(*nd, false, -1, end, at);+ } else if (midi) {+ auto& sm = src->midiEffects[index];+ std::shared_ptr<MidiDevice> md = keepSource ? cloneMidiDevice(*sm) : sm;+ if (!md) return -3;+ if (md->ccDestDevice() >= 0) { // its CC target is a device on the old track+ if (md == sm) md = cloneMidiDevice(*sm);+ if (!md) return -3;+ md->setCcDest(-1, -1);+ flags |= kTransferLinksDropped;+ }+ if (ns) {+ ns->midiEffects.erase(ns->midiEffects.begin() + index);+ remapAutomationAfterDeviceChange(*ns, true, index, -1, -1);+ }+ const int32_t end = static_cast<int32_t>(nd->midiEffects.size());+ at = (atIndex < 0 || atIndex > end) ? end : atIndex;+ nd->midiEffects.insert(nd->midiEffects.begin() + at, md);+ if (at != end) remapAutomationAfterDeviceChange(*nd, true, -1, end, at);+ } else {+ std::shared_ptr<Instrument> in = keepSource ? cloneInstrumentFrom(*src->instrument) : src->instrument;+ if (!in) return -3;+ if (keepSource) in->setBypassed(src->instrument->bypassed());+ if (dst->instrument) dst->instrument->closeEditor();+ nd->instrument = in;+ }+ for (auto& l : lanes) {+ if (!inst) l.deviceIndex = at;+ // An instrument lane for a parameter the new track already automates takes that lane's+ // place, so there is one lane per parameter (edits and recording find the first one).+ AutomationLane* same = nullptr;+ if (inst)+ for (auto& d : nd->automation)+ if (d.target == AutomationTarget::PluginParam && d.deviceIndex < 0+ && (l.paramId.empty() ? d.paramId.empty() && d.paramIndex == l.paramIndex : d.paramId == l.paramId)) {+ same = &d;+ break;+ }+ if (same) {+ same->paramIndex = l.paramIndex;+ same->points = std::move(l.points);+ } else+ nd->automation.push_back(std::move(l));+ }++ const bool dropSource = inst && !keepSource;+ if (dropSource) { // the track goes with its effects; it survives in undo history+ for (auto& d : src->devices)+ if (d) d->closeEditor();+ flags |= kTransferSourceRemoved;+ }+ auto g = std::make_shared<Graph>();+ inheritGraphLevel(*g, *authoring_);+ if (srcId == kMasterTrackId && ns) g->masterTrack = ns;+ if (dstId == kMasterTrackId) g->masterTrack = nd;+ g->tracks.reserve(authoring_->tracks.size());+ for (auto& t : authoring_->tracks) {+ if (t->id() == srcId) {+ if (dropSource) continue;+ g->tracks.push_back(ns ? ns : t);+ } else+ g->tracks.push_back(t->id() == dstId ? nd : t);+ }+ publish(std::move(g));+ // CV links into either chain follow the indices: links to the moved device are dropped on the+ // old track, the devices after it shift, and on the new track the ones after the insert shift.+ if (!inst) {+ const int32_t last = static_cast<int32_t>(midi ? nd->midiEffects.size() : nd->devices.size()) - 1;+ if (ns) remapCvLinksAfterDeviceChange(srcId, index, -1, -1, midi);+ if (at != last) remapCvLinksAfterDeviceChange(dstId, -1, last, at, midi);+ }+ // Voices belong to the audio thread: ask it to silence them (AR-4). The old track loses the+ // arp-driven notes of a moved MIDI effect; a moved instrument drops the notes it held there.+ auto notesOff = [this](int32_t trackId) {+ Command c;+ c.type = CommandType::TrackNotesOff;+ c.i0 = trackId;+ commands_.push(c);+ };+ if (midi && ns) notesOff(srcId);+ if (inst && !keepSource) notesOff(dstId);+ recomputePdc();+ if (outFlags) *outFlags = flags;+ return inst ? 0 : at;+}++int32_t Engine::deviceClipboardKind() const { return clipDevice_ ? 1 : clipMidi_ ? 2 : clipInstrument_ ? 3 : 0; }bool Engine::deviceClipboardSidechain() const { return clipDevice_ && clipDevice_->sidechainSourceTrackId() >= 0; }diff --git a/src/native/nota.engine/src/engine/Engine_Modulation.cpp b/src/native/nota.engine/src/engine/Engine_Modulation.cppindex d677cc71..7a5bb9ff 100644--- a/src/native/nota.engine/src/engine/Engine_Modulation.cpp+++ b/src/native/nota.engine/src/engine/Engine_Modulation.cpp@@ -354,8 +354,9 @@ static int32_t remappedMoveIndex(int32_t idx, int32_t from, int32_t to) {return idx;}-void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex, int32_t from, int32_t to) {+void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex, int32_t from, int32_t to, bool midi) {if (!authoring_) return;+ const auto chainKind = static_cast<int32_t>(midi ? CvTargetKind::MidiFx : CvTargetKind::Device);bool anyChange = false;auto g = std::make_shared<Graph>();inheritGraphLevel(*g, *authoring_);@@ -365,7 +366,7 @@ void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex,bool needs = false;for (auto& l : ot->cvLinks) {const int32_t tgt = l.targetTrack < 0 ? ot->id() : l.targetTrack;- const bool paramSrcHere = ownerIsEdited && l.sourceKind == static_cast<int32_t>(CvSourceKind::Param);+ const bool paramSrcHere = !midi && ownerIsEdited && l.sourceKind == static_cast<int32_t>(CvSourceKind::Param);if (tgt == track || paramSrcHere) {needs = true;break;@@ -380,9 +381,9 @@ void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex,kept.reserve(nt->cvLinks.size());for (auto& l : nt->cvLinks) {bool drop = false;- // Target index fix-up (device-target links whose target is the edited track).+ // Target index fix-up (links into the edited chain of the edited track).const int32_t tgt = l.targetTrack < 0 ? nt->id() : l.targetTrack;- if (tgt == track && l.targetKind == static_cast<int32_t>(CvTargetKind::Device)) {+ if (tgt == track && l.targetKind == chainKind) {if (removedIndex >= 0) {if (l.targetDevice == removedIndex) drop = true;else if (l.targetDevice > removedIndex)@@ -391,7 +392,7 @@ void Engine::remapCvLinksAfterDeviceChange(int32_t track, int32_t removedIndex,l.targetDevice = remappedMoveIndex(l.targetDevice, from, to);}// Source index fix-up (param source lives on the owner = edited track).- if (!drop && ownerIsEdited && l.sourceKind == static_cast<int32_t>(CvSourceKind::Param)) {+ if (!drop && !midi && ownerIsEdited && l.sourceKind == static_cast<int32_t>(CvSourceKind::Param)) {if (removedIndex >= 0) {if (l.sourceDevice == removedIndex) drop = true;else if (l.sourceDevice > removedIndex)diff --git a/src/native/nota.engine/src/engine/Engine_Rack.cpp b/src/native/nota.engine/src/engine/Engine_Rack.cppindex be6a84e7..3ecff627 100644--- a/src/native/nota.engine/src/engine/Engine_Rack.cpp+++ b/src/native/nota.engine/src/engine/Engine_Rack.cpp@@ -225,6 +225,7 @@ static std::shared_ptr<RackInstrument> forkRackInstrument(const RackInstrument&if (dynamic_cast<const DrumRack*>(&src)) r = std::make_shared<DrumRack>();else r = std::make_shared<RackInstrument>();r->forkFrom(src);+ r->adoptUid(src); // the same rack to the UI: its card keeps its preset label and A/Br->shareMonoWith(src); // held keys, the sounding note and a glide in progress play onr->setBypassed(src.bypassed());r->folded = src.folded;@@ -357,6 +358,7 @@ bool Engine::rackChainDeviceCopy(int32_t t, int32_t di, int32_t c, int32_t i) {if (!copy) return false;clipDevice_ = std::move(copy);clipMidi_.reset();+ clipInstrument_.reset();return true;}bool Engine::rackChainMidiCopy(int32_t t, int32_t di, int32_t c, int32_t i) {@@ -366,6 +368,7 @@ bool Engine::rackChainMidiCopy(int32_t t, int32_t di, int32_t c, int32_t i) {if (!copy) return false;clipMidi_ = std::move(copy);clipDevice_.reset();+ clipInstrument_.reset();return true;}int32_t Engine::rackChainDevicePaste(int32_t t, int32_t di, int32_t c, int32_t at) {diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex 6c3a910c..2daefb15 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -849,6 +849,9 @@ void Engine::drainCommands() {releasePitches_[c.i1 >> 5] |= 1u << (c.i1 & 31);}break;+ case CommandType::TrackNotesOff:+ if (notesOffCount_ < 8) notesOffTracks_[notesOffCount_++] = c.i0;+ break;case CommandType::Seek:seekedWhileRolling_ |= transport_.isPlaying(); // a jump mid-playback, not Stop→Seek→Playtransport_.seekBeats(c.d0);@@ -1709,6 +1712,20 @@ void Engine::processBlock(float* out, int32_t numFrames) {const bool seeked = seekedThisBlock_, seekedRolling = seekedWhileRolling_;seekedThisBlock_ = seekedWhileRolling_ = false;if ((!playing && renderWasPlaying_) || (playing && renderWasPlaying_ && seekedRolling)) flushArrangementVoices();+ // A device moved between tracks (specs/043): the moved instrument's held notes, or the+ // voices an arp drove on the track it left, stop here, on the thread that owns them.+ if (g)+ for (int32_t k = 0; k < notesOffCount_; ++k)+ for (auto& tptr : g->tracks)+ if (tptr->id() == notesOffTracks_[k]) {+ if (tptr->instrument) {+ tptr->instrument->allNotesOff();+ releaseHeldControllers(*tptr->instrument);+ }+ for (auto& md : tptr->midiEffects)+ if (md) md->reset();+ }+ notesOffCount_ = 0;// Note chase: when playback starts, the playhead jumps (seek) or the loop wraps, clip// notes that began before the playhead but are still held get re-triggered at the// jump point — otherwise a note you start in the middle of stays silent.diff --git a/tests/Nota.SmokeTest/InstrumentChainTests.cs b/tests/Nota.SmokeTest/InstrumentChainTests.csnew file mode 100644index 00000000..43ec1ecc--- /dev/null+++ b/tests/Nota.SmokeTest/InstrumentChainTests.cs@@ -0,0 +1,299 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// The instrument as a first-class device in the chain (specs/043).+// - set_builtin_instrument swaps a track's instrument for an empty Instrument Rack / Drum Rack+// and back, clips and effects untouched, one undo step each.+// - The instrument on the shared device clipboard: copy / paste across tracks keeps every+// param and its state (racks with their chains, pads and mappings), survives the source+// track's removal, and refuses what can't take it.+// - transfer_device moves or copies an audio effect, a MIDI effect or the instrument to another+// track in one undo step: a move takes the device's automation along, a copy takes none, the+// instrument's move replaces the target's and removes the source track, a sidechain key on the+// target itself is cleared.+// Also runnable alone: `dotnet run --project tests/Nota.SmokeTest -- --instrument-chain`.++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class InstrumentChainTests+{+ private const int Volt = 6, Keys = 16, InstrumentRack = 3, DrumRack = 4, Reverb = 2, Eq8 = 0, Compressor = 1, Arp = 0;+ private const int ReverbMix = 12;+ private static readonly int[] InstrumentKinds = { 0, 2, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17 };++ public static IEnumerable<(bool ok, string label)> Run()+ {+ foreach (var r in Replace()) yield return r;+ foreach (var r in Clipboard()) yield return r;+ foreach (var r in Transfer()) yield return r;+ }++ private static bool Same(float a, float b) => Math.Abs(a - b) <= 1e-4f * Math.Max(1f, Math.Abs(a));++ private static float Off(float cur) => Math.Abs(cur - 0.37f) < 1e-3f ? 0.71f : 0.37f;++ private static bool Exists(NotaEngine e, int id)+ {+ for (int i = 0; i < e.TrackCount; i++)+ if (e.TryGetTrackInfo(i, out var ti) && ti.Id == id) return true;+ return false;+ }++ private static int Clips(NotaEngine e, int id)+ {+ for (int i = 0; i < e.TrackCount; i++)+ if (e.TryGetTrackInfo(i, out var ti) && ti.Id == id) return ti.ClipCount;+ return -1;+ }++ private static string Chain(NotaEngine e, int t)+ {+ var k = new int[e.TrackDeviceCount(t)];+ for (int i = 0; i < k.Length; i++) k[i] = e.TrackDeviceBuiltinKind(t, i);+ return string.Join(",", k);+ }++ private static float[] InstParams(NotaEngine e, int t)+ {+ var p = new float[e.PluginParamCount(t, -1)];+ for (int i = 0; i < p.Length; i++) p[i] = e.PluginParamGet(t, -1, i);+ return p;+ }++ private static int FirstDiff(float[] a, float[] b)+ {+ if (a.Length != b.Length) return -2;+ for (int i = 0; i < a.Length; i++) if (!Same(a[i], b[i])) return i;+ return -1;+ }++ // "target:device:param:points" for every lane, in order.+ private static string Lanes(NotaEngine e, int t)+ {+ var s = new List<string>();+ for (int i = 0; i < e.AutomationLaneCount(t); i++)+ {+ var l = e.AutomationLaneInfo(t, i);+ s.Add($"{(int)l.Target}:{l.DeviceIndex}:{l.ParamIndex}:{l.PointCount}");+ }+ return string.Join(" ", s);+ }++ private static IEnumerable<(bool, string)> Replace()+ {+ using var e = new NotaEngine();+ int t = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(t, Volt);+ e.AddMidiClip(t, 0, 4);+ e.AddBuiltinDevice(t, Eq8);+ int tracks = e.TrackCount;++ bool rack = e.SetTrackBuiltinInstrument(t, InstrumentRack);+ yield return (rack && e.TrackInstrumentKind(t) == InstrumentRack && e.RackChainCount(t) == 0+ && Clips(e, t) == 1 && Chain(e, t) == "0" && e.TrackCount == tracks,+ $"instrument chain: Volt → an empty Instrument Rack, clip and EQ kept (kind {e.TrackInstrumentKind(t)})");+ bool drum = e.SetTrackBuiltinInstrument(t, DrumRack);+ yield return (drum && e.TrackInstrumentKind(t) == DrumRack && e.RackChainCount(t) == 0 && Clips(e, t) == 1,+ "instrument chain: → an empty Drum Rack");+ bool back = e.SetTrackBuiltinInstrument(t, Volt);+ yield return (back && e.TrackInstrumentKind(t) == Volt && Chain(e, t) == "0", "instrument chain: → Volt again");+ yield return (e.Undo() && e.TrackInstrumentKind(t) == DrumRack && e.Undo() && e.TrackInstrumentKind(t) == InstrumentRack+ && e.Undo() && e.TrackInstrumentKind(t) == Volt,+ "instrument chain: each swap is one undo step");++ int a = e.AddAudioTrack();+ yield return (!e.SetTrackBuiltinInstrument(a, InstrumentRack) && !e.SetTrackBuiltinInstrument(a, DrumRack),+ "instrument chain: an audio track takes no rack");++ // The instrument's id (review of #350): the same through edits — a rack's forks included —+ // and a move; another for a replacement; back by undo.+ int r = e.AddInstrumentRackTrack();+ long rid = e.TrackInstrumentId(r);+ e.RackAddChain(r, Volt);+ e.RackSetChainName(r, 0, "Lead");+ bool sameAfterEdit = e.TrackInstrumentId(r) == rid && rid != 0;+ int v = e.AddVoltSynthTrack();+ long vid = e.TrackInstrumentId(v);+ e.SetTrackBuiltinInstrument(v, Volt);+ long replaced = e.TrackInstrumentId(v);+ e.Undo();+ bool backByUndo = e.TrackInstrumentId(v) == vid && replaced != vid;+ int to = e.AddInstrumentTrack();+ e.TransferDevice(v, DeviceFamily.Instrument, 0, to, -1, false, out _);+ bool followsMove = e.TrackInstrumentId(to) == vid;+ yield return (sameAfterEdit && backByUndo && followsMove,+ $"instrument chain: the instrument id holds through rack edits and a move, changes on replace, comes back by undo ({sameAfterEdit}, {backByUndo}, {followsMove})");+ }++ private static IEnumerable<(bool, string)> Clipboard()+ {+ using var e = new NotaEngine();+ var bad = new List<string>();+ foreach (int kind in InstrumentKinds)+ {+ int a = e.AddInstrumentTrack(), b = e.AddInstrumentTrack();+ if (!e.SetTrackBuiltinInstrument(a, kind)) { bad.Add($"kind {kind}: not set"); continue; }+ e.SetTrackBuiltinInstrument(b, 0);+ int pc = e.PluginParamCount(a, -1);+ for (int i = 0; i < pc; i++) e.PluginParamSet(a, -1, i, Off(e.PluginParamGet(a, -1, i)));+ var want = InstParams(e, a);+ var wantState = e.GetPluginState(a, -1);+ string name = e.DeviceName(a, -1);+ if (!e.CopyInstrument(a) || e.DeviceClipboardKind() != 3) { bad.Add($"{name}: not copied"); continue; }+ e.RemoveTrack(a); // a cut: the clipboard keeps its own copy+ if (e.PasteInstrument(b) != 0) { bad.Add($"{name}: not pasted"); continue; }+ if (e.TrackInstrumentKind(b) != kind) bad.Add($"{name}: kind {e.TrackInstrumentKind(b)}");+ int diff = FirstDiff(want, InstParams(e, b));+ if (diff != -1) bad.Add($"{name} param {diff}");+ if (!wantState.AsSpan().SequenceEqual(e.GetPluginState(b, -1))) bad.Add($"{name} state");+ if (!(e.Undo() && e.TrackInstrumentKind(b) == 0)) bad.Add($"{name}: undo");+ }+ yield return (bad.Count == 0, $"instrument chain: every built-in instrument copies and pastes with its settings ({string.Join("; ", bad)})");++ // Racks copy themselves: chains, a pad's sample, macro mappings.+ int r = e.AddInstrumentRackTrack();+ int c0 = e.RackAddChain(r, Volt);+ e.RackAddChain(r, Keys);+ int m = e.RackAddMacroMapping(r, 0, c0, -1, 0, 0f, 1f);+ int dst = e.AddInstrumentTrack();+ e.CopyInstrument(r);+ int p = e.PasteInstrument(dst);+ yield return (m >= 0 && p == 0 && e.TrackInstrumentKind(dst) == InstrumentRack && e.RackChainCount(dst) == 2+ && e.RackMappingCount(dst) == e.RackMappingCount(r),+ $"instrument chain: an Instrument Rack pastes with its chains and mappings ({e.RackChainCount(dst)} chains, {e.RackMappingCount(dst)} mappings)");++ int d = e.AddDrumRackTrack();+ string wav = Wav();+ e.RackAddSamplerChain(d, wav, 36, false);+ int dst2 = e.AddInstrumentTrack();+ e.CopyInstrument(d);+ yield return (e.PasteInstrument(dst2) == 0 && e.TrackInstrumentKind(dst2) == DrumRack && e.RackChainCount(dst2) == 1,+ "instrument chain: a Drum Rack pastes with its pad");+ File.Delete(wav);++ int audio = e.AddAudioTrack();+ yield return (e.PasteInstrument(audio) == -2 && Exists(e, audio), "instrument chain: an audio track refuses a pasted instrument");+ int fx = e.AddBuiltinDevice(audio, Eq8);+ e.CopyDevice(audio, fx);+ yield return (e.DeviceClipboardKind() == 1 && e.PasteInstrument(dst) == -1,+ "instrument chain: copying an effect replaces the instrument on the clipboard");+ yield return (!e.CopyInstrument(audio), "instrument chain: an audio track has no instrument to copy");+ }++ private static IEnumerable<(bool, string)> Transfer()+ {+ using var e = new NotaEngine();++ // An audio effect with a lane, moved: the lane goes along, the source's lanes after it shift.+ int t1 = e.AddAudioTrack(), t2 = e.AddAudioTrack();+ int rv = e.AddBuiltinDevice(t1, Reverb);+ int eq = e.AddBuiltinDevice(t1, Eq8);+ e.AddBuiltinDevice(t2, Compressor);+ int lr = e.AddAutomationLane(t1, AutomationTarget.DeviceParam, rv, ReverbMix);+ e.SetAutomationPoints(t1, lr, new[] { new AutomationPoint(0, 0.2f), new AutomationPoint(4, 0.8f) });+ int le = e.AddAutomationLane(t1, AutomationTarget.DeviceParam, eq, 0);+ e.SetAutomationPoints(t1, le, new[] { new AutomationPoint(0, 0.5f) });+ string lanes1 = Lanes(e, t1), lanes2 = Lanes(e, t2);+ int at = e.TransferDevice(t1, DeviceFamily.Audio, rv, t2, -1, false, out var f0);+ yield return (at == 1 && Chain(e, t1) == "0" && Chain(e, t2) == "1,2" && f0 == TransferFlags.None,+ $"instrument chain: a Reverb moves to the end of another track ({Chain(e, t1)} | {Chain(e, t2)})");+ yield return (Lanes(e, t1) == "2:0:0:1" && Lanes(e, t2) == $"2:1:{ReverbMix}:2",+ $"instrument chain: its lane goes along, the EQ's lane shifts ({Lanes(e, t1)} | {Lanes(e, t2)})");+ yield return (e.Undo() && Chain(e, t1) == "2,0" && Chain(e, t2) == "1" && Lanes(e, t1) == lanes1 && Lanes(e, t2) == lanes2,+ "instrument chain: one undo puts both tracks back");++ // A copy (⌥-drag): the source is untouched, no lane on the target.+ at = e.TransferDevice(t1, DeviceFamily.Audio, rv, t2, 0, true, out _);+ yield return (at == 0 && Chain(e, t1) == "2,0" && Chain(e, t2) == "2,1" && Lanes(e, t1) == lanes1 && Lanes(e, t2) == lanes2,+ $"instrument chain: a copy leaves the source and carries no lane ({Chain(e, t2)}, {Lanes(e, t2)})");+ yield return (e.TransferDevice(t1, DeviceFamily.Audio, 0, t1, -1, false, out _) == -1, "instrument chain: onto its own track → −1");+ yield return (e.TransferDevice(t1, DeviceFamily.Audio, 9, t2, -1, false, out _) == -1, "instrument chain: a bad index → −1");++ // A MIDI effect: between instrument tracks only.+ int i1 = e.AddInstrumentTrack(), i2 = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(i1, Volt); e.SetTrackBuiltinInstrument(i2, Keys);+ int arp = e.AddMidiEffect(i1, Arp);+ yield return (e.TransferDevice(i1, DeviceFamily.Midi, arp, t1, -1, false, out _) == -2 && e.TrackMidiEffectCount(i1) == 1,+ "instrument chain: a MIDI effect won't go to an audio track");+ yield return (e.TransferDevice(i1, DeviceFamily.Midi, arp, i2, -1, false, out _) == 0+ && e.TrackMidiEffectCount(i1) == 0 && e.TrackMidiEffectCount(i2) == 1 && e.MidiEffectKind(i2, 0) == Arp,+ "instrument chain: an Arp moves between instrument tracks");++ // The instrument: replaces the target's, takes its lane, removes the source track.+ int pc = e.PluginParamCount(i1, -1);+ for (int i = 0; i < pc; i++) e.PluginParamSet(i1, -1, i, Off(e.PluginParamGet(i1, -1, i)));+ var want = InstParams(e, i1);+ e.AddMidiClip(i1, 0, 4);+ e.AddPluginAutomationLane(i1, -1, e.PluginParamId(i1, -1, 0));+ int tracks = e.TrackCount;+ int r = e.TransferDevice(i1, DeviceFamily.Instrument, 0, i2, -1, false, out var fi);+ yield return (r == 0 && !Exists(e, i1) && e.TrackCount == tracks - 1 && e.TrackInstrumentKind(i2) == Volt+ && FirstDiff(want, InstParams(e, i2)) == -1 && fi.HasFlag(TransferFlags.SourceTrackRemoved),+ $"instrument chain: Volt moves onto the Keys track and its own track goes (kind {e.TrackInstrumentKind(i2)}, flags {fi})");+ bool laneMoved = false;+ for (int i = 0; i < e.AutomationLaneCount(i2); i++)+ {+ var l = e.AutomationLaneInfo(i2, i);+ laneMoved |= l.Target == AutomationTarget.PluginParam && l.DeviceIndex < 0;+ }+ yield return (laneMoved, $"instrument chain: the instrument's lane moves with it ({Lanes(e, i2)})");+ yield return (e.Undo() && Exists(e, i1) && Clips(e, i1) == 1 && e.TrackInstrumentKind(i1) == Volt && e.TrackInstrumentKind(i2) == Keys+ && e.TrackCount == tracks,+ "instrument chain: one undo brings back both tracks and the clip");+ yield return (e.TransferDevice(i1, DeviceFamily.Instrument, 0, t1, -1, false, out _) == -2 && Exists(e, i1)+ && e.TrackInstrumentKind(i1) == Volt,+ "instrument chain: an instrument won't go to an audio track");+ r = e.TransferDevice(i1, DeviceFamily.Instrument, 0, i2, -1, true, out var fc);+ yield return (r == 0 && Exists(e, i1) && e.TrackInstrumentKind(i1) == Volt && e.TrackInstrumentKind(i2) == Volt+ && !fc.HasFlag(TransferFlags.SourceTrackRemoved),+ "instrument chain: an instrument copy leaves the source track");++ // CV links into the MIDI-effect chain follow it (review of #350): with two MIDI effects,+ // moving the first drops the link to it and the second's link shifts to index 0.+ int m1 = e.AddInstrumentTrack(), m2 = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(m1, Volt); e.SetTrackBuiltinInstrument(m2, Volt);+ e.AddMidiEffect(m1, Arp); e.AddMidiEffect(m1, 1);+ int lfo = e.ModulatorAdd(m1, 0);+ e.CvLinkAddToTarget(m1, lfo, 2, -1, 0, 0);+ e.CvLinkAddToTarget(m1, lfo, 2, -1, 1, 0);+ e.TransferDevice(m1, DeviceFamily.Midi, 0, m2, -1, false, out var fm);+ bool oneLeft = e.CvLinkCount(m1) == 1 && e.CvLinkDevice(m1, 0) == 0 && e.CvLinkTargetKind(m1, 0) == 2;+ yield return (oneLeft && fm.HasFlag(TransferFlags.LinksDropped),+ $"instrument chain: a moved MIDI effect's CV link is dropped and the next one's shifts (links {e.CvLinkCount(m1)}, device {(e.CvLinkCount(m1) > 0 ? e.CvLinkDevice(m1, 0) : -9)}, flags {fm})");++ // One lane per instrument parameter (review of #350): moving an instrument onto a track+ // that automates the same parameter replaces that lane instead of adding a second one.+ int a1 = e.AddInstrumentTrack(), a2 = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(a1, Volt); e.SetTrackBuiltinInstrument(a2, Volt);+ string pid = e.PluginParamId(a1, -1, 0);+ int la = e.AddPluginAutomationLane(a1, -1, pid);+ e.SetAutomationPoints(a1, la, new[] { new AutomationPoint(0, 0.1f), new AutomationPoint(2, 0.9f), new AutomationPoint(4, 0.5f) });+ int lb = e.AddPluginAutomationLane(a2, -1, pid);+ e.SetAutomationPoints(a2, lb, new[] { new AutomationPoint(0, 0.3f) });+ int lanesBefore = e.AutomationLaneCount(a2);+ e.TransferDevice(a1, DeviceFamily.Instrument, 0, a2, -1, false, out _);+ yield return (e.AutomationLaneCount(a2) == lanesBefore && e.AutomationLaneInfo(a2, lb).PointCount == 3,+ $"instrument chain: a moved instrument's lane takes the place of the target's lane for the same parameter ({e.AutomationLaneCount(a2)} lanes, {e.AutomationLaneInfo(a2, lb).PointCount} points)");++ // A sidechain key on the target itself is cleared.+ int k = e.AddAudioTrack();+ int comp = e.AddBuiltinDevice(t2, Compressor);+ e.SetDeviceSidechainSource(t2, comp, k);+ int moved = e.TransferDevice(t2, DeviceFamily.Audio, comp, k, -1, false, out var fs);+ yield return (moved >= 0 && e.DeviceSidechainSource(k, moved) == -1 && fs.HasFlag(TransferFlags.SidechainCleared),+ $"instrument chain: a Compressor keyed from the target loses its key there (flags {fs})");+ }++ private static string Wav()+ {+ const int rate = 44100;+ var path = Path.Combine(Path.GetTempPath(), $"nota-043-{Guid.NewGuid():N}.wav");+ var x = new float[rate / 4 * 2];+ for (int i = 0; i < x.Length / 2; i++) x[2 * i] = x[2 * i + 1] = 0.5f * (float)Math.Sin(2 * Math.PI * 60 * i / rate);+ using (var w = new Nota.Infrastructure.WavWriter(path, rate, 2, WavBitDepth.Float32)) w.WriteFrames(x, x.Length / 2);+ return path;+ }+}diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex fe215b03..43cf329e 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -436,6 +436,14 @@ if (args.Length >= 1 && args[0] == "--device-copy")Console.WriteLine(failures == 0 ? "DEVICE COPY PASSED" : $"DEVICE COPY FAILED ({failures})");return failures == 0 ? 0 : 1;}+// The instrument as a device in the chain (specs/043) alone: `--instrument-chain`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--instrument-chain")+{+ Console.WriteLine("-- instrument chain --");+ foreach (var (ok, label) in InstrumentChainTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "INSTRUMENT CHAIN PASSED" : $"INSTRUMENT CHAIN FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Drum Rack one-shot pads, pad audition, warp off/on alone: `--pad-warp`. Also part of the full run.if (args.Length >= 1 && args[0] == "--pad-warp"){@@ -14366,7 +14374,10 @@ Console.WriteLine("-- MCP tools --");Check(re.TrackInstrumentKind(t) == 9, $"instrument is now Operator ({re.TrackInstrumentKind(t)})");Check(re.SetTrackBuiltinInstrument(t, 1), "swap to Sampler succeeds");Check(re.TrackInstrumentKind(t) == 1, "instrument is now Sampler");- Check(!re.SetTrackBuiltinInstrument(t, 3), "swap to a Rack kind is rejected");+ // specs/043: Replace… can pick a rack — an empty one, as a new rack track starts.+ Check(re.SetTrackBuiltinInstrument(t, 3) && re.TrackInstrumentKind(t) == 3 && re.RackChainCount(t) == 0,+ "swap to an Instrument Rack gives an empty rack");+ Check(!re.SetTrackBuiltinInstrument(t, 99), "swap to an unknown kind is rejected");int at = re.AddAudioTrack();Check(!re.SetTrackBuiltinInstrument(at, 6), "audio track rejects an instrument swap");}@@ -15138,6 +15149,8 @@ Console.WriteLine("-- device remove undo --");foreach (var (ok, label) in DeviceRemoveUndoTests.Run()) Check(ok, label);Console.WriteLine("-- device copy + rack undo --");foreach (var (ok, label) in DeviceCopyTests.Run()) Check(ok, label);+Console.WriteLine("-- instrument chain --");+foreach (var (ok, label) in InstrumentChainTests.Run()) Check(ok, label);// --- racks redesign (specs/040): v8 compatibility, mapping rules, MIDI racks, chain MIDI effects ---foreach (var (title, run) in RackSections())