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) Discard and retry the take being recorded (#185) (#486)
Egor Khindikaynenee5bb1d84913
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex f6a6e6ca..c0ab26e8 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -23,6 +23,14 @@ Entry categories: `Added`, `Changed`, `Fixed`, `Removed`.## [Unreleased]### Added+- **Discard and retry take** (#185): ⌘. (Ctrl+. on Windows and Linux) — also in the+ Transport menu, the command palette and over MCP (`retry_take`) — throws away the take+ being recorded and records it again in one press. In the Arrangement the playhead goes back+ to where the transport was started — the take's start, counting in again if it did, or+ where Play was pressed when you punched in, so the run-up plays again. In the Session view+ only the recording slot's take goes: the other clips keep playing, and the slot shows it is+ waiting until it records again from the next launch quantum. Nothing of the discarded take+ stays — not its audio, loop passes, notes, controllers or automation, and not an undo step.- **Preview a translation**: **Load file…** in Settings → Appearance → Language runs Nota in alanguage file from your disk after a restart and lists the entries it cannot use;`NOTA_UI_LANGUAGE=/path/to/file.json` does the same for one run.diff --git a/FEATURES.md b/FEATURES.mdindex 9010e2cc..644f3b9c 100644--- a/FEATURES.md+++ b/FEATURES.md@@ -101,6 +101,11 @@ on a pool of render threads, export and freeze use every core, and an idle enginloop seam keep sounding and release tails ring into the next pass; an arpeggiator keeps itspattern going across the seam.- **Metronome** and **count-in** before recording, Session slot takes from stop included (notes played on the count-in are recorded).+- **Discard and retry take** (⌘. / Ctrl+., Transport menu, palette, MCP `retry_take`): drops+ the take being recorded — audio, loop passes, notes, controllers, automation, with no undo+ step — and records again. The Arrangement goes back to where the transport was started+ (the take's start with the count-in again, or the Play position for a punch-in); a Session+ slot records again from the next launch quantum, shown as waiting, while other clips play on.- **Transport shortcuts** (Space play/stop, Enter stop, R/M/A, clip copy-paste, typingnotes, undo/redo) work in detached windows too.@@ -1445,7 +1450,8 @@ appears in the UI immediately.Coverage:- **Transport**: play/stop, tempo, time signature, loop, metronome, loop record mode- (`set_loop_record_mode`; `get_transport` reports it).+ (`set_loop_record_mode`; `get_transport` reports it), discard and retry the take being+ recorded (`retry_take`).- **Project**: `get_overview` (a full snapshot); the arrangement's sections(`list_sections`, `set_sections`) and rearranging the song by them (`move_section`,`duplicate_section_with_content`, `delete_section_with_content`); version history — `list_versions` (with whatdiff --git a/specs/078-discard-and-retry-take/checklists/requirements.md b/specs/078-discard-and-retry-take/checklists/requirements.mdnew file mode 100644index 00000000..8e42f541--- /dev/null+++ b/specs/078-discard-and-retry-take/checklists/requirements.md@@ -0,0 +1,37 @@+# Specification Quality Checklist: Discard and Retry a Take++**Purpose**: Validate specification completeness and quality before proceeding to planning+**Created**: 2026-11-04+**Feature**: [spec.md](../spec.md)++## Content Quality++- [x] No implementation details (languages, frameworks, APIs)+- [x] Focused on user value and business needs+- [x] Written for non-technical stakeholders+- [x] All mandatory sections completed++## Requirement Completeness++- [x] No [NEEDS CLARIFICATION] markers remain+- [x] Requirements are testable and unambiguous+- [x] Success criteria are measurable+- [x] Success criteria are technology-agnostic (no implementation details)+- [x] All acceptance scenarios are defined+- [x] Edge cases are identified+- [x] Scope is clearly bounded+- [x] Dependencies and assumptions identified++## Feature Readiness++- [x] All functional requirements have clear acceptance criteria+- [x] User scenarios cover primary flows+- [x] Feature meets measurable outcomes defined in Success Criteria+- [x] No implementation details leak into specification++## Notes++- Resolved 2026-11-04: Session slot recording in scope (US4, FR-012–FR-014); a punched-in+ take restarts where playback was started (FR-005).+- The Nota Context and Compliance sections name engine/managed areas by design (template+ requirement); the user-facing sections stay implementation-free.diff --git a/specs/078-discard-and-retry-take/contracts/c-abi.md b/specs/078-discard-and-retry-take/contracts/c-abi.mdnew file mode 100644index 00000000..ef713d71--- /dev/null+++ b/specs/078-discard-and-retry-take/contracts/c-abi.md@@ -0,0 +1,22 @@+# Contract: C ABI (`nota_engine.h`)++```c+/* Discard the take in progress and record it again (#185, specs/078). Drops everything the+ * take wrote — audio, loop passes, MIDI notes/controllers/expression, a clip it created,+ * automation written while recording — with no undo or redo step, then:+ * - Arrangement: returns to where the transport was started for the take (its start beat+ * when the take started the transport, else the Play position) and records again, with+ * the count-in again when the take had one;+ * - Session slot: leaves other clips and the transport running and records into the same+ * slot again from the next launch quantum (immediately when quantize is off).+ * Returns 0 nothing was recording (no change), 1 Arrangement take retried,+ * 2 Session slot take retried, -1 discarded but recording could not restart+ * (see nota_engine_record_start_status). Message thread. */+NOTA_API int32_t nota_engine_retry_take(NotaEngine* engine);++/* Slot state: 0 empty, 1 filled, 2 queued, 3 playing, 4 recording,+ * 5 record pending (the slot will record from the next quantum). */+NOTA_API int32_t nota_session_slot_state(const NotaEngine* engine, int32_t track_id, int32_t scene);+```++Managed mirror: `IAudioEngine.RetryTake()` → `RetryTakeResult { None, Arrangement, Session, Failed }`.diff --git a/specs/078-discard-and-retry-take/contracts/commands.md b/specs/078-discard-and-retry-take/contracts/commands.mdnew file mode 100644index 00000000..b8119709--- /dev/null+++ b/specs/078-discard-and-retry-take/contracts/commands.md@@ -0,0 +1,20 @@+# Contract: App command, shortcut, MCP++## Command catalog++| Id | Title (en key) | Group | Default shortcut | Keywords |+|----|----------------|-------|------------------|----------|+| `transport.retryTake` | `commands.discard_and_retry_take` — "Discard and retry take" | Transport | `⌘.` (macOS) / `Ctrl+.` | `undo restart retry discard take again redo record over` |++- Also in the Transport menu, after Record.+- Listed on Preferences → Shortcuts (nota-shortcuts skill).+- Status line after the command: `transport.take_discarded_retrying` "Take discarded — recording+ again" / `transport.no_take_to_discard` "Nothing is recording — no take to discard" /+ the existing record-start failure messages for `Failed`.+- All new strings go to `en.json` (and the other bundled languages via the localization flow).++## MCP++`retry_take` (TransportTools): "Discard the take being recorded and record it again from the+same place (Arrangement) or the next launch quantum (Session slot). Leaves no undo step."+Returns `{ "result": "none" | "arrangement" | "session" | "failed" }`.diff --git a/specs/078-discard-and-retry-take/data-model.md b/specs/078-discard-and-retry-take/data-model.mdnew file mode 100644index 00000000..6d0276ad--- /dev/null+++ b/specs/078-discard-and-retry-take/data-model.md@@ -0,0 +1,42 @@+# Data Model: Discard and Retry a Take++Engine-side state only; nothing new is persisted in the project file.++## TakeAttempt (engine, message thread)++One Record press or one retry, until Stop or the next retry.++| Field | Meaning |+|-------|---------|+| `active` | an attempt is open (set where `recording_` becomes true for a take) |+| `kind` | Arrangement or Session slot (mutually exclusive, research R4) |+| `baseTracks` | `trackId → shared_ptr<const Track>` as they were before the attempt wrote them: record targets at start; a track whose automation write begins during the attempt is added then (first write wins) |+| `undoBase` | `undoStack_` size when the attempt began (decremented when depth trimming drops the oldest entry) |+| `redoSaved` | the redo stack as it was when the attempt began |+| `countedIn` | the attempt started from stop with a count-in (Arrangement) |+| `startedTransport` / `returnBeat` | existing `recordStartedTransport_` / `recordReturnBeat_` |+| `sessionTrackId`, `sessionScene` | the slot (Session attempts) |+| `retryStartBeat` | Session audio retry: capture before this beat is trimmed; `NaN` otherwise |++**Lifecycle**++```text+idle ──Record/recordSessionSlot──▶ open ──Stop──▶ idle (take materialised: 1 undo step)+ │+ └─retry──▶ discard ──▶ open (fresh attempt, same targets)+```++- Stop closes the attempt and drops `baseTracks` / `redoSaved` (no lingering references).+- A count-in cancelled by Stop closes it as today (`cancelSessionCountIn`).++## takeEpoch (engine, atomic)++`uint32_t`, bumped by every discard. The audio thread copies it into each queued+`RecordedNote` / `RecordedCtl` / `RecordedExpr`; `poll()` ignores entries whose epoch is not+current (research R2).++## Session slot state++`nota_session_slot_state` gains **5 = record pending**: the slot is the record target but the+take has not begun capturing (MIDI player still queued, or the playhead before+`retryStartBeat`). 0 empty, 1 filled, 2 queued, 3 playing, 4 recording are unchanged.diff --git a/specs/078-discard-and-retry-take/plan.md b/specs/078-discard-and-retry-take/plan.mdnew file mode 100644index 00000000..d7d1c80c--- /dev/null+++ b/specs/078-discard-and-retry-take/plan.md@@ -0,0 +1,176 @@+# Implementation Plan: Discard and Retry a Take++**Branch**: `feat/discard-and-retry-recording` | **Date**: 2026-11-04 | **Spec**: [spec.md](spec.md)++**Input**: Feature specification from `specs/078-discard-and-retry-take/spec.md`+(issue [nota-daw/nota#185](https://github.com/nota-daw/nota/issues/185))++## Summary++One command — "Discard and retry take", `⌘.` — throws away the take being recorded and records+it again. The engine already keeps immutable track snapshots (AR-5), so a take attempt+remembers the pre-take `Track` objects it may write and the undo/redo stacks; a discard+republishes those tracks raw, trims the undo entries the take pushed and restores redo+(research R1). Late MIDI from the audio thread is fenced with a take epoch (R2). The+Arrangement restarts from where the transport was started, counting in again when the take did+(R3); a Session slot restarts on the next launch quantum with a new "record pending" slot state+while the rest of the Session keeps playing (R4). The app exposes it through the command+catalog (menu, palette, shortcut), MCP and a status message.++## Nota: Read Before Planning++- **Engine work** → [`ARCHITECTURE.md`](../../ARCHITECTURE.md): AR-4, AR-5, AR-6, AR-7, AR-9.+- **UI work** → [`DESIGN.md`](../../DESIGN.md): the pending slot reuses the Session grid's+ existing record/queued visuals.+- **Anything** → [`CONTRIBUTING.md`](../../CONTRIBUTING.md).++## Technical Context++**Language/Version**: C++20 (engine), C# / .NET 10 (managed app, MCP, smoke test)++**Primary Dependencies**: none new++**Storage**: none — nothing new in the project file; a discarded take never enters the graph,+so save/autosave never write it (R5)++**Audio-Thread Impact**: one relaxed atomic load of the take epoch per block, copied into the+already-queued recorded-event structs (a new `uint32_t` field). No allocation, lock or I/O+(AR-6). Discard, restore and restart run on the message thread and publish immutable graphs+(AR-5); transport moves go through the existing command queue (AR-4, AR-9).++**Testing**: `tests/Nota.SmokeTest` (offline render through the C ABI) — new `RetryTakeTests`;+`PaletteTests` for the catalog entry++**Target Platform**: macOS, Windows, Linux (desktop)++**Project Type**: desktop app (native engine + managed UI)++**Performance Goals**: retry completes within one UI tick; no extra dropout beyond the+transport restart (SC-005)++**Constraints**: real-time safety (AR-6); pure C ABI (AR-7)++**Scale/Scope**: ~1 engine file new (`Engine_TakeRetry.cpp`), edits in recording / render /+session / undo; 1 ABI call; managed: engine wrapper, catalog, transport VM, MCP, localization,+Session grid state 5, smoke test++## Constitution Check++| Principle | Status |+|-----------|--------|+| 0 Approved issue | ✅ #185 carries `approved` |+| I Real-time safety | ✅ only an atomic epoch on the audio thread; restore/publish on the message thread |+| II Boundary discipline | ✅ one new C function, plain `int32_t` return; no JUCE |+| III Licensing | ✅ new files get the SPDX header; no dependency |+| IV Verification gate | ✅ `RetryTakeTests` in the smoke test |+| V One logical change | ✅ one command and what it needs |+| VI Docs in sync | ✅ CHANGELOG, FEATURES.md, Shortcuts page, user docs (EN+RU) |+| VII Spec first | ✅ this spec/plan/tasks |+| VIII Rules not weakened | ✅ |++Post-design re-check: unchanged — the design keeps all audio-thread work to the epoch stamp.++## Design++### Engine (`src/native/nota.engine`)++1. **Take attempt** (`Engine.h`, new `src/engine/Engine_TakeRetry.cpp`): struct per+ [data-model.md](data-model.md). `openTakeAttempt(kind)` is called where an Arrangement take+ (`setRecording(true)`, before the MIDI clip is created) or a Session take+ (`recordSessionSlot`, before `addSessionMidiClip`) begins; `noteTakeTrack(trackId)` from+ `beginAutomationWrite` while an attempt is open; `closeTakeAttempt()` on Stop / finalize /+ count-in cancel. `pushUndo` decrements `undoBase` when it trims the oldest entry.+2. **Discard** (`discardTake()`): end automation writes without committing; abort the audio+ capture without materialising (`abortAudioRecording()`: taps off, drain, clear buffers and+ passes); clear MIDI fold state (`takeNotes_`, `takeCtls_`, `ctlBatch_`, `pendingExpr_`,+ ctl-stop); bump `takeEpoch_`; republish base tracks raw — Arrangement: whole track objects;+ Session: only the target slot copied from the base track into the current track; run the+ undo-restore follow-ups (`placeTakesForTempo`, `recomputePdc`, …) only when a restored track's+ chains differ; trim `undoStack_` to `undoBase`, restore `redoStack_`.+3. **Restart** (`retryTake()`): Arrangement — remember `countedIn` / `startedTransport` /+ `returnBeat`; discard; `transportStop()`; seek to `returnBeat` when the take started the+ transport; call the internal start with `allowCountIn = countedIn`. Session — remember+ track/scene/audio; discard; for audio set `retryStartBeat_` = next launch-quantum boundary+ (now when quantize is 0); call `recordSessionSlot(track, scene)` without touching other+ players or the transport.+4. **Epoch**: add `uint32_t epoch` to `RecordedNote`, `RecordedCtl`, `RecordedExpr`; the audio+ thread loads `takeEpoch_` once per block; `poll()` / `collectRecordedExpr()` skip stale ones.+5. **Session audio trim**: `stopAudioRecording()` (session branch) drops frames before+ `retryStartBeat_` and resets it.+6. **Slot state 5**: `sessionSlotState` returns 5 when this slot is the record target and the+ MIDI player isn't playing it yet, or the audio playhead is before `retryStartBeat_`.+7. **ABI**: `nota_engine_retry_take` in `nota_engine.h` + `src/abi/nota_engine_core.cpp`;+ doc for slot state 5 ([contracts/c-abi.md](contracts/c-abi.md)).++### Managed (`src/managed`)++- `Nota.Infrastructure/Interop`: P/Invoke + `NotaEngine.RetryTake()`; `IAudioEngine` ++ `RetryTakeResult` enum (`Nota.Application/Engine`). Any test doubles implementing+ `IAudioEngine` get the member.+- `Nota.Application/Palette/CommandCatalog.cs`: `transport.retryTake`, `Shortcut.Cmd('.')`.+- `Nota.Presentation/ViewModels/TransportViewModel.cs`: `RetryTakeCommand` → engine, keeps+ `RecordOn` true, raises `TracksChanged` and the status message.+- `Nota.App`: bind the command id (`MainWindow.Commands.cs`), Transport menu item+ (`MainWindow.axaml`), Session grid draws state 5 as record-pending (`SessionView.Grid.cs`),+ refresh after retry.+- `Nota.Mcp/Tools/TransportTools.cs`: `retry_take`.+- Localization keys in `Nota.Application/Localization/en.json` (+ bundled languages per the+ localization workflow).++### Tests & docs++- `tests/Nota.SmokeTest/RetryTakeTests.cs` + registration in `Program.cs`, scenarios in+ [quickstart.md](quickstart.md); `PaletteTests` expectation for the new shortcut if it lists them.+- `CHANGELOG.md` `[Unreleased]` → Added; FEATURES.md (nota-features); Shortcuts page+ (nota-shortcuts); user docs EN+RU (nota-docs).++## Project Structure++### Documentation (this feature)++```text+specs/078-discard-and-retry-take/+├── spec.md+├── plan.md+├── research.md+├── data-model.md+├── quickstart.md+├── contracts/+│ ├── c-abi.md+│ └── commands.md+├── checklists/requirements.md+└── tasks.md # /speckit-tasks+```++### Source Code (repository root)++```text+src/native/nota.engine/+├── include/nota/nota_engine.h # nota_engine_retry_take, slot state 5 doc+├── src/abi/nota_engine_core.cpp # ABI shim+└── src/engine/+ ├── Engine.h # TakeAttempt, takeEpoch_, retryStartBeat_+ ├── Engine_TakeRetry.cpp # NEW: open/close/discard/retry+ ├── Engine_Recording.cpp # open/close hooks, abortAudioRecording, session trim+ ├── Engine_Render.cpp # epoch stamp + stale filter in poll()+ ├── Engine_Session.cpp # open hook, slot state 5+ ├── Engine_Automation.cpp # noteTakeTrack on write begin+ └── Engine.cpp # pushUndo trims undoBase+src/managed/+├── Nota.Application/Engine/IAudioEngine.cs, EngineContracts.cs+├── Nota.Application/Palette/CommandCatalog.cs+├── Nota.Application/Localization/en.json+├── Nota.Infrastructure/Interop/NativeMethods.cs, NotaEngine*.cs+├── Nota.Presentation/ViewModels/TransportViewModel.cs+├── Nota.App/MainWindow.Commands.cs, MainWindow.axaml, SessionView.Grid.cs+└── Nota.Mcp/Tools/TransportTools.cs+tests/Nota.SmokeTest/RetryTakeTests.cs, Program.cs+```++**Structure Decision**: the existing engine/managed split; one new engine translation unit+keeps the attempt logic out of the already long recording file (it must be added to the+engine's CMake source list).++## Complexity Tracking++None.diff --git a/specs/078-discard-and-retry-take/quickstart.md b/specs/078-discard-and-retry-take/quickstart.mdnew file mode 100644index 00000000..5529ecd7--- /dev/null+++ b/specs/078-discard-and-retry-take/quickstart.md@@ -0,0 +1,33 @@+# Quickstart: verify Discard and Retry++## Automated (the PR gate)++```bash+scripts/build.sh+```++The smoke test `RetryTakeTests` (tests/Nota.SmokeTest) drives the engine offline and checks:++1. Arrangement MIDI from stop with count-in: notes, retry mid-take → clip gone (or back to its+ pre-take notes), playhead at the take start, count-in running; play again, stop → only the+ second take's notes; one `Undo` → the pre-first-take state; `CanRedo` false.+2. Arrangement audio (internal resample source, no device): retry → no clip and no take lane;+ stop after retry → one clip starting at the original start beat.+3. Loop recording with ≥2 passes → retry → no new take lanes; earlier takes intact.+4. Punch-in while playing from beat 4, take begun at beat 8 → retry → playhead at 4, recording,+ no count-in.+5. Automation written during the take → retry → lane back to pre-take points.+6. A note released after the retry → not in the new take (epoch guard).+7. Session MIDI slot with another slot playing on another track → retry → the other track's+ slot still playing, target slot state 5 until the quantum, then 4; stop → slot plays.+8. Session audio slot retry → take trimmed to start on the quantum boundary.+9. `RetryTake` with nothing recording → `None`, project unchanged.+10. Palette/catalog: `transport.retryTake` present with `⌘.`.++## Manual (the app)++1. Arm an audio track, set count-in to 1 bar, press ⌘R, play a few bars, press ⌘. — the take+ disappears, the count-in clicks again, recording continues; ⌘. a few more times, then Return+ → one take; ⌘Z once → empty track; ⌘⇧Z → nothing to redo.+2. Session view: launch a drum clip, record into an empty slot on an armed track, press ⌘.+ → drums never stop; the slot shows pending until the next bar, then records.diff --git a/specs/078-discard-and-retry-take/research.md b/specs/078-discard-and-retry-take/research.mdnew file mode 100644index 00000000..0d277861--- /dev/null+++ b/specs/078-discard-and-retry-take/research.md@@ -0,0 +1,123 @@+# Research: Discard and Retry a Take++All findings come from reading the engine and app as of `origin/develop` (31c2efda).++## R1 — How a take reaches the project and the undo history today++- **Audio (Arrangement)**: the capture lives in `audioCaptureBuf_` (plus `capturePasses_` for+ loop passes) on the message thread; nothing reaches the graph until `stopAudioRecording()`+ materialises it with `republishWithTrack` — one undo step+ (`Engine_Recording.cpp`).+- **MIDI (Arrangement)**: `setRecording(true)` creates the take's clip with+ `republishWithTrack` when no clip spans the playhead (an undo step); `poll()` folds the+ notes / controllers / expression the audio thread queued (`recorded_`, `recordedCtl_`,+ `recordedExpr_`) into the clip with `republishWithTrackRaw` — no undo step+ (`Engine_Render.cpp`).+- **Automation record**: the record button also turns automation record on;+ `beginAutomationWrite` pushes one undo checkpoint per write session and grows lanes raw+ (`Engine_Automation.cpp`).+- **Session slot**: audio is captured through the same buffer and materialised into the slot+ in `stopAudioRecording()`; a fresh MIDI slot is created with `addSessionMidiClip` (an undo+ step, its count kept in `sessionCountInUndo_`) and grown raw in `poll()`.++**Decision**: a take attempt remembers, at its start, the *pre-take* `Track` objects of every+track it can write (record targets; tracks that start an automation write during the take are+added at that moment) and the undo/redo stacks' state. Discard republishes those tracks raw+(no checkpoint), truncates the undo entries pushed since the take started and restores the+redo stack.++**Rationale**: graph snapshots are immutable and cheap to keep (`shared_ptr<Track>`, AR-5);+restoring per track keeps edits on other tracks (FR-011); truncating the stack gives FR-003+exactly (the take never was).++**Alternatives considered**:+- *Plain `undo()` after a normal stop* — leaves a redo step (violates FR-003), materialises+ audio first (wasted work, and a loop take adds several take lanes before vanishing).+- *Restore the whole pre-take graph* — throws away edits made on other tracks during the take.+- *Wrap every take in an undo group* — changes the undo shape of ordinary takes; not needed.++Review of #486: the take's own checkpoints (its clip, its first lane write) are marked+(`UndoEntry::take`, via `TakePushScope`). A discard drops only those; checkpoints the user+pushed meanwhile stay, with the take's tracks put back in their saved graphs, so undoing them+later doesn't bring the take back. A track gets into the attempt before its first automation+write, armed or not.++Undo-depth trimming: `pushUndo` erases the oldest entry past `kMaxUndoDepth`; the take's base+index is decremented with it (as `undoGroupBase_` already is).++## R2 — Late MIDI from the audio thread++The audio thread queues a note when it is *released* (`Engine_Render.cpp`, live and routed+paths, loop-wrap split). A note released after the discard but timed in the old take would+otherwise land in the retried one.++**Decision**: a take epoch (`std::atomic<uint32_t>`) bumped by the discard; the audio thread+stamps `RecordedNote` / `RecordedCtl` / `RecordedExpr` with the epoch it read for the block;+`poll()` drops entries from an older epoch. Keys still held at the retry are seeded into the+new take by the existing "held across Record" logic (#56), from the new take's first moment.++**Rationale**: lock-free, no allocation on the audio thread (AR-6), one relaxed load per block.++Audio capture frames get the same fence (review of #486): each producer (input thread,+internal-resampling tap) pushes a marker frame the first time it writes after the capture epoch+moved, and loads the epoch before the capture gate; a retried take drops everything drained+before that marker. A Session MIDI retry adopts the new take epoch on the audio thread only+when its slot has relaunched, so notes and controllers played while it waits stay out and keys+held across the relaunch start with it.++**Alternatives**: draining the queues at discard time only — races with the block in flight.++## R3 — Where an Arrangement retry restarts++`Transport::stop()` returns the playhead to the start anchor (where Play was launched or the+last seek). A take started from stop has `recordStartedTransport_` with `recordReturnBeat_` =+its start.++**Decision** (clarified 2026-11-04): stop the transport; if the take started it, seek to+`recordReturnBeat_`; otherwise the stop has already returned to the anchor — where playback+started. Then start recording again *from stop* with the attempt's count-in policy: the count-in+plays again when the original attempt counted in; a punched-in take restarts rolling with no+count-in (the run-up is the context). Implemented by a `forceNoCountIn` argument to the+internal start path, not by changing `setRecording`'s public behaviour.++## R4 — Session slot retry++- Arrangement and Session takes are mutually exclusive in the engine (one capture buffer, one+ `recording_` flag; `poll()` gives the session target priority). FR-014 was reworded to say so.+- Session MIDI takes start via `launchSlot` → the slot player launches on the next launch+ quantum; `sessionSlotState` already reports 4 (recording) the moment `recording_` is set,+ even while the player is still pending — the issue comment's "pending, not recording" gap.+- Session **audio** takes start capturing immediately (no quantum), from fresh-take or retry.++**Decision**:+- Discard restores the slot from the pre-take track (only that slot's `SessionSlot`, so other+ slots' edits survive), drops the capture without materialising, and leaves every other+ player and the transport alone.+- Restart: MIDI → the existing `recordSessionSlot` path (launches on the next quantum; immediate+ when quantize is off). Audio → capture starts now, and a *retry start beat* is set to the next+ launch-quantum boundary; the drain notes the capture frame where the+ playhead crossed it (at the tempo of that moment) and `stopAudioRecording()` trims what came+ before, so the take starts on the grid.+- New slot state **5 = record pending**: `recording_` for this slot but MIDI player not yet+ playing it, or audio playhead before the retry start beat. Callers that test `!= 0` / `>= 2`+ keep working (5 is "active, not empty").++**Alternatives**: gating the input tap on the audio thread at the boundary — more moving parts+for the same result; the trim is sample-exact against the take's own clock.++## R5 — Disk and dirty state (FR-004, "clean stays clean")++Recorded audio stays in memory (`SampleBuffer`) and is written by `ProjectService` on save+from the graph; autosave also serialises the graph. A discarded take never enters the graph,+so it never reaches disk. `HasUnsavedChanges()` compares a content fingerprint, so restoring+the pre-take tracks makes a clean project clean again.++## R6 — Command surface++- No user-remappable shortcuts exist; commands live in `CommandCatalog` with a default+ shortcut and are bound by id (`MainWindow.Commands.cs`). `⌘.` / `Ctrl+.` is free+ (`Shortcut.Cmd('.')`; `.` → `Key.OemPeriod` already mapped).+- MCP: `TransportTools.cs` holds `play`/`stop`/`seek`; add `retry_take` there.+- C ABI: one new call `nota_engine_retry_take` returning what it did; slot state doc gets 5.+- Shortcuts page, FEATURES.md, CHANGELOG, user docs (EN+RU) via the nota-shortcuts /+ nota-features / nota-docs skills.diff --git a/specs/078-discard-and-retry-take/spec.md b/specs/078-discard-and-retry-take/spec.mdnew file mode 100644index 00000000..9e1b387e--- /dev/null+++ b/specs/078-discard-and-retry-take/spec.md@@ -0,0 +1,270 @@+# Feature Specification: Discard and Retry a Take++**Feature Branch**: `feat/discard-and-retry-recording`++**Created**: 2026-11-04++**Status**: Draft++**Input**: User description: "Abort current recording and start over (issue #185): a dedicated, assignable "Undo & Restart" (discard take and retry) command. While recording, a single key press stops recording, discards the take(s) just recorded (no undo entry left behind, audio files removed), returns the playhead to the position recording started from (including preroll/count-in), and immediately starts recording again. Inspired by Logic's Cmd+Period "Discard Recording and Return to Last Play Position" and Studio One's "Undo & Restart". Consider the comment on the issue about Session-view slot recording."++Issue: [nota-daw/nota#185](https://github.com/nota-daw/nota/issues/185) (approved).++## Nota Context *(fill in — drives plan and tasks)*++**Feature area** *(pick the main one)*:++- [x] Engine (C++, `src/native/nota.engine`) — real-time audio rules apply, see `ARCHITECTURE.md` AR table+- [x] Managed app (C#, `src/managed/*`) — domain, application, infrastructure, presentation+- [ ] UI (Avalonia, `src/managed/Nota.Presentation`) — follow `DESIGN.md` (Studio)+- [ ] Plugin hosting (`pluginhost/`) — the only place JUCE is allowed+- [ ] Build / packaging / CI (`scripts/`, `.github/`) — see `BUILD.md`+- [ ] Docs only++The take is decided on the engine's message thread (where a stopped take is materialised+into the arrangement and the undo history); the command, its shortcut and its feedback+live in the managed app (command catalog, transport view-model, MCP).++**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 - Throw the take away and go again (Priority: P1)++A guitarist records a passage in the Arrangement, starting from stop with a one-bar+count-in. Halfway through they fluff a chord. They press one key: the take vanishes, the+playhead jumps back to where the take started, the count-in clicks again and recording is+already running when it ends. They play the passage again without touching the mouse.++**Why this priority**: This is the whole request — guitar tracking repeats the same+passage dozens of times, and today a retry is Stop → Undo → reposition → Record.++**Independent Test**: Arm an audio track, record from stop with count-in, trigger the+command mid-take; the arrangement holds no trace of the first take, the playhead is back at+the take start, the count-in plays and a new take is capturing. Stop: only the second take+is in the arrangement.++**Acceptance Scenarios**:++1. **Given** an armed audio track recording from stop with a count-in set, **When** the user+ triggers Discard and retry, **Then** the take in progress is dropped, the playhead+ returns to the beat where the take started, the count-in plays again and recording+ resumes when it ends.+2. **Given** the same, but with the count-in off, **When** the user triggers the command,+ **Then** recording restarts immediately from the take's start beat.+3. **Given** the retried take is stopped normally, **When** the user presses Undo once,+ **Then** the arrangement returns to its state before the *first* (discarded) take — the+ discarded take never appears in the undo or redo history.+4. **Given** an armed instrument track recording MIDI (alone or together with an audio+ track), **When** the user triggers the command, **Then** the notes and controller data+ of the take — and any clip the take created — are dropped too, and both tracks record+ again.+5. **Given** the record button is engaged and the user moved a control (writing+ automation) during the take, **When** the user triggers the command, **Then** the+ automation written during the take is dropped as well.++---++### User Story 2 - Retry a loop-recorded take (Priority: P2)++With the transport loop on, a player records several passes over a four-bar loop, decides+the whole attempt is bad and wants to start again from the first pass.++**Why this priority**: Loop recording is the other common way to track a part; the+command must not leave half of a multi-pass take behind.++**Independent Test**: Loop on, record three passes, trigger the command; no pass and no+take lane from this recording remains, earlier takes on the track are untouched, recording+restarts from where it started.++**Acceptance Scenarios**:++1. **Given** loop recording has completed two or more passes, **When** the user triggers+ the command, **Then** every pass of this recording is discarded (no new takes in the+ track's take lanes) and takes from earlier recordings stay as they were.+2. **Given** loop recording in Replace mode removed notes of earlier passes, **When** the+ user triggers the command, **Then** the clip is back to what it held before this+ recording began.++---++### User Story 3 - Reach it the way that fits the session (Priority: P2)++The user finds the command where other transport commands live: a default keyboard+shortcut, the Transport menu, and the command palette; an assistant driving Nota over MCP+can trigger it too.++**Why this priority**: The issue asks for a dedicated key command; a command nobody can+find is no command.++**Independent Test**: Trigger the command once from each entry point while recording; each+discards and restarts the take. The Shortcuts page in Preferences lists it.++**Acceptance Scenarios**:++1. **Given** recording is running, **When** the user presses the default shortcut+ (⌘. on macOS, Ctrl+. elsewhere), **Then** the take is discarded and restarted.+2. **Given** nothing is recording, **When** the user triggers the command, **Then**+ nothing in the project changes and the status line says there is no take to discard.+3. **Given** the command palette is open, **When** the user searches "retry", "discard" or+ "undo restart", **Then** the command is found.++---++### User Story 4 - Retry a take recorded into a Session slot (Priority: P3)++A cellist records a four-bar take into an empty Session slot while a drum clip on another+track keeps playing. They make a mistake and trigger the same command. Only that slot's+take is dropped; the drums and every other playing clip carry on; the slot shows it is+waiting and starts capturing again at the next launch-quantize boundary.++**Why this priority**: Raised in the issue's discussion; Session recording is a separate+path from the Arrangement take, and live looping is exactly where a retry must not stop the+music.++**Independent Test**: With a clip playing on one track, record into an empty slot on an+armed track, trigger the command mid-take; the other clip never stops, the slot returns to+pending and records again from the next quantize boundary; Stop leaves one playable clip+in the slot, and save/reopen keeps only that take.++**Acceptance Scenarios**:++1. **Given** a slot recording while other Session clips play, **When** the user triggers the+ command, **Then** the slot's in-progress take is discarded, the other clips keep playing+ uninterrupted, and the transport keeps running.+2. **Given** the same, **When** the retry is waiting for the next launch-quantize boundary,+ **Then** the slot is shown as pending (waiting to record), not as recording, until+ capture actually starts.+3. **Given** the slot held no clip before the take, **When** the retried take is stopped,+ **Then** the slot holds only the new take, it plays, and after save and reopen it is the+ only take stored for that slot.+4. **Given** launch quantize is off, **When** the user triggers the command, **Then** the+ slot records again immediately.+5. **Given** a fixed Session record length is set, **When** the retried take reaches that+ length, **Then** it ends and plays like any fixed-length take.++---++### Edge Cases++- **Take punched in while already playing** (recording engaged mid-playback, so no+ count-in applied): the retry restarts at the position playback was started from, so+ the player hears the run-up again; recording runs from there. The new take therefore+ begins earlier than the discarded one did.+- **Command during the count-in** (nothing captured yet): the count-in starts over from the+ beginning; nothing is discarded because nothing was recorded.+- **Command pressed repeatedly in quick succession**: each press discards whatever the+ current attempt captured and restarts; the project ends up exactly as before the first+ attempt plus nothing.+- **Recording could not start** (nothing armed, no audio input): the command behaves as on+ a stopped transport — nothing changes, the status line explains.+- **Loop turned on in the middle of a take**: the whole take is discarded, as for any other.+- **Armed track deleted or disarmed during the take**: the retry restarts recording on+ whatever is armed now; if nothing is, it stops and explains, as Record does.+- **Edits made by other means during the take** (an MCP client or the user editing another+ track while recording runs): [assumption] they are kept; only what the take itself wrote+ is dropped.+- **Unsaved-changes state**: a project that was clean before the discarded take is clean+ again after it (the discard alone does not mark the project modified).++## Clarifications++### Session 2026-11-04++- Q: Does the command cover Session slot recording too? → A: Yes — Arrangement and Session+ (User Story 4, FR-012–FR-014).+- Q: Where does a retry restart when the take was punched in during playback? → A: Where+ playback was started, so the run-up plays again (FR-005).++## Requirements *(mandatory)*++### Functional Requirements++- **FR-001**: The app MUST offer a single command, "Discard and retry take", available+ while a take is recording or counting in.+- **FR-002**: The command MUST drop everything the take in progress recorded — the audio+ capture, every loop pass and the take lanes it would add, MIDI notes and controller and+ expression data, clips the take created, notes a Replace-mode pass removed, and+ automation written while the record button was engaged — leaving those tracks exactly as+ they were when the take started.+- **FR-003**: The discarded take MUST leave no undo or redo step: after the command, Undo+ behaves as if the discarded take had never been recorded.+- **FR-004**: The discarded take MUST never reach disk — no audio file is written for it,+ and saving afterwards stores nothing of it.+- **FR-005**: After discarding an Arrangement take, the playhead MUST return to the+ position the transport was started from for this attempt — the take's start beat when the+ take started the transport, the Play position when the take was punched in during+ playback — and recording MUST start again there on the same armed tracks without further+ input.+- **FR-006**: A take that started from stop MUST get the count-in again on retry when a+ count-in is set, and its capture MUST stay gated until the count-in ends, exactly as for+ a fresh Record from stop.+- **FR-007**: The retried take MUST behave as an ordinary take: stopping it materialises it+ as one undo step, it can be retried again, and it saves and reopens like any take.+- **FR-008**: The command MUST have a default shortcut (⌘. on macOS, Ctrl+. on Windows and+ Linux), an entry in the Transport menu and the command palette, and be listed on the+ Preferences → Shortcuts page.+- **FR-009**: The command MUST be callable through the MCP server as a tool that reports+ whether a take was discarded.+- **FR-010**: Triggered with no take recording, the command MUST change nothing in the+ project or transport and MUST show a short status message.+- **FR-011**: Edits to the project that the take did not make (another track edited during+ the take) MUST survive the discard.+- **FR-012**: While a Session slot is recording, the command MUST discard only that slot's+ in-progress take (the slot returns to what it held before), leave every other Session+ clip, the Arrangement and the transport running, and re-record into the same slot from+ the next launch-quantize boundary (immediately when quantize is off).+- **FR-013**: While a Session retry waits for its boundary, the slot MUST be shown as+ pending, not recording, until capture actually starts.+- **FR-014**: Nota records one take at a time — an Arrangement take or a Session slot take;+ the command MUST act on whichever is recording, by its rule (FR-005 or FR-012).++### Key Entities++- **Take attempt**: one press of Record (or one retry) up to Stop or the next retry: the+ tracks it records, the beat it started at, whether it started the transport and counted+ in, and the project state just before it began — what a discard returns to.++## Success Criteria *(mandatory)*++### Measurable Outcomes++- **SC-001**: Retrying a take takes one key press instead of the current four steps (Stop,+ Undo, reposition, Record).+- **SC-002**: After any number of retries followed by Stop, the project contains exactly one+ new take, and one Undo returns it to the state before the first attempt — verified in an+ automated end-to-end test.+- **SC-003**: A take started from stop is retried from the same musical position —+ sample-aligned with the discarded one; a Session retry starts on the launch-quantize+ grid.+- **SC-006**: A Session retry never interrupts the other clips that are playing.+- **SC-004**: Saving after a discarded take writes no audio for it: the project folder+ holds the same audio files as if the discarded take had never been recorded.+- **SC-005**: No audible glitch or dropout is introduced by the retry beyond the transport+ restart itself.++## Assumptions++- Nota has no music-playing pre-roll; the issue's "preroll" is Nota's count-in (the+ clicks-only bars before a take started from stop).+- "Assignable" means a command in the catalog with a default shortcut, reachable from+ menu, palette and MCP. User-remappable shortcuts do not exist in Nota yet and are out of+ scope.+- The command acts only on the take in progress. Discarding a take after it was stopped is+ ordinary Undo and stays as it is.+- The default shortcut ⌘. / Ctrl+. is free in the command catalog today.+- Nota Remote (phone) and the Cardputer remote do not get a button in this change.++## Nota Compliance Checklist *(review before implementation; re-check in tasks.md)*++- [x] Every new source file will carry the AGPL-3.0-only SPDX header (two lines, see CONTRIBUTING.md)+- [x] No new dependency — or: license checked, AGPL-compatible, `LICENSES/third-party.md` row planned+- [x] 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)+- [x] Managed/native crossings go through the pure C ABI in `nota_engine.h` only (AR-7); no JUCE outside `pluginhost/`+- [x] Smoke-test impact assessed: engine behaviour change → extend `tests/Nota.SmokeTest`+- [x] 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)+- [x] UI change → follows `DESIGN.md` (Studio design language)diff --git a/specs/078-discard-and-retry-take/tasks.md b/specs/078-discard-and-retry-take/tasks.mdnew file mode 100644index 00000000..1634b792--- /dev/null+++ b/specs/078-discard-and-retry-take/tasks.md@@ -0,0 +1,153 @@+---++description: "Tasks: Discard and Retry a Take (#185)"+---++# Tasks: Discard and Retry a Take++**Input**: Design documents from `specs/078-discard-and-retry-take/`++**Prerequisites**: plan.md, spec.md, research.md, data-model.md, contracts/, quickstart.md++**Tests**: Required — the constitution's verification gate (IV) and SC-002 ask for smoke-test+coverage of engine behaviour. Tests live in `tests/Nota.SmokeTest/RetryTakeTests.cs`.++**Organization**: grouped by user story (spec.md priorities).++## Format: `[ID] [P?] [Story] Description`++- **[P]**: can run in parallel (different files, no dependency on an unfinished task)+- **[Story]**: US1–US4 from spec.md++---++## Phase 1: Setup++- [X] T001 Add `src/engine/Engine_TakeRetry.cpp` (SPDX header, why-comment) to the engine source list in `src/native/nota.engine/CMakeLists.txt`++---++## Phase 2: Foundational (blocks every story)++- [X] T002 Declare the take-attempt state in `src/native/nota.engine/src/engine/Engine.h` per data-model.md: `TakeAttempt { bool active; bool session; std::vector<std::pair<int32_t, std::shared_ptr<Track>>> baseTracks; size_t undoBase; std::vector<UndoEntry> redoSaved; bool countedIn; int32_t sessionTrackId; int32_t sessionScene; }`, `std::atomic<uint32_t> takeEpoch_`, `double retryStartBeat_ = NaN`, and private methods `openTakeAttempt(bool session)`, `noteTakeTrack(int32_t)`, `closeTakeAttempt()`, `discardTake()`, `abortAudioRecording()`, public `int32_t retryTake()`+- [X] T003 Implement `openTakeAttempt` / `noteTakeTrack` (first write wins; master track id included) / `closeTakeAttempt` in `src/native/nota.engine/src/engine/Engine_TakeRetry.cpp`+- [X] T004 In `pushUndo` (`src/native/nota.engine/src/engine/Engine.cpp`) decrement `takeAttempt_.undoBase` when the oldest entry is trimmed past `kMaxUndoDepth`+- [X] T005 Add a `uint32_t epoch` to `RecordedNote`, `RecordedCtl`, `RecordedExpr` (Engine.h); stamp it on the audio thread from one relaxed load of `takeEpoch_` per block in `src/native/nota.engine/src/engine/Engine_Render.cpp` (live, routed, loop-wrap split, controller and expression pushes); drop stale entries in `poll()` and `collectRecordedExpr()`+- [X] T006 Implement `abortAudioRecording()` in `src/native/nota.engine/src/engine/Engine_Recording.cpp`: taps off, `releaseAudioInputIfIdle`, drain, clear `audioCaptureBuf_`, `capturePasses_`, loop-capture fields, `audioRecordTrackId_`, `recordSessionAudio_` — no materialise+- [X] T007 Implement `discardTake()` in `Engine_TakeRetry.cpp`: `recording_ = false`; end automation writes without committing (reuse `finishAllWrites` paths, then restore lanes via base tracks); `abortAudioRecording()`; clear MIDI fold state (`takeNotes_`, `takeCtls_`, `ctlBatch_`, `pendingExpr_`, `ctlStopPending_`, `resetCtlFold()`); bump `takeEpoch_`; republish base tracks raw (Arrangement: whole tracks still present; Session: only the target slot copied into the current track); `recomputePdc()` / `reapplyRackMacros()` / `reapplyCcRoutes()` after the restore; trim `undoStack_` to `undoBase`, restore `redoStack_`; close the attempt+- [X] T008 Add `nota_engine_retry_take` to `src/native/nota.engine/include/nota/nota_engine.h` (doc per contracts/c-abi.md) and its shim in `src/native/nota.engine/src/abi/nota_engine_core.cpp`+- [X] T009 [P] Managed mirror: `RetryTakeResult { None = 0, Arrangement = 1, Session = 2, Failed = -1 }` and `RetryTakeResult RetryTake()` in `src/managed/Nota.Application/Engine/IAudioEngine.cs` / `EngineContracts.cs`; P/Invoke in `src/managed/Nota.Infrastructure/Interop/NativeMethods.cs` and wrapper in `NotaEngine*.cs`; update any other `IAudioEngine` implementations (test doubles)++**Checkpoint**: the engine can discard a take; nothing calls it yet.++---++## Phase 3: User Story 1 — Throw the take away and go again (P1) 🎯 MVP++**Goal**: one command discards an Arrangement take and records again from the same place.++**Independent Test**: quickstart.md automated scenarios 1, 2, 4, 5, 6, 9.++### Tests++- [X] T010 [US1] Create `tests/Nota.SmokeTest/RetryTakeTests.cs` (SPDX header) and register it in `tests/Nota.SmokeTest/Program.cs`; scenarios: MIDI from stop with count-in (clip removed, playhead at start, count-in running, second take only, one Undo → pre-first-take, no Redo); retry into an existing clip restores its notes; audio via internal resample source (no clip, then one clip at the original start); punch-in from beat 4 at beat 8 → restarts at 4 with no count-in; automation written during the take is gone; a note released after the retry is not in the new take; nothing recording → `None`, project unchanged++### Implementation++- [X] T011 [US1] Call `openTakeAttempt(false)` in `setRecording(true)` before the MIDI clip is created and record `countedIn`; call `closeTakeAttempt()` on `setRecording(false)` in `src/native/nota.engine/src/engine/Engine_Recording.cpp`+- [X] T012 [US1] Call `noteTakeTrack(trackId)` from `beginAutomationWrite` while an attempt is open, before the lane is created, in `src/native/nota.engine/src/engine/Engine_Automation.cpp`+- [X] T013 [US1] Implement the Arrangement branch of `retryTake()` in `Engine_TakeRetry.cpp`: remember `countedIn`, `recordStartedTransport_`, `recordReturnBeat_`; `discardTake()`; `transportStop()`; seek to `recordReturnBeat_` when the take started the transport; restart through an internal start that takes `allowCountIn` (refactor `setRecording(true)` body into `startRecordingTake(bool allowCountIn)`); return 1, or −1 when nothing could start+- [X] T014 [US1] `RetryTakeCommand` in `src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs`: call `RetryTake()`; `Arrangement` → keep `RecordOn`, `TracksChanged`, message `transport.take_discarded_retrying`; `None` → `transport.no_take_to_discard`; `Failed` → set `RecordOn` false without re-calling the engine and show the record-start failure message+- [X] T015 [US1] Localization keys `commands.discard_and_retry_take`, `transport.take_discarded_retrying`, `transport.no_take_to_discard` in `src/managed/Nota.Application/Localization/en.json` and the bundled languages the localization flow requires++**Checkpoint**: MVP — Arrangement retry works through the view-model.++---++## Phase 4: User Story 2 — Retry a loop-recorded take (P2)++**Goal**: no pass of a multi-pass loop take survives a retry; Replace-mode removals come back.++**Independent Test**: quickstart.md scenario 3.++- [X] T016 [US2] Add loop scenarios to `tests/Nota.SmokeTest/RetryTakeTests.cs`: audio loop take with ≥2 passes → retry → `TakeCount` unchanged from before; MIDI Replace pass that removed notes → retry → clip notes equal the pre-take notes+- [X] T017 [US2] Verify `abortAudioRecording()` / `discardTake()` cover loop punch state (`captureLoop_`, `captureWrapped_`, `capturePasses_`, `replaceUpTo_`, `appliedReplaceUpTo_`) and fix gaps in `Engine_TakeRetry.cpp` / `Engine_Recording.cpp`++---++## Phase 5: User Story 3 — Reach it the way that fits the session (P2)++**Goal**: shortcut, menu, palette, MCP.++**Independent Test**: quickstart.md scenario 10; manual step 1.++- [X] T018 [P] [US3] Add `C("transport.retryTake", Loc.T("commands.discard_and_retry_take"), Loc.T("common.transport"), Shortcut.Cmd('.'), "undo restart retry discard take again redo record over")` after `transport.record` in `src/managed/Nota.Application/Palette/CommandCatalog.cs`+- [X] T019 [US3] Bind `transport.retryTake` to `_vm.Transport.RetryTakeCommand` in `src/managed/Nota.App/MainWindow.Commands.cs`; add the Transport menu item with `app:Commands.Id="transport.retryTake"` in `src/managed/Nota.App/MainWindow.axaml`; make sure `⌘.` reaches it from the keyboard handler in `MainWindow.Input.cs` (not swallowed by a focused text box only when typing)+- [X] T020 [P] [US3] MCP tool `retry_take` in `src/managed/Nota.Mcp/Tools/TransportTools.cs` returning `{ result: none|arrangement|session|failed }` (contracts/commands.md)+- [X] T021 [US3] Smoke check in `RetryTakeTests.cs` (or `PaletteTests`) that the catalog holds `transport.retryTake` with `⌘.`++---++## Phase 6: User Story 4 — Retry a take recorded into a Session slot (P3)++**Goal**: only the slot's take is dropped; other clips keep playing; pending until the quantum.++**Independent Test**: quickstart.md scenarios 7, 8.++- [X] T022 [US4] Session scenarios in `tests/Nota.SmokeTest/RetryTakeTests.cs`: MIDI slot with another track's slot playing → retry → other slot still state 3; target state 5 until the quantum, then 4; stop → target slot plays; fresh slot removed then re-created (no undo residue); audio slot retry → materialised take starts on the quantum (trimmed length)+- [X] T023 [US4] Call `openTakeAttempt(true)` in `recordSessionSlot` before `addSessionMidiClip`, store track/scene; close it in `finalizeSessionRecord` and `cancelSessionCountIn` in `src/native/nota.engine/src/engine/Engine_Session.cpp`+- [X] T024 [US4] Session branch of `retryTake()` in `Engine_TakeRetry.cpp`: remember track/scene/audio; `discardTake()` (slot restore only, other players untouched, transport untouched); for audio set `retryStartBeat_` to the next launch-quantum boundary (now when quantize is 0); `recordSessionSlot(track, scene)`; return 2+- [X] T025 [US4] Trim frames before `retryStartBeat_` in the session branch of `stopAudioRecording()` (`Engine_Recording.cpp`) and reset it; also reset it on discard / close+- [X] T026 [US4] Slot state 5 "record pending" in `sessionSlotState` (`Engine_Session.cpp`) and the ABI doc in `nota_engine.h`; `TryGetSessionRecordTarget` unchanged+- [X] T027 [US4] Session grid draws state 5 as record-pending (the queued visual in record colour) in `src/managed/Nota.App/SessionView.Grid.cs`; `TransportViewModel` / MainWindow refresh the Session view after a `Session` result++---++## Phase 7: Polish & Cross-Cutting++- [X] T028 [P] `CHANGELOG.md` `[Unreleased]` → Added entry (closes #185)+- [X] T029 [P] FEATURES.md via the nota-features skill+- [X] T030 [P] Preferences → Shortcuts list via the nota-shortcuts skill+- [X] T031 [P] User docs EN + RU (recording page) via the nota-docs skill in `../nota-docs`+- [X] T032 Run `scripts/build.sh` — native + managed + smoke test green+- [X] T033 Re-check the Nota Compliance Checklist in spec.md; run `/speckit-converge`++---++## Dependencies & Execution Order++- Phase 1 → Phase 2 → stories. T002 before T003–T007; T008 after T007; T009 after T008.+- US1 (Phase 3) is the MVP and is needed by US2 (same retry path) and US3's command (T014).+- US3 T018/T020 can start once T009 is done; T019 needs T014.+- US4 needs Phase 2 and T013's refactor (shared `retryTake()` entry); independent of US2/US3.+- Polish after the stories.++## Parallel Opportunities++- T009 (managed mirror) alongside T010 (test scaffolding).+- T018 and T020 in parallel (different projects).+- T028–T031 in parallel.++## Implementation Strategy++1. Phases 1–2, then US1 → run the smoke test → MVP.+2. US2 (mostly verification), US3 (surface), US4 (Session).+3. Polish, `scripts/build.sh`, converge.++## Phase 8: Convergence++- [X] T034 Restart a Session take's count-in from its first click when retried during it, in `src/native/nota.engine/src/engine/Engine_TakeRetry.cpp`, per Edge Cases: command during the count-in (partial)+- [X] T035 Release the Record button when recording ended outside the UI (MCP `retry_take` failed) by following the engine in `TransportViewModel.Tick` (`src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs`), per FR-009 / FR-010 (partial)++## Phase 9: Review of PR #486++- [X] T036 Remember a track before its first automation write in the take (`beginAutomationWrite`), so a retry drops lanes written on tracks the take doesn't record, per FR-002 (T012 had been marked done without it)+- [X] T037 Mark the take's own checkpoints (`UndoEntry::take`); a discard drops only those and removes the take from the user's checkpoints made meanwhile, so their undo steps survive, per FR-003 / FR-011+- [X] T038 Close the take attempt when disarming ends the take, and return None when nothing records, so a retry never deletes a kept take, per FR-010+- [X] T039 Session MIDI retry: the audio thread adopts the new take epoch only when the slot has relaunched (held keys reseeded there), per FR-012 / FR-013+- [X] T040 Session retry relaunches the slot whatever its launch mode (Toggle), per FR-012+- [X] T041 Capture epoch marker frames in the input ring: a retried audio take drops what an in-flight block wrote for the discarded one, per FR-002+- [X] T042 Session audio retry notes the boundary frame when the capture crosses it (tempo changes after it don't move the trim), per FR-012+- [X] T043 Disarming one of two recording tracks keeps its part and leaves the attempt for the capture still running (`keepTakeTrack`), per FR-010 / FR-014+- [X] T044 Every take started without a retry syncs the audio thread's take epoch and cancels a Session retry still waiting for its slot (`syncTakeEpoch`), per FR-007+- [X] T045 A retry after a partial keep drops the former take checkpoints that end up changing nothing (no empty Undo), per FR-003diff --git a/src/managed/Nota.App/MainWindow.Commands.cs b/src/managed/Nota.App/MainWindow.Commands.csindex a326722d..4688dd1c 100644--- a/src/managed/Nota.App/MainWindow.Commands.cs+++ b/src/managed/Nota.App/MainWindow.Commands.cs@@ -108,6 +108,7 @@ public partial class MainWindowB("transport.playPause", () => _vm?.Transport.PlayPauseCommand.Execute(null));B("transport.stop", () => _vm?.Transport.StopCommand.Execute(null));B("transport.record", () => OnMenuRecord(this, e));+ B("transport.retryTake", () => { _vm?.Transport.RetryTakeCommand.Execute(null); _session?.Refresh(); });B("transport.armOnSelect", ToggleArmOnSelect);B("transport.loop", () => OnMenuLoop(this, e));B("transport.metronome", () => OnMenuMetronome(this, e));diff --git a/src/managed/Nota.App/MainWindow.Input.cs b/src/managed/Nota.App/MainWindow.Input.csindex a8540e04..76933857 100644--- a/src/managed/Nota.App/MainWindow.Input.cs+++ b/src/managed/Nota.App/MainWindow.Input.cs@@ -209,6 +209,14 @@ public partial class MainWindowe.Handled = true; // an auto-repeat is swallowed, not passed on to the menureturn;}+ // ⌘. / ⌃.: discard the take and record it again (#185). Held down it retries once,+ // not on every auto-repeat.+ if (plainMod && e.Key == Key.OemPeriod)+ {+ if (_heldKeys.Add(e.Key)) _commands.Run("transport.retryTake");+ e.Handled = true;+ return;+ }// ⌘⇧R / ⌃⇧R: loop record mode, Overdub ↔ Replace.if (mod && e.Key == Key.R && (e.KeyModifiers & KeyModifiers.Shift) != 0 && (e.KeyModifiers & KeyModifiers.Alt) == 0){diff --git a/src/managed/Nota.App/MainWindow.axaml b/src/managed/Nota.App/MainWindow.axamlindex 762d0256..4080705b 100644--- a/src/managed/Nota.App/MainWindow.axaml+++ b/src/managed/Nota.App/MainWindow.axaml@@ -104,6 +104,7 @@<NativeMenuItem Header="{app:T 'common.play_stop'}" app:Commands.Id="transport.playStop"/><NativeMenuItem Header="{app:T 'main.play_pause'}" app:Commands.Id="transport.playPause"/><NativeMenuItem Header="{app:T 'common.record'}" app:Commands.Id="transport.record"/>+ <NativeMenuItem Header="{app:T 'commands.discard_and_retry_take'}" app:Commands.Id="transport.retryTake"/><NativeMenuItem Header="{app:T 'main.auto_arm_selected_track'}" app:Commands.Id="transport.armOnSelect" ToggleType="CheckBox"/><NativeMenuItem Header="{app:T 'common.loop'}" app:Commands.Id="transport.loop"/><NativeMenuItem Header="{app:T 'main.loop_record_overdub_replace'}" app:Commands.Id="transport.loopRecordMode"/>diff --git a/src/managed/Nota.App/PreferencesWindow.cs b/src/managed/Nota.App/PreferencesWindow.csindex fb811436..9dbea175 100644--- a/src/managed/Nota.App/PreferencesWindow.cs+++ b/src/managed/Nota.App/PreferencesWindow.cs@@ -1420,6 +1420,7 @@ public sealed partial class PreferencesWindow : NotaWindow("⇧Space", Loc.T("preferences.play_pause_the_playhead_stays")),("Return", Loc.T("preferences.stop_again_back_to_the")),("⌘R", Loc.T("common.record")),+ ("⌘.", Loc.T("preferences.discard_the_take_and_record")),("⌘M", Loc.T("common.metronome")),("⌘L", Loc.T("preferences.loop_on_off_loop_the")),(Loc.T("preferences.double_click_loop_brace"), Loc.T("preferences.loop_on_off_in_the")),diff --git a/src/managed/Nota.App/SessionView.Grid.cs b/src/managed/Nota.App/SessionView.Grid.csindex 1026f627..fa1aca1d 100644--- a/src/managed/Nota.App/SessionView.Grid.cs+++ b/src/managed/Nota.App/SessionView.Grid.cs@@ -580,11 +580,13 @@ public sealed partial class SessionViewprivate void RenderRecording(DrawingContext ctx, Rect r){- bool waiting = _o._recElapsed <= 0;+ // Waiting for the take to begin: a fresh take before its launch quantum, or a retried+ // one (⌘., specs/078) before the boundary it records from — slot state 5.+ bool waiting = _o._recElapsed <= 0 || _o._engine.SessionSlotState(_c.TrackId, _scene) == 5;FillCell(ctx, r, NotaPalette.Wash(NotaPalette.Record, 0x33), NotaPalette.Record);var lc = LaunchZone.Center;ctx.DrawEllipse(waiting && !_o._blinkOn ? NotaPalette.Wash(NotaPalette.Record, 0x66) : NotaPalette.Record, null, lc, 4.5, 4.5);- var lenFt = Ft(FormatDuration(_o._recElapsed), NotaFonts.Mono, 9, NotaPalette.DangerBright);+ var lenFt = Ft(FormatDuration(waiting ? 0 : _o._recElapsed), NotaFonts.Mono, 9, NotaPalette.DangerBright);double lenX = r.Width - 6 - lenFt.Width;ctx.DrawText(lenFt, new Point(lenX, (TopRowH - lenFt.Height) / 2));var nameFt = Ft(waiting ? Loc.T("session.grid.rec_in") : Loc.T("session.recording"), NotaFonts.SansMedium, 11, NotaPalette.TextHeading, lenX - 31);diff --git a/src/managed/Nota.Application/Engine/EngineContracts.cs b/src/managed/Nota.Application/Engine/EngineContracts.csindex 8f1c4cad..3bd9918a 100644--- a/src/managed/Nota.Application/Engine/EngineContracts.cs+++ b/src/managed/Nota.Application/Engine/EngineContracts.cs@@ -11,6 +11,19 @@ using System.Runtime.InteropServices;namespace Nota.Application;+/// <summary>What <see cref="IAudioEngine.RetryTake"/> did (specs/078).</summary>+public enum RetryTakeResult+{+ /// <summary>Recording could not start again after the take was discarded (see RecordStartStatus).</summary>+ Failed = -1,+ /// <summary>Nothing was recording: nothing changed.</summary>+ None = 0,+ /// <summary>An Arrangement take was discarded and records again.</summary>+ Arrangement = 1,+ /// <summary>A Session slot take was discarded and records again from the next launch quantum.</summary>+ Session = 2,+}+/// <summary>A MIDI note, blittable and laid out to match the native NotaNoteData/// struct. Times are in beats, relative to the containing clip's start.</summary>[StructLayout(LayoutKind.Sequential)]diff --git a/src/managed/Nota.Application/Engine/IAudioEngine.cs b/src/managed/Nota.Application/Engine/IAudioEngine.csindex a95c8164..b47ef7c2 100644--- a/src/managed/Nota.Application/Engine/IAudioEngine.cs+++ b/src/managed/Nota.Application/Engine/IAudioEngine.cs@@ -95,6 +95,8 @@ public interface IAudioEngine : IDisposableint AddScene();/// <summary>Removes a scene row (always keeps at least one). False if it couldn't.</summary>bool RemoveScene(int scene);+ /// <summary>0 empty, 1 filled, 2 queued, 3 playing, 4 recording, 5 record pending (the take+ /// starts capturing on the next launch quantum, specs/078).</summary>int SessionSlotState(int trackId, int scene);double SessionSlotLength(int trackId, int scene);void SetSessionSlotLength(int trackId, int scene, double lengthBeats);@@ -1071,6 +1073,11 @@ public interface IAudioEngine : IDisposablevoid SetAuditionTrack(int trackId);void SetRecording(bool enabled);bool IsRecording { get; }+ /// <summary>Discard the take in progress and record it again (#185, specs/078): nothing of+ /// it stays, not even an undo step. The Arrangement goes back to where the transport was+ /// started and counts in again if the take did; a Session slot records again from the next+ /// launch quantum while everything else keeps playing.</summary>+ RetryTakeResult RetryTake();int RecordStartStatus { get; }/// <summary>Track id of the in-progress audio take (0 when not capturing).</summary>int AudioRecordTrackId { get; }diff --git a/src/managed/Nota.Application/Localization/en.json b/src/managed/Nota.Application/Localization/en.jsonindex 9e21be38..6e2e8ac1 100644--- a/src/managed/Nota.Application/Localization/en.json+++ b/src/managed/Nota.Application/Localization/en.json@@ -304,6 +304,7 @@"commands.copy_clips_to_session_arrangement": "Copy clips to Session / Arrangement","commands.cycle_clip_names": "Cycle clip names","commands.delete_section_with_content": "Delete section with content",+ "commands.discard_and_retry_take": "Discard and retry take","commands.duplicate_section_with_content": "Duplicate section with content","commands.edit_selected_clips_together": "Edit selected clips together","commands.exit_nota": "Exit Nota",@@ -3003,6 +3004,7 @@"preferences.devices_after_a_click_on": "Devices (after a click on a device)","preferences.devices_settings": "Devices","preferences.direction": "Direction",+ "preferences.discard_the_take_and_record": "Discard the take being recorded and record it again · Arrangement: from where it started, counting in again · Session: from the next launch quantum","preferences.double_click_a_browser_instrument": "Double-click a browser instrument","preferences.double_click_a_chain_or": "Double-click a chain or macro name","preferences.double_click_a_knob_fader": "Double-click a knob, fader or slider",@@ -3731,8 +3733,10 @@"transport.cant_record_arm_a_track": "Can't record: arm a track first (click Arm on a track header).","transport.cant_record_no_audio_input": "Can't record: no audio input — grant microphone access (needs a bundled app).","transport.count_in": "count-in",+ "transport.no_take_to_discard": "Nothing is recording — no take to discard.","transport.paused_play_carries_on_from": "Paused · Play carries on from here","transport.recording_didnt_start": "Recording didn't start.",+ "transport.take_discarded_retrying": "● Take discarded — recording again…","transport.time": "time","update.app_updater.couldnt_download_the_update": "Couldn't download the update: {0}","update.app_updater.couldnt_prepare_the_update": "Couldn't prepare the update ({0}: {1}).",diff --git a/src/managed/Nota.Application/Palette/CommandCatalog.cs b/src/managed/Nota.Application/Palette/CommandCatalog.csindex 2cf55504..f5125409 100644--- a/src/managed/Nota.Application/Palette/CommandCatalog.cs+++ b/src/managed/Nota.Application/Palette/CommandCatalog.cs@@ -83,6 +83,7 @@ public static class CommandCatalogC("transport.playPause", Loc.T("commands.play_pause"), Loc.T("common.transport"), Shortcut.Shift("Space"), "resume continue hold"),C("transport.stop", Loc.T("common.stop"), Loc.T("common.transport"), Shortcut.None("Return"), "halt"),C("transport.record", Loc.T("common.record"), Loc.T("common.transport"), Shortcut.Cmd('R'), "arm capture"),+ C("transport.retryTake", Loc.T("commands.discard_and_retry_take"), Loc.T("common.transport"), Shortcut.Cmd('.'), "undo restart retry discard take again redo record over punch"),C("transport.armOnSelect", Loc.T("commands.auto_arm_selected_track"), Loc.T("common.transport"), "", "arm on select follow selection record keyboard"),C("transport.loop", Loc.T("commands.toggle_loop"), Loc.T("common.transport"), Shortcut.Cmd('L'), "cycle repeat"),C("transport.metronome", Loc.T("common.metronome"), Loc.T("common.transport"), Shortcut.Cmd('M'), "click"),diff --git a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs b/src/managed/Nota.Infrastructure/Interop/NativeMethods.csindex f321494b..fc31914a 100644--- a/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs+++ b/src/managed/Nota.Infrastructure/Interop/NativeMethods.cs@@ -165,6 +165,9 @@ internal static partial class NativeMethods[LibraryImport(Lib, EntryPoint = "nota_engine_is_recording")]internal static partial int IsRecording(IntPtr engine);+ [LibraryImport(Lib, EntryPoint = "nota_engine_retry_take")]+ internal static partial int RetryTake(IntPtr engine);+[LibraryImport(Lib, EntryPoint = "nota_engine_record_start_status")]internal static partial int RecordStartStatus(IntPtr engine);diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.csindex d2290e8a..0446ec55 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.Session.cs@@ -15,7 +15,7 @@ public sealed partial class NotaEnginepublic void AddSessionMidiClip(int trackId, int scene, double lengthBeats = 4.0){ ThrowIfDisposed(); Check(NativeMethods.SessionAddMidiClip(_handle, trackId, scene, lengthBeats)); }- /// <summary>Slot state: 0 empty, 1 filled, 2 queued, 3 playing, 4 recording.</summary>+ /// <summary>Slot state: 0 empty, 1 filled, 2 queued, 3 playing, 4 recording, 5 record pending (specs/078).</summary>public int SessionSlotState(int trackId, int scene){ ThrowIfDisposed(); return NativeMethods.SessionSlotState(_handle, trackId, scene); }diff --git a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs b/src/managed/Nota.Infrastructure/Interop/NotaEngine.csindex a6688dd2..c5e70719 100644--- a/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs+++ b/src/managed/Nota.Infrastructure/Interop/NotaEngine.cs@@ -152,6 +152,7 @@ public sealed partial class NotaEngine : IAudioEnginepublic void SetAuditionTrack(int trackId) { ThrowIfDisposed(); NativeMethods.SetAuditionTrack(_handle, trackId); }public void SetRecording(bool enabled) { ThrowIfDisposed(); Check(NativeMethods.SetRecording(_handle, enabled ? 1 : 0)); }public bool IsRecording { get { ThrowIfDisposed(); return NativeMethods.IsRecording(_handle) != 0; } }+ public RetryTakeResult RetryTake() { ThrowIfDisposed(); return (RetryTakeResult)NativeMethods.RetryTake(_handle); }/// <summary>Why the last SetRecording(true) did (not) start: 0 ok, 1 no armed track, 2 audio input failed.</summary>public int RecordStartStatus { get { ThrowIfDisposed(); return NativeMethods.RecordStartStatus(_handle); } }/// <summary>Track id of the in-progress audio take (0 when not capturing), for drawing a growing clip.</summary>diff --git a/src/managed/Nota.Mcp/Tools/SessionTools.cs b/src/managed/Nota.Mcp/Tools/SessionTools.csindex b34fd621..c85470ef 100644--- a/src/managed/Nota.Mcp/Tools/SessionTools.cs+++ b/src/managed/Nota.Mcp/Tools/SessionTools.cs@@ -6,7 +6,7 @@// (or the clip's own quantum). Clips carry a name, colour and launch properties (launch mode,// legato, loop, follow actions); scenes carry a name, colour, tempo / signature and a scene// follow action. Slot state: 0 empty, 1 filled, 2 queued (about to start), 3 playing,-// 4 recording.+// 4 recording, 5 record pending (a retried / quantized take waiting for its launch quantum).using System.ComponentModel;using ModelContextProtocol.Server;@@ -32,7 +32,7 @@ public sealed class SessionTools(IAudioEngine engine, IEngineDispatch dispatch,private static readonly string[] Modes = { "trigger", "gate", "toggle", "repeat" };private static readonly string[] Actions = { "none", "stop", "again", "previous", "next", "first", "last", "any", "other", "jump" };- private static string StateName(int s) => s switch { 4 => "recording", 3 => "playing", 2 => "queued", 1 => "filled", _ => "empty" };+ private static string StateName(int s) => s switch { 5 => "record pending", 4 => "recording", 3 => "playing", 2 => "queued", 1 => "filled", _ => "empty" };private static NotaNote ToEngine(Note n) => new(n.Pitch, n.Start, n.Length, Math.Clamp(n.Velocity, 0f, 1f));private static Note FromEngine(NotaNote n) => new(n.Pitch, n.StartBeat, n.LengthBeats, n.Velocity);diff --git a/src/managed/Nota.Mcp/Tools/TransportTools.cs b/src/managed/Nota.Mcp/Tools/TransportTools.csindex 75dce6ea..e147a93b 100644--- a/src/managed/Nota.Mcp/Tools/TransportTools.cs+++ b/src/managed/Nota.Mcp/Tools/TransportTools.cs@@ -26,6 +26,18 @@ public sealed class TransportTools(IAudioEngine engine, IEngineDispatch dispatch[McpServerTool(Name = "stop"), Description("Stop playback (a second stop returns the playhead to the start).")]public Task StopTransport() => Mutate(() => E.StopTransport());+ public sealed record RetryTakeOutcome(string Result);++ [McpServerTool(Name = "retry_take"), Description("Discard the take being recorded and record it again, leaving no undo step: an Arrangement take restarts from where the transport was started (counting in again if it did); a Session slot take records again into the same slot from the next launch quantum while other clips keep playing. Result: none (nothing was recording), arrangement, session, or failed (discarded but recording could not restart).")]+ public Task<RetryTakeOutcome> RetryTake()+ => Mutate(() => new RetryTakeOutcome(E.RetryTake() switch+ {+ RetryTakeResult.Arrangement => "arrangement",+ RetryTakeResult.Session => "session",+ RetryTakeResult.Failed => "failed",+ _ => "none",+ }));+[McpServerTool(Name = "seek"), Description("Move the playhead to a beat position (0 = bar 1).")]public Task Seek([Description("Target position in beats")] double beat) => Mutate(() => E.Seek(Math.Max(0, beat)));diff --git a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.csindex 2b096bca..c315638b 100644--- a/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs+++ b/src/managed/Nota.Presentation/ViewModels/TransportViewModel.cs@@ -158,6 +158,37 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObject});}+ /// <summary>⌘. (#185, specs/078): throw the take being recorded away and record it again —+ /// the Arrangement from where the transport was started, a Session slot from the next launch+ /// quantum. The record button stays down; nothing of the take is left, not even an undo step.</summary>+ [RelayCommand]+ private void RetryTake()+ {+ switch (_engine.RetryTake())+ {+ case RetryTakeResult.Arrangement:+ case RetryTakeResult.Session:+ TracksChanged?.Invoke();+ Message?.Invoke(Loc.T("transport.take_discarded_retrying"));+ break;+ case RetryTakeResult.Failed:+ // The take is gone but recording couldn't start again: pop the button up.+ if (RecordOn) { _revertingRec = true; RecordOn = false; _revertingRec = false; }+ _engine.SetRecording(false);+ TracksChanged?.Invoke();+ Message?.Invoke(_engine.RecordStartStatus switch+ {+ 1 => Loc.T("transport.cant_record_arm_a_track"),+ 2 => Loc.T("transport.cant_record_no_audio_input"),+ _ => Loc.T("transport.recording_didnt_start"),+ });+ break;+ default:+ Message?.Invoke(Loc.T("transport.no_take_to_discard"));+ break;+ }+ }+[RelayCommand]private void PlayStop(){@@ -230,6 +261,8 @@ public partial class TransportViewModel(IAudioEngine engine) : ObservableObjectelse UpdatePositionText(beats);if (IsCountingIn != wasCounting) PositionUnitText = IsCountingIn ? Loc.T("transport.count_in") : ShowTimeDisplay ? Loc.T("transport.time") : Loc.T("transport.bars");IsPlaying = _engine.IsPlaying || IsCountingIn; // the Play button lights from the first click+ // Recording can end outside the UI (an MCP retry that couldn't restart): let the button go.+ if (RecordOn && !_engine.IsRecording) { _revertingRec = true; RecordOn = false; _revertingRec = false; }PlayLabel = IsPlaying ? "■ Stop" : "▶ Play";// The loop record mode can also be set from outside the UI (MCP): follow the engine.bool replace = _engine.LoopRecordReplace;diff --git a/src/native/nota.engine/CMakeLists.txt b/src/native/nota.engine/CMakeLists.txtindex 344e51f6..d53fe320 100644--- a/src/native/nota.engine/CMakeLists.txt+++ b/src/native/nota.engine/CMakeLists.txt@@ -98,6 +98,7 @@ set(NOTA_ENGINE_SOURCESsrc/engine/Engine_Rack.cppsrc/engine/Engine_Recording.cppsrc/engine/Engine_Takes.cpp+ src/engine/Engine_TakeRetry.cppsrc/engine/Engine_Render.cppsrc/engine/Audition.cppsrc/engine/AudioThreadPool.cpp # fork-join pooldiff --git a/src/native/nota.engine/include/nota/nota_engine.h b/src/native/nota.engine/include/nota/nota_engine.hindex 694d9ea2..b4aa6cf7 100644--- a/src/native/nota.engine/include/nota/nota_engine.h+++ b/src/native/nota.engine/include/nota/nota_engine.h@@ -925,6 +925,18 @@ NOTA_API void nota_engine_set_audition_track(NotaEngine* engine, int32_t t* the armed instrument track are recorded into a clip. */NOTA_API NotaResult nota_engine_set_recording(NotaEngine* engine, int32_t enabled);NOTA_API int32_t nota_engine_is_recording(const NotaEngine* engine);+/* Discard the take in progress and record it again (#185, specs/078). Drops everything the+ * take wrote — audio, loop passes, MIDI notes/controllers/expression, a clip it created,+ * automation written while recording — with no undo or redo step, then:+ * - Arrangement: returns to where the transport was started for the take (its start when+ * the take started the transport, else the Play position) and records again, counting in+ * again when the take did;+ * - Session slot: leaves other clips and the transport running and records into the same+ * slot again from the next launch quantum (immediately when quantize is off).+ * Returns 0 nothing was recording (no change), 1 Arrangement take retried, 2 Session slot+ * take retried, -1 discarded but recording could not start again (see+ * nota_engine_record_start_status). Message thread. */+NOTA_API int32_t nota_engine_retry_take(NotaEngine* engine);/* Why the last set_recording(1) did (not) start: 0 ok, 1 no armed track, 2 audio input failed. */NOTA_API int32_t nota_engine_record_start_status(const NotaEngine* engine);/* Live audio-capture geometry for drawing a growing take: the armed track id@@ -1218,7 +1230,8 @@ NOTA_API NotaResult nota_session_set_slot_length(NotaEngine* engine, int32_t tra/* Audio-slot playback gain (linear). Get returns 1.0 when the slot isn't an audio take. */NOTA_API float nota_session_slot_gain(const NotaEngine* engine, int32_t track_id, int32_t scene);NOTA_API NotaResult nota_session_set_slot_gain(NotaEngine* engine, int32_t track_id, int32_t scene, float gain);-/* Slot state: 0 empty, 1 filled, 2 queued, 3 playing, 4 recording. */+/* Slot state: 0 empty, 1 filled, 2 queued, 3 playing, 4 recording,+ * 5 record pending (the slot's take starts capturing on the next launch quantum). */NOTA_API int32_t nota_session_slot_state(const NotaEngine* engine, int32_t track_id, int32_t scene);/* Quantized launch/stop (M5-2). Launch of an empty slot stops the track. */NOTA_API NotaResult nota_session_set_launch_quant(NotaEngine* engine, double beats);diff --git a/src/native/nota.engine/src/abi/nota_engine_core.cpp b/src/native/nota.engine/src/abi/nota_engine_core.cppindex 8dd1a87f..043f9adb 100644--- a/src/native/nota.engine/src/abi/nota_engine_core.cpp+++ b/src/native/nota.engine/src/abi/nota_engine_core.cpp@@ -295,6 +295,9 @@ NotaResult nota_engine_set_recording(NotaEngine* e, int32_t enabled) {int32_t nota_engine_is_recording(const NotaEngine* e) {return (e && CENG(e)->isRecording()) ? 1 : 0;}+int32_t nota_engine_retry_take(NotaEngine* e) {+ return e ? ENG(e)->retryTake() : 0;+}int32_t nota_engine_record_start_status(const NotaEngine* e) {return e ? CENG(e)->recordStartStatus() : 0;}diff --git a/src/native/nota.engine/src/engine/CommandQueue.h b/src/native/nota.engine/src/engine/CommandQueue.hindex 99faab65..ed77d0d3 100644--- a/src/native/nota.engine/src/engine/CommandQueue.h+++ b/src/native/nota.engine/src/engine/CommandQueue.h@@ -39,6 +39,10 @@ enum class CommandType : uint32_t {// 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,+ // A take was discarded and records again (specs/078). Queued after the transport moves+ // that put the playhead back, so every block rendered from here belongs to the new take:+ // i0 = the new take epoch, i1 = 1 to open the capture gate now (no count-in to wait for).+ TakeRestart,};struct Command {diff --git a/src/native/nota.engine/src/engine/Engine.cpp b/src/native/nota.engine/src/engine/Engine.cppindex 7397d525..2171cf22 100644--- a/src/native/nota.engine/src/engine/Engine.cpp+++ b/src/native/nota.engine/src/engine/Engine.cpp@@ -758,11 +758,14 @@ void Engine::pushUndo() {return;}}- undoStack_.push_back({authoring_, {}}); // authoring_ is immutable after publish+ // authoring_ is immutable after publish. A take's own checkpoint is marked so a retry can+ // take it out without touching the user's edits made meanwhile (specs/078).+ undoStack_.push_back({authoring_, {}, takePushing_ && takeAttempt_.active});++undoPushCount_;if (undoStack_.size() > kMaxUndoDepth) {undoStack_.erase(undoStack_.begin());if (undoGroupDepth_ > 0 && undoGroupBase_ > 0) --undoGroupBase_; // keep the group's anchor+ if (takeAttempt_.active && takeAttempt_.undoBase > 0) --takeAttempt_.undoBase; // specs/078}redoStack_.clear(); // a new edit invalidates the redo branch}@@ -778,7 +781,10 @@ void Engine::endUndoGroup() {if (undoStack_.size() > undoGroupBase_ + 1) {auto first = undoStack_.begin() + static_cast<std::ptrdiff_t>(undoGroupBase_);for (auto it = first + 1; it != undoStack_.end(); ++it) {- if (!first->graph) first->graph = it->graph;+ if (!first->graph) {+ first->graph = it->graph;+ first->take = it->take; // a take's checkpoint stays the take's (specs/078)+ }mergeMix(first->mix, it->mix);}undoStack_.erase(first + 1, undoStack_.end());@@ -1069,7 +1075,10 @@ void Engine::endMixGesture(int32_t handle) {const size_t base = std::min(g.stackSizeAtBegin, undoStack_.size() - 1);auto first = undoStack_.begin() + static_cast<std::ptrdiff_t>(base);for (auto it = first + 1; it != undoStack_.end(); ++it) {- if (!first->graph) first->graph = it->graph;+ if (!first->graph) {+ first->graph = it->graph;+ first->take = it->take; // a take's checkpoint stays the take's (specs/078)+ }mergeMix(first->mix, it->mix);}undoStack_.erase(first + 1, undoStack_.end());diff --git a/src/native/nota.engine/src/engine/Engine.h b/src/native/nota.engine/src/engine/Engine.hindex 1fee532a..892f50df 100644--- a/src/native/nota.engine/src/engine/Engine.h+++ b/src/native/nota.engine/src/engine/Engine.h@@ -31,6 +31,8 @@#include <array>#include <atomic>#include <functional>+#include <cmath>+#include <limits>#include <list>#include <memory>#include <map>@@ -1286,6 +1288,10 @@ class Engine {// (for clicking rack/drum pads). -1 = none. Lock-free.void setAuditionTrack(int32_t trackId) { auditionTrackId_.store(trackId, std::memory_order_relaxed); }void setRecording(bool on);+ // Discard the take in progress and record it again (#185, specs/078). Returns 0 nothing+ // was recording, 1 Arrangement take retried, 2 Session slot take retried, -1 discarded but+ // recording could not start again. Message thread.+ int32_t retryTake();bool isRecording() const { return recording_.load(std::memory_order_relaxed) || audioRecording_; }// Why the last setRecording(true) did (not) start: 0 ok, 1 no armed track, 2 audio input failed.int32_t recordStartStatus() const { return recordStartStatus_; }@@ -1901,6 +1907,86 @@ class Engine {bool recordStartedTransport_ = false;double recordReturnBeat_ = 0.0;+ // Discard and retry (specs/078). One record press — or one retry — until the take stops:+ // the tracks as they were before it wrote them and the undo/redo state, so a discard puts+ // them back with no history of its own. Message thread.+ struct TakeAttempt {+ bool active = false;+ bool session = false; // a Session slot take (else Arrangement)+ bool countedIn = false; // the Arrangement take counted in from stop+ std::vector<std::pair<int32_t, std::shared_ptr<Track>>> baseTracks; // first write wins+ size_t undoBase = 0; // undoStack_ size when the take began+ std::vector<UndoEntry> redoSaved; // redoStack_ when the take began+ int32_t sessionTrackId = 0, sessionScene = -1;+ };+ TakeAttempt takeAttempt_;+ bool takePushing_ = false; // the take itself is checkpointing (its clip, its first lane write)+ struct TakePushScope { // marks the checkpoints pushed in this scope as the take's own+ Engine& e;+ bool was;+ explicit TakePushScope(Engine& en) : e(en), was(en.takePushing_) { e.takePushing_ = true; }+ ~TakePushScope() { e.takePushing_ = was; }+ };+ bool forceSlotLaunch_ = false; // a retried Session take relaunches its slot whatever its launch mode+ bool retryingTake_ = false; // the restart of a retried take is starting the capture+ // Capture epoch (specs/078): a producer of capture frames (input thread, internal tap) puts+ // a marker frame (NaN, NaN) in the ring the first time it pushes after the epoch changed;+ // after a retry the drain drops everything before that marker — frames an in-flight block+ // or callback wrote for the take that was thrown away.+ std::atomic<uint32_t> captureEpoch_{0};+ uint32_t hwCaptureEpoch_ = 0; // input thread's last marked epoch+ uint32_t rtCaptureEpoch_ = 0; // audio thread's (internal resampling)+ bool awaitCaptureMarker_ = false;+ static bool isCaptureMarker(const InputFrame& f) { return std::isnan(f.l) && std::isnan(f.r); }+ // Producer side: mark the first push of a new capture epoch. RT-safe (one atomic load).+ // Load the epoch before the capture gate: a retry shuts the gate before it moves the epoch,+ // so a producer that sees the new epoch also sees the gate shut until the restart opens it.+ void markCaptureEpoch(uint32_t& last, uint32_t ep) {+ if (ep == last) return;+ last = ep;+ const float nan = std::numeric_limits<float>::quiet_NaN();+ inputQueue_.push(InputFrame{nan, nan});+ }+ // Session MIDI retry: the audio thread adopts the new take epoch only once the slot has+ // actually relaunched, so nothing played while it waits (shown pending) enters the take.+ uint32_t rtPendingEpoch_ = 0;+ int32_t rtWaitScene_ = -1;+ // Session audio retry: the capture frame where the boundary was crossed (-1 = not yet).+ int64_t retryKeepFrom_ = -1;+ void openTakeAttempt(bool session);+ void noteTakeTrack(int32_t trackId); // a track the take is about to write (no-op when idle)+ void closeTakeAttempt();+ void keepTakeTrack(int32_t trackId); // that track's part of the take is kept; the rest may still be retried+ void syncTakeEpoch(); // a take starts normally: the audio thread takes the current epoch+ void discardTake(); // drop what the take wrote; no undo step+ void abortAudioRecording(); // stop capturing without materialising+ // Explicit start for a retried take: the transport UI mirror lags the commands just+ // queued, so the restart says where it starts and whether the clock is rolling.+ bool startArrangementTake(bool wasPlaying, double playhead, bool retryCountIn);+ double takeStartOverride_ = std::numeric_limits<double>::quiet_NaN(); // startAudioRecording+ int takePlayingOverride_ = -1; // -1 = read the transport+ double takePlayhead() const;+ bool takeTransportPlaying() const;+ // Take epoch: the message thread's current attempt, and the audio thread's copy (set by+ // the TakeRestart command). Recorded events carry the audio thread's; poll() drops stale ones.+ uint32_t takeEpoch_ = 0;+ uint32_t rtTakeEpoch_ = 0;+ bool rtTakeRestart_ = false; // audio thread: a TakeRestart arrived, the next drain restarts the take+ void pushRecorded(RecordedNote n) {+ n.epoch = rtTakeEpoch_;+ recorded_.push(n);+ }+ void pushRecordedCtl(RecordedCtl x) {+ x.epoch = rtTakeEpoch_;+ recordedCtl_.push(x);+ }+ void pushRecordedExpr(RecordedExpr x) {+ x.epoch = rtTakeEpoch_;+ recordedExpr_.push(x);+ }+ // A Session audio retry starts on the launch quantum: capture before this beat is trimmed.+ double retryStartBeat_ = std::numeric_limits<double>::quiet_NaN();+// automation write/record state (M9-C, message thread only)std::atomic<bool> autoRecord_{false}; // transport record engaged -> gestures writestruct ActiveWrite {@@ -2015,6 +2101,7 @@ class Engine {double routedPressBeat_[128] = {};float routedPressVel_[128] = {};int32_t routedOwner_ = -1;+ bool routedSeedFromNow_ = false; // the take was retried: held routed notes start now (specs/078)bool routedSeedPending_ = false; // a take just started: seed after this block's routed eventsvoid trackRoutedDown(int32_t ownerId, const MidiEv* evs, int n, double blockStart, double spb, bool timed);// Capture clock: during a count-in the transport holds still, so notes are timed backdiff --git a/src/native/nota.engine/src/engine/EngineTypes.h b/src/native/nota.engine/src/engine/EngineTypes.hindex 76e4102e..7d117cc4 100644--- a/src/native/nota.engine/src/engine/EngineTypes.h+++ b/src/native/nota.engine/src/engine/EngineTypes.h@@ -38,6 +38,7 @@ struct RecordedNote {double lengthBeats;float velocity;int32_t pass = 0;+ uint32_t epoch = 0; // take attempt it belongs to (specs/078): stamped by the audio thread};using RecordedQueue = SpscRingBuffer<RecordedNote, 1024>;// A recorded note's expression sample (audio -> message): the note is identified by its pitch@@ -48,6 +49,7 @@ struct RecordedExpr {int32_t dim;float beat;float value;+ uint32_t epoch = 0; // take attempt (specs/078)};using RecordedExprQueue = SpscRingBuffer<RecordedExpr, 1u << 14>;// A recorded controller sample (audio -> message): at an absolute beat of the take (a Session@@ -58,6 +60,7 @@ struct RecordedCtl {double beat;float value;int32_t pass;+ uint32_t epoch = 0; // take attempt (specs/078)};using RecordedCtlQueue = SpscRingBuffer<RecordedCtl, 1u << 14>;// A clip note's expression at a sample offset of the block (the render pass replays these).@@ -122,6 +125,8 @@ struct MixChange {struct UndoEntry {std::shared_ptr<Graph> graph; // the state to restore; null for a mix-only stepstd::vector<MixChange> mix; // empty for a structural step; one change per target+ bool take = false; // a take's own checkpoint (specs/078): a retry drops its graph+ bool wasTake = false; // was one, until part of the take was kept (a track disarmed)};using ControlEventQueue = SpscRingBuffer<ControlEvent, 1024>;diff --git a/src/native/nota.engine/src/engine/Engine_Automation.cpp b/src/native/nota.engine/src/engine/Engine_Automation.cppindex e6c51334..667631b9 100644--- a/src/native/nota.engine/src/engine/Engine_Automation.cpp+++ b/src/native/nota.engine/src/engine/Engine_Automation.cpp@@ -411,6 +411,11 @@ void Engine::beginAutomationWrite(return;}+ // Writing a lane during a take is part of the take (specs/078): remember the track as it was+ // before, and mark the checkpoints below (a new lane, the pre-write state) as the take's.+ noteTakeTrack(trackId);+ TakePushScope takePush(*this);+// Resolve (or create) the target's lane. PluginParam resolves paramIndex by id.int32_t laneIndex, resolvedParam = paramIndex;if (static_cast<AutomationTarget>(target) == AutomationTarget::PluginParam) {diff --git a/src/native/nota.engine/src/engine/Engine_Recording.cpp b/src/native/nota.engine/src/engine/Engine_Recording.cppindex bc0d85eb..dd06e171 100644--- a/src/native/nota.engine/src/engine/Engine_Recording.cpp+++ b/src/native/nota.engine/src/engine/Engine_Recording.cpp@@ -31,6 +31,8 @@ void Engine::setTrackArmed(int32_t trackId, bool armed) {}// Disarming a track that's currently recording finalizes its take (the audio clip is// materialised / MIDI capture stops), so toggling its REC button stops the recording.+ const bool endsTake = (audioRecording_ && trackId == audioRecordTrackId_) ||+ (recording_.load(std::memory_order_relaxed) && trackId == recordTrackId_);if (audioRecording_ && trackId == audioRecordTrackId_) stopAudioRecording();if (recording_.load(std::memory_order_relaxed) && trackId == recordTrackId_) {flushCtlTake(); // the take's controllers still in flight (specs/020)@@ -39,6 +41,12 @@ void Engine::setTrackArmed(int32_t trackId, bool armed) {recordClipIndex_ = -1;recording_.store(false, std::memory_order_relaxed);}+ // Its take is kept (specs/078): with nothing else recording the attempt ends; otherwise a+ // retry goes on covering the capture still running, without this track.+ if (endsTake && takeAttempt_.active && !takeAttempt_.session) {+ if (!isRecording()) closeTakeAttempt();+ else keepTakeTrack(trackId);+ }}void Engine::setTrackRecordInput(int32_t trackId, int32_t source) {auto t = findTrackAuthoring(trackId);@@ -91,7 +99,9 @@ bool Engine::ensureAudioInput() {if (n > inputBlockFrames_.load(std::memory_order_relaxed))inputBlockFrames_.store(n, std::memory_order_relaxed);// The gate is shut while a count-in clicks: the take starts when the transport rolls.- if (hwRecordTap_.load(std::memory_order_relaxed) && captureGate_.load(std::memory_order_relaxed)) {+ const uint32_t capEp = captureEpoch_.load(std::memory_order_acquire); // before the gate (specs/078)+ if (hwRecordTap_.load(std::memory_order_relaxed) && captureGate_.load(std::memory_order_acquire)) {+ markCaptureEpoch(hwCaptureEpoch_, capEp);int64_t dropped = 0;for (int32_t i = 0; i < n; ++i)if (!inputQueue_.push(InputFrame{s[i * 2], s[i * 2 + 1]})) ++dropped;@@ -355,6 +365,7 @@ void Engine::setRecording(bool on) {}recording_.store(false, std::memory_order_relaxed);stopAudioRecording(); // materialise if an audio take was rolling+ if (!takeAttempt_.session) closeTakeAttempt(); // the take is kept: nothing to put back// If the take started the transport, stop it and rewind to where the// take began so re-recording lands in the same place (no drift).if (recordStartedTransport_) {@@ -364,11 +375,16 @@ void Engine::setRecording(bool on) {}return;}+ startArrangementTake(transport_.uiIsPlaying(), transport_.uiPositionBeats(), false);+}++// The take start behind setRecording(true). A retry (specs/078) passes where the take starts+// and whether the clock rolls — the transport mirror still shows the take it just dropped —+// and retryCountIn counts in again right away (the stop it queued hasn't landed yet).+bool Engine::startArrangementTake(bool wasPlaying, double playhead, bool retryCountIn) {// Record every armed track together: the first armed audio track captures audio// (hardware or internal), the first armed instrument track captures MIDI. Both run// at once, so arming an instrument + an audio track and hitting REC records both.- const bool wasPlaying = transport_.uiIsPlaying();- const double playhead = transport_.uiPositionBeats();std::shared_ptr<Track> audioT, instT;for (auto& t : authoring_->tracks) {if (!t->armed()) continue;@@ -381,14 +397,23 @@ void Engine::setRecording(bool on) {if (!audioT && !instT) {recording_.store(false, std::memory_order_relaxed);recordStartStatus_ = 1;- return;+ return false;}// A take started from stop gets the count-in (if one is set); the capture taps stay// gated until it runs out, so the clicks-only pre-roll isn't recorded.recordCountIn_ = !wasPlaying && !recordSessionAudio_ && countInBars() > 0;+ // Remember what the take may write before it writes anything (the MIDI clip below).+ openTakeAttempt(false);+ takeAttempt_.countedIn = recordCountIn_;+ if (audioT) noteTakeTrack(audioT->id());+ if (instT) noteTakeTrack(instT->id());+ takeStartOverride_ = playhead;+ takePlayingOverride_ = wasPlaying ? 1 : 0;bool audioOk = true;if (audioT) audioOk = startAudioRecording(audioT->id());+ takeStartOverride_ = std::numeric_limits<double>::quiet_NaN();+ takePlayingOverride_ = -1;if (instT) {recordTrackId_ = instT->id();@@ -409,6 +434,7 @@ void Engine::setRecording(bool on) {c.lengthBeats = 4.0;nt->midiClips.push_back(c);idx = static_cast<int32_t>(nt->midiClips.size()) - 1;+ TakePushScope takePush(*this); // the take's own clip (specs/078)republishWithTrack(recordTrackId_, nt);}recordClipIndex_ = idx;@@ -427,12 +453,26 @@ void Engine::setRecording(bool on) {recordStartedTransport_ = !wasPlaying;}if (!wasPlaying) { // roll so the take advances (idempotent if already rolling)- if (recordCountIn_) transportPlayCountIn();+ if (recordCountIn_ && retryCountIn) {+ arrangementActive_.store(true, std::memory_order_relaxed);+ startCountIn(countInBars());+ } else if (recordCountIn_)+ transportPlayCountIn();elsetransportPlay();}recordCountIn_ = false;recordStartStatus_ = (audioT && !audioOk && !instT) ? 2 : 0;+ if (!isRecording()) closeTakeAttempt(); // nothing started: nothing to retry+ return isRecording();+}++double Engine::takePlayhead() const {+ return std::isnan(takeStartOverride_) ? transport_.uiPositionBeats() : takeStartOverride_;+}++bool Engine::takeTransportPlaying() const {+ return takePlayingOverride_ < 0 ? transport_.uiIsPlaying() : takePlayingOverride_ != 0;}// Decide the capture layout at take start: loop punch if the transport loop is on@@ -503,9 +543,16 @@ void Engine::drainInputQueue() {captureScratch_.clear();InputFrame f;while (inputQueue_.pop(f)) {+ if (isCaptureMarker(f)) { // the producer's first frames of a new capture epoch follow+ if (awaitCaptureMarker_) captureScratch_.clear();+ awaitCaptureMarker_ = false;+ continue;+ }+ if (awaitCaptureMarker_) continue; // written for the take a retry threw away (specs/078)captureScratch_.push_back(f.l);captureScratch_.push_back(f.r);}+ if (awaitCaptureMarker_) inputDroppedFrames_.store(0, std::memory_order_relaxed);Track::foldInputChannels(captureScratch_.data(), captureScratch_.size() / 2, captureChannels_);// Frames the audio thread had to drop while this drain was stalled (ring full).// They are the newest samples — the ones that couldn't fit after the popped batch —@@ -540,6 +587,17 @@ void Engine::drainInputQueue() {if (audioCaptureBuf_.size() < need) audioCaptureBuf_.resize(need, 0.0f);std::copy_n(captureScratch_.data(), frames * 2, audioCaptureBuf_.data() + base * 2);captureWritePos_ = base + frames;+ // A retried Session audio take (specs/078) keeps what follows its launch boundary: note the+ // capture frame where it was crossed now, at the tempo it was crossed at.+ if (recordSessionAudio_ && !std::isnan(retryStartBeat_) && retryKeepFrom_ < 0) {+ const double pos = transport_.uiPositionBeats();+ if (pos >= retryStartBeat_) {+ const double devSR = transport_.sampleRate();+ const double fpb = transport_.samplesPerBeat() * (devSR > 0.0 ? audioRecordSampleRate_ / devSR : 1.0);+ const int64_t past = static_cast<int64_t>(std::llround((pos - retryStartBeat_) * fpb));+ retryKeepFrom_ = std::max<int64_t>(0, static_cast<int64_t>(captureWritePos_) - past);+ }+ }}bool Engine::startAudioRecording(int32_t trackId) {@@ -549,8 +607,10 @@ bool Engine::startAudioRecording(int32_t trackId) {captureWritePos_ = 0;captureLoop_ = false;inputDroppedFrames_.store(0, std::memory_order_relaxed); // fresh drop accounting per take+ awaitCaptureMarker_ = retryingTake_; // a retried take keeps nothing from before its marker+ retryKeepFrom_ = -1;audioRecordTrackId_ = trackId;- audioRecordStartBeat_ = transport_.uiPositionBeats();+ audioRecordStartBeat_ = takePlayhead();// Internal resampling: capture another track / send / master output instead of the// hardware input. The audio thread feeds the ring from mixGraph; no device is opened.@@ -566,9 +626,9 @@ bool Engine::startAudioRecording(int32_t trackId) {audioRecording_ = true;if (!recordSessionAudio_) {recordReturnBeat_ = audioRecordStartBeat_;- recordStartedTransport_ = !transport_.uiIsPlaying();+ recordStartedTransport_ = !takeTransportPlaying();}- if (!transport_.uiIsPlaying() && !recordCountIn_) transportPlay();+ if (!takeTransportPlaying() && !recordCountIn_) transportPlay();return true;}@@ -590,12 +650,31 @@ bool Engine::startAudioRecording(int32_t trackId) {// their own transport via launchSlot, so don't arm the rewind for them.if (!recordSessionAudio_) {recordReturnBeat_ = audioRecordStartBeat_;- recordStartedTransport_ = !transport_.uiIsPlaying();+ recordStartedTransport_ = !takeTransportPlaying();}- if (!transport_.uiIsPlaying() && !recordCountIn_) transportPlay(); // else setRecording counts in+ if (!takeTransportPlaying() && !recordCountIn_) transportPlay(); // else setRecording counts inreturn true;}+// Stop capturing and throw the capture away (a discarded take, specs/078): the taps go quiet,+// whatever the input or mix thread already queued is drained and dropped with the rest.+void Engine::abortAudioRecording() {+ if (!audioRecording_) return;+ audioRecording_ = false;+ internalRecordSource_.store(0, std::memory_order_relaxed);+ hwRecordTap_.store(false, std::memory_order_relaxed);+ releaseAudioInputIfIdle();+ drainInputQueue();+ audioCaptureBuf_.clear();+ captureScratch_.clear();+ capturePasses_.clear();+ captureWritePos_ = 0;+ captureLoop_ = false;+ captureWrapped_ = false;+ audioRecordTrackId_ = 0;+ retryStartBeat_ = std::numeric_limits<double>::quiet_NaN();+}+void Engine::stopAudioRecording() {if (!audioRecording_) return;audioRecording_ = false;@@ -642,6 +721,22 @@ void Engine::stopAudioRecording() {return;}+ // A Session audio retry (specs/078) captured from the retry on; the take starts on the launch+ // quantum after it, so what came before that boundary goes.+ // The boundary frame was noted as the capture crossed it (drainInputQueue); stopped before+ // that, nothing of the retried take is kept.+ if (recordSessionAudio_ && !std::isnan(retryStartBeat_)) {+ const size_t have = audioCaptureBuf_.size() / 2;+ const size_t drop = retryKeepFrom_ < 0 ? have : std::min(have, static_cast<size_t>(retryKeepFrom_));+ audioCaptureBuf_.erase(audioCaptureBuf_.begin(), audioCaptureBuf_.begin() + static_cast<std::ptrdiff_t>(drop * 2));+ }+ retryStartBeat_ = std::numeric_limits<double>::quiet_NaN();+ retryKeepFrom_ = -1;+ if (audioCaptureBuf_.empty()) { // stopped before the retried take's boundary: nothing to keep+ recordSessionAudio_ = false;+ return;+ }+auto sample = std::make_shared<SampleBuffer>();sample->channels = 2;sample->frames = static_cast<int64_t>(audioCaptureBuf_.size() / 2);diff --git a/src/native/nota.engine/src/engine/Engine_Render.cpp b/src/native/nota.engine/src/engine/Engine_Render.cppindex a9696dab..58e2df31 100644--- a/src/native/nota.engine/src/engine/Engine_Render.cpp+++ b/src/native/nota.engine/src/engine/Engine_Render.cpp@@ -416,12 +416,14 @@ void Engine::poll() {const int32_t replaceUpTo = replaceUpTo_.load(std::memory_order_acquire);RecordedNote rn;std::vector<RecordedNote> batch;- while (recorded_.pop(rn)) batch.push_back(rn);+ while (recorded_.pop(rn))+ if (rn.epoch == takeEpoch_) batch.push_back(rn); // a discarded take's late notes go (specs/078)// Expression after the notes: a note's points were all queued before its note-off was.collectRecordedExpr();{RecordedCtl x;- while (recordedCtl_.pop(x)) ctlBatch_.push_back(x);+ while (recordedCtl_.pop(x))+ if (x.epoch == takeEpoch_) ctlBatch_.push_back(x);} // controllers (specs/020)const bool ctlWork = !ctlBatch_.empty() || ctlStopPending_;const bool replacePending = replaceUpTo > appliedReplaceUpTo_ && recordSessionScene_ < 0;@@ -553,6 +555,7 @@ void Engine::poll() {void Engine::collectRecordedExpr() {RecordedExpr x;while (recordedExpr_.pop(x)) {+ if (x.epoch != takeEpoch_) continue; // a discarded take's (specs/078)auto& curve = pendingExpr_[{x.pitch, x.startBeat}].dim[x.dim];if (!curve.empty() && x.beat <= curve.back().beat) curve.back().value = x.value; // same instantelse@@ -742,7 +745,8 @@ void Engine::commitCtlRun(MidiClip& clip, int32_t ctl, double slotLen, bool finavoid Engine::flushCtlTake() {{RecordedCtl x;- while (recordedCtl_.pop(x)) ctlBatch_.push_back(x);+ while (recordedCtl_.pop(x))+ if (x.epoch == takeEpoch_) ctlBatch_.push_back(x);}ctlStopPending_ = true;ctlStopAt_ = transport_.uiPositionBeats();@@ -911,6 +915,20 @@ void Engine::drainCommands() {transport_.seekBeats(c.d0);seekedThisBlock_ = true;break;+ case CommandType::TakeRestart: // specs/078: the blocks from here belong to the retried take+ if ((c.i1 & 4) != 0) { // a take started normally: the current epoch, nothing waits+ rtTakeEpoch_ = static_cast<uint32_t>(c.i0);+ rtWaitScene_ = -1;+ } else if ((c.i1 & 2) != 0) { // a Session MIDI take: from when its slot relaunches+ rtPendingEpoch_ = static_cast<uint32_t>(c.i0);+ rtWaitScene_ = static_cast<int32_t>(c.d0);+ } else {+ rtTakeEpoch_ = static_cast<uint32_t>(c.i0);+ rtTakeRestart_ = true;+ rtWaitScene_ = -1;+ }+ if ((c.i1 & 1) != 0) captureGate_.store(true, std::memory_order_release);+ break;case CommandType::None: break;}}@@ -967,9 +985,23 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {// Track-addressed notes (Nota Remote) are recorded only when they play the take's// track; ordinary live input records onto it whatever it is.const int32_t recTrack = recordTrackRt_.load(std::memory_order_relaxed);- const bool takeStarted = rec && !prevRecording_;+ // A retried Session MIDI take begins when its slot has relaunched: until then what is+ // played carries the old epoch and stays out (specs/078).+ if (rtWaitScene_ >= 0 && slot && slot->pending.load(std::memory_order_relaxed) != rtWaitScene_ &&+ slot->playing.load(std::memory_order_relaxed) == rtWaitScene_) {+ rtTakeEpoch_ = rtPendingEpoch_;+ rtTakeRestart_ = true;+ rtWaitScene_ = -1;+ }+ // A retry (TakeRestart) starts a fresh take even when this thread never saw recording off.+ const bool restarted = rtTakeRestart_;+ rtTakeRestart_ = false;+ const bool takeStarted = rec && (!prevRecording_ || restarted);routedSeedPending_ = takeStarted && !slot; // routed notes held now join the take (captureRoutedNotes)- if (rec != prevRecording_)+ // A retried take restarts from a playhead that jumped back: keys still held join it at its+ // start, not at a press beat from the take that was thrown away.+ routedSeedFromNow_ = restarted;+ if (rec != prevRecording_ || restarted)for (int i = 0; i < 128; ++i) {pendingActive_[i] = false;recRoutedActive_[i] = false;@@ -1040,7 +1072,7 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {double len = nowBeat - pendingStart_[e.pitch];if (slot && len < 0.0) len += slotLen; // wrapped past the loop endRecordedNote rn{e.pitch, pendingStart_[e.pitch], len, pendingVel_[e.pitch], recordPass_};- recorded_.push(rn);+ pushRecorded(rn);pendingActive_[e.pitch] = false;}}@@ -1055,7 +1087,7 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {if (!liveDown_[p] || pendingActive_[p] || (livePressTrack_[p] >= 0 && livePressTrack_[p] != recTrack))continue;pendingActive_[p] = true;- pendingStart_[p] = (slot || std::isnan(livePressBeat_[p])) ? nowBeat : livePressBeat_[p];+ pendingStart_[p] = (slot || restarted || std::isnan(livePressBeat_[p])) ? nowBeat : livePressBeat_[p];pendingVel_[p] = livePressVel_[p];}if (rec && timed && liveExprCount_ > 0) captureLiveExpr(nowBeat, slot ? slotLen : 0.0);@@ -1067,14 +1099,14 @@ void Engine::drainLiveMidi(double blockStartBeat, bool playing) {const double seedAt = slot ? nowBeat : blockStartBeat;for (int32_t c = 0; c < kCtlCount; ++c) {const float v = liveCtl_[c].load(std::memory_order_relaxed);- if (v != kCtlRest && !ctlIsReserved(c)) recordedCtl_.push(RecordedCtl{c, seedAt, v, recordPass_});+ if (v != kCtlRest && !ctlIsReserved(c)) pushRecordedCtl(RecordedCtl{c, seedAt, v, recordPass_});}}if (rec && timed)for (int i = 0; i < liveExprCount_; ++i) {const MidiEvent& e = liveExpr_[i];if (e.expr < kCtlDimBase || (e.trackId >= 0 && e.trackId != recTrack)) continue;- recordedCtl_.push(RecordedCtl{e.expr - kCtlDimBase, nowBeat, e.velocity, recordPass_});+ pushRecordedCtl(RecordedCtl{e.expr - kCtlDimBase, nowBeat, e.velocity, recordPass_});}}@@ -1090,7 +1122,7 @@ void Engine::captureLiveExpr(double nowBeat, double slotLen) {if (!pendingActive_[e.pitch] || (e.trackId >= 0 && e.trackId != recTrack)) continue;double off = nowBeat - pendingStart_[e.pitch];if (slotLen > 0.0 && off < 0.0) off += slotLen; // a Session take wrapped past its loop end- recordedExpr_.push(+ pushRecordedExpr(RecordedExpr{e.pitch, pendingStart_[e.pitch], e.expr, static_cast<float>(std::max(0.0, off)), e.velocity});}}@@ -1128,7 +1160,7 @@ void Engine::captureRoutedNotes(const MidiEv* evs, int n, double blockStart, dourecRoutedVel_[p] = evs[k].vel;if (!recordSlotPlayer_.load(std::memory_order_relaxed)) triggerPassReplace();} else if (recRoutedActive_[p]) {- recorded_.push(RecordedNote{+ pushRecorded(RecordedNote{p, recRoutedStart_[p], std::max(0.0, beat - recRoutedStart_[p]), recRoutedVel_[p], recordPass_});recRoutedActive_[p] = false;}@@ -1143,7 +1175,7 @@ void Engine::captureRoutedNotes(const MidiEv* evs, int n, double blockStart, doufor (int p = 0; p < 128; ++p) {if (!routedDown_[p] || recRoutedActive_[p]) continue;recRoutedActive_[p] = true;- recRoutedStart_[p] = std::isnan(routedPressBeat_[p]) ? now : routedPressBeat_[p];+ recRoutedStart_[p] = (routedSeedFromNow_ || std::isnan(routedPressBeat_[p])) ? now : routedPressBeat_[p];recRoutedVel_[p] = routedPressVel_[p];}}@@ -1418,7 +1450,7 @@ void Engine::renderInstrumentRaw(for (int k = 0; k < rs_->blockExprN[j]; ++k) {const ExprEv& x = rs_->blockExpr[j][k];if (x.dim < kCtlDimBase) continue;- recordedCtl_.push(RecordedCtl{x.dim - kCtlDimBase,+ pushRecordedCtl(RecordedCtl{x.dim - kCtlDimBase,(blockStart + x.off) / spb + countInClockOffset(), x.value, recordPass_});}}@@ -1738,7 +1770,7 @@ void Engine::onLoopWrap(Graph* g, double loopStartBeat, double loopEndBeat) {constexpr double kMinHead = 1.0 / 64.0;auto split = [&](int32_t pitch, double& start, float vel) {const double head = loopEndBeat - start;- if (head >= kMinHead) recorded_.push(RecordedNote{pitch, start, head, vel, recordPass_});+ if (head >= kMinHead) pushRecorded(RecordedNote{pitch, start, head, vel, recordPass_});start = loopStartBeat;};for (int p = 0; p < 128; ++p)@@ -1746,7 +1778,7 @@ void Engine::onLoopWrap(Graph* g, double loopStartBeat, double loopEndBeat) {for (int p = 0; p < 128; ++p)if (recRoutedActive_[p]) split(p, recRoutedStart_[p], recRoutedVel_[p]);// Controllers being replaced over a range stop at the pass end (specs/020).- recordedCtl_.push(RecordedCtl{-1, loopEndBeat, 0.0f, recordPass_});+ pushRecordedCtl(RecordedCtl{-1, loopEndBeat, 0.0f, recordPass_});// A new pass of the take: the continuations above belong to it (they don't trigger a// replace — only a fresh note does), and it takes the loop record mode set right now.++recordPass_;@@ -2141,7 +2173,12 @@ void Engine::mixGraph(Graph* g, float* out, int32_t frames, double blockStart, b// Internal resampling (record from another track/send/master): tap the source's// post-fader output into the input ring while a take is rolling.- const int32_t recSrc = countInActive_ ? 0 : internalRecordSource_.load(std::memory_order_relaxed);+ // Shut while counting in, and while a retried take waits for its TakeRestart (specs/078).+ const uint32_t capEp = captureEpoch_.load(std::memory_order_acquire); // before the gate+ const int32_t recSrc = (countInActive_ || !captureGate_.load(std::memory_order_acquire))+ ? 0+ : internalRecordSource_.load(std::memory_order_relaxed);+ if (recSrc != 0) markCaptureEpoch(rtCaptureEpoch_, capEp);// Live input monitoring: this segment's hardware input (shared by every track// monitoring it), and the set of tracks whose output some monitoring track hears —diff --git a/src/native/nota.engine/src/engine/Engine_Session.cpp b/src/native/nota.engine/src/engine/Engine_Session.cppindex 9a416a54..8563ddf8 100644--- a/src/native/nota.engine/src/engine/Engine_Session.cpp+++ b/src/native/nota.engine/src/engine/Engine_Session.cpp@@ -175,7 +175,8 @@ void Engine::launchSlotImpl(Track& t, int32_t scene, float velocity, bool fromScreturn;}const SessionSlot& s = t.sessionSlots[scene];- if (!fromScene && s.launchMode == LaunchMode::Toggle && sp.playing.load(std::memory_order_relaxed) == scene &&+ if (!fromScene && !forceSlotLaunch_ && s.launchMode == LaunchMode::Toggle &&+ sp.playing.load(std::memory_order_relaxed) == scene &&sp.pending.load(std::memory_order_relaxed) == SessionPlayer::kNone) {sp.requestStop();return;@@ -282,6 +283,11 @@ void Engine::recordSessionSlot(int32_t trackId, int32_t scene) {!transport_.uiIsPlaying() && uiCountIn_.load(std::memory_order_relaxed) <= 0.0 && countInBars() > 0;sessionCountIn_ = false;sessionCountInFresh_ = false;+ // Remember the slot as it was, so the take can be discarded and retried (specs/078).+ openTakeAttempt(true);+ noteTakeTrack(trackId);+ takeAttempt_.sessionTrackId = trackId;+ takeAttempt_.sessionScene = scene;// Audio track: capture input into the slot (M5-4). Reuses the M4-3 input// pipeline; stopSessionRecord() materialises the take into slot.audio.@@ -311,11 +317,15 @@ void Engine::recordSessionSlot(int32_t trackId, int32_t scene) {recordSessionAudio_ = false;recordSessionScene_ = -1;recordSessionTrackId_ = 0;+ closeTakeAttempt();}return;}- if (t->type() != TrackType::Instrument) return;+ if (t->type() != TrackType::Instrument) {+ closeTakeAttempt();+ return;+ }// Make sure the slot holds a clip we can overdub into.const bool hasClip = scene < static_cast<int32_t>(t->sessionSlots.size()) && t->sessionSlots[scene].hasClip;// An empty slot records a fresh take: with a fixed length it is that long; otherwise it@@ -323,7 +333,10 @@ void Engine::recordSessionSlot(int32_t trackId, int32_t scene) {recordSessionGrowing_ = false;if (!hasClip) {recordSessionGrowing_ = sessionRecordLen_ <= 0.0;- addSessionMidiClip(trackId, scene, recordSessionGrowing_ ? kGrowingTakeBeats : sessionRecordLen_);+ {+ TakePushScope takePush(*this); // the take's own clip (specs/078)+ addSessionMidiClip(trackId, scene, recordSessionGrowing_ ? kGrowingTakeBeats : sessionRecordLen_);+ }t = findTrackAuthoring(trackId);if (!t) return;sessionCountInFresh_ = true;@@ -399,6 +412,7 @@ void Engine::finalizeSessionRecord(bool relaunch) {recordSessionScene_ = -1;recordSessionTrackId_ = 0;recordSessionAudio_ = false; // also when the take captured nothing (stopAudioRecording left it)+ closeTakeAttempt(); // the take is kept}// A Session take stopped during its count-in: stop the clicks (the transport never rolled),@@ -414,6 +428,7 @@ void Engine::cancelSessionCountIn() {recordSessionTrackId_ = 0;recordSessionAudio_ = false;recordSessionGrowing_ = false;+ closeTakeAttempt();arrangementActive_.store(false, std::memory_order_relaxed);uiCountIn_.store(0.0, std::memory_order_relaxed);Command c;@@ -590,8 +605,17 @@ bool Engine::setSessionSlotGain(int32_t trackId, int32_t scene, float gain) {int32_t Engine::sessionSlotState(int32_t trackId, int32_t scene) const {auto t = findTrackAuthoring(trackId);if (!t || scene < 0 || scene >= static_cast<int32_t>(t->sessionSlots.size())) return 0;- if (recording_.load(std::memory_order_relaxed) && recordSessionTrackId_ == trackId && recordSessionScene_ == scene)+ if (recording_.load(std::memory_order_relaxed) && recordSessionTrackId_ == trackId && recordSessionScene_ == scene) {+ // Not capturing yet (specs/078): a retried take before the boundary it records from, or a+ // MIDI take whose slot waits for a launch quantum (unquantized, it starts next block).+ if (!std::isnan(retryStartBeat_) && transport_.uiPositionBeats() < retryStartBeat_) return 5;+ if (auto* sp = recordSlotPlayer_.load(std::memory_order_acquire);+ !recordSessionAudio_ && launchQuant() > 0.0 && sp && sp->playing.load(std::memory_order_relaxed) != scene &&+ sp->pending.load(std::memory_order_relaxed) == scene) {+ return 5;+ }return 4; // recording+ }if (auto& sp = t->sessionPlayer) {if (sp->playing.load(std::memory_order_relaxed) == scene) return 3; // playingif (sp->pending.load(std::memory_order_relaxed) == scene) return 2; // queued@@ -1033,7 +1057,10 @@ bool Engine::sessionRecordTarget(int32_t* trackId, int32_t* scene, double* elapsif (!recording_.load(std::memory_order_relaxed) || recordSessionScene_ < 0 || recordSessionTrackId_ <= 0)return false;double el = 0.0;- if (recordSessionAudio_) el = std::max(0.0, transport_.uiPositionBeats() - audioRecordStartBeat_);+ if (recordSessionAudio_) // a retried take counts from the boundary it records from (specs/078)+ el = std::max(0.0, transport_.uiPositionBeats() -+ (std::isnan(retryStartBeat_) ? audioRecordStartBeat_+ : std::max(audioRecordStartBeat_, retryStartBeat_)));else if (auto* sp = recordSlotPlayer_.load(std::memory_order_acquire))if (sp->playing.load(std::memory_order_relaxed) == recordSessionScene_)el = sp->playedBeats.load(std::memory_order_relaxed);diff --git a/src/native/nota.engine/src/engine/Engine_TakeRetry.cpp b/src/native/nota.engine/src/engine/Engine_TakeRetry.cppnew file mode 100644index 00000000..3f63bee0--- /dev/null+++ b/src/native/nota.engine/src/engine/Engine_TakeRetry.cpp@@ -0,0 +1,270 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Discard and retry a take (#185, specs/078). A take attempt remembers, before it writes+// anything, the tracks it may write and the undo/redo state; a retry puts those tracks back+// with no history step of its own and records again — the Arrangement from where the+// transport was started, a Session slot from the next launch quantum while the rest of the+// Session plays on. The audio thread learns of the new take through a TakeRestart command+// queued behind the transport moves, so nothing from before the restart reaches it.++#include "Engine.h"++#include <algorithm>+#include <cmath>++namespace nota {++void Engine::openTakeAttempt(bool session) {+ if (!retryingTake_) syncTakeEpoch();+ takeAttempt_ = TakeAttempt{};+ takeAttempt_.active = true;+ takeAttempt_.session = session;+ takeAttempt_.undoBase = undoStack_.size();+ takeAttempt_.redoSaved = redoStack_;+}++void Engine::noteTakeTrack(int32_t trackId) {+ if (!takeAttempt_.active || !authoring_) return;+ for (const auto& b : takeAttempt_.baseTracks)+ if (b.first == trackId) return; // first write wins: that is the pre-take state+ if (auto t = findTrackAuthoring(trackId)) takeAttempt_.baseTracks.emplace_back(trackId, std::move(t));+}++// A track left the take with its part kept (disarmed while recording). Its pre-take state no+// longer applies, and the checkpoints the take made so far now hold a kept recording, so they+// become ordinary history: a later retry restores only what is still recording.+void Engine::keepTakeTrack(int32_t trackId) {+ auto& b = takeAttempt_.baseTracks;+ b.erase(std::remove_if(b.begin(), b.end(), [&](const auto& p) { return p.first == trackId; }), b.end());+ for (size_t i = std::min(takeAttempt_.undoBase, undoStack_.size()); i < undoStack_.size(); ++i)+ if (undoStack_[i].take) {+ undoStack_[i].take = false;+ undoStack_[i].wasTake = true; // a retry drops it again if it ends up changing nothing+ }+ takeAttempt_.redoSaved.clear(); // a kept recording is an edit: the old redo branch is gone+}++// Every take that starts without a retry puts the audio thread on the current take epoch and+// cancels a Session retry still waiting for its slot — one stopped before it relaunched would+// otherwise leave the next take's events on an epoch poll() drops.+void Engine::syncTakeEpoch() {+ Command c;+ c.type = CommandType::TakeRestart;+ c.i0 = static_cast<int32_t>(takeEpoch_);+ c.i1 = 4; // epoch only: no restart, the gate as it is+ commands_.push(c);+}++void Engine::closeTakeAttempt() {+ takeAttempt_ = TakeAttempt{};+ retryStartBeat_ = std::numeric_limits<double>::quiet_NaN();+}++void Engine::discardTake() {+ if (!takeAttempt_.active) return;+ TakeAttempt a = std::move(takeAttempt_);+ takeAttempt_ = TakeAttempt{};++ // Stop capturing: automation writes end (their lanes come back with the tracks below),+ // the audio capture is dropped unmaterialised, and the MIDI fold forgets the take.+ finishAllWrites();+ recording_.store(false, std::memory_order_relaxed);+ abortAudioRecording();+ {+ RecordedNote n;+ while (recorded_.pop(n)) {}+ RecordedExpr x;+ while (recordedExpr_.pop(x)) {}+ }+ resetCtlFold();+ pendingExpr_.clear();+ takeNotes_.clear();+ appliedReplaceUpTo_ = 0;+ replaceUpTo_.store(0, std::memory_order_relaxed);+ ++takeEpoch_; // whatever the audio thread still queues for the old take is dropped by poll()+ recordTrackId_ = 0;+ recordClipIndex_ = -1;+ recordTrackRt_.store(-1, std::memory_order_relaxed);+ recordSlotPlayer_.store(nullptr, std::memory_order_release);+ recordSessionScene_ = -1;+ recordSessionTrackId_ = 0;+ recordSessionAudio_ = false;+ recordSessionGrowing_ = false;+ sessionCountIn_ = false;+ retryStartBeat_ = std::numeric_limits<double>::quiet_NaN();++ // Put the tracks back as they were before the take wrote them — in the graph that plays and+ // in every checkpoint the user's own edits pushed meanwhile, so undoing one of those later+ // doesn't bring the take back. A Session take restores only its slot, so edits to the+ // track's other slots stay.+ auto baseOf = [&](int32_t id) -> std::shared_ptr<Track> {+ for (const auto& b : a.baseTracks)+ if (b.first == id) return b.second;+ return nullptr;+ };+ auto restoreTrack = [&](const std::shared_ptr<Track>& cur) -> std::shared_ptr<Track> {+ auto base = cur ? baseOf(cur->id()) : nullptr;+ if (!base) return cur;+ if (!a.session || cur->id() != a.sessionTrackId) return base;+ auto nt = cloneTrack(*cur);+ const int32_t sc = a.sessionScene;+ if (sc < 0) return nt;+ if (static_cast<int32_t>(nt->sessionSlots.size()) <= sc) nt->sessionSlots.resize(sc + 1);+ nt->sessionSlots[sc] =+ sc < static_cast<int32_t>(base->sessionSlots.size()) ? base->sessionSlots[sc] : SessionSlot{};+ return nt;+ };+ auto restoreGraph = [&](const Graph& src) {+ auto g = std::make_shared<Graph>();+ inheritGraphLevel(*g, src);+ g->tracks.reserve(src.tracks.size());+ for (const auto& t : src.tracks) g->tracks.push_back(restoreTrack(t));+ g->masterTrack = restoreTrack(src.masterTrack);+ return g;+ };+ if (authoring_ && !a.baseTracks.empty()) {+ publishRaw(restoreGraph(*authoring_));+ placeTakesForTempo();+ recomputePdc();+ reapplyRackMacros();+ reapplyCcRoutes();+ }++ // No history of its own: the take's checkpoints go (a value change merged into one stays,+ // without the graph — that is the user's hand, not the take). The user's checkpoints made+ // meanwhile stay, without the take in them; with none, the redo branch comes back.+ const size_t base = std::min(a.undoBase, undoStack_.size());+ std::vector<UndoEntry> kept;+ bool userEdits = false;+ for (size_t i = base; i < undoStack_.size(); ++i) {+ UndoEntry e = std::move(undoStack_[i]);+ if (e.take) {+ if (e.mix.empty()) continue;+ e.graph = nullptr;+ e.take = false;+ } else if (e.graph && !a.baseTracks.empty()) {+ e.graph = restoreGraph(*e.graph);+ }+ userEdits = true;+ kept.push_back(std::move(e));+ }+ // A checkpoint the take made before part of it was kept (wasTake) may now step between two+ // identical states — its content was the part just discarded: an Undo that changes nothing.+ // Drop those (track-only edits, so comparing the tracks is enough).+ auto sameTracks = [](const Graph& x, const Graph& y) {+ if (x.masterTrack != y.masterTrack || x.tracks.size() != y.tracks.size()) return false;+ for (size_t k = 0; k < x.tracks.size(); ++k)+ if (x.tracks[k] != y.tracks[k]) return false;+ return true;+ };+ std::shared_ptr<Graph> next = authoring_;+ for (size_t k = kept.size(); k-- > 0;) {+ if (!kept[k].graph) continue;+ if (kept[k].wasTake && kept[k].mix.empty() && next && sameTracks(*kept[k].graph, *next)) {+ kept.erase(kept.begin() + static_cast<std::ptrdiff_t>(k));+ continue;+ }+ next = kept[k].graph;+ }+ userEdits = !kept.empty();+ undoStack_.resize(base);+ for (auto& e : kept) undoStack_.push_back(std::move(e));+ if (!userEdits) redoStack_ = std::move(a.redoSaved);+}++int32_t Engine::retryTake() {+ if (!takeAttempt_.active) return 0;+ // The take already ended (its track was disarmed, say): it was kept — nothing to retry.+ if (!isRecording()) {+ closeTakeAttempt();+ return 0;+ }++ // waitScene >= 0: a Session MIDI take — the audio thread adopts the new epoch only when+ // that slot has relaunched, so nothing played while it waits enters the take.+ auto pushTakeRestart = [&](bool openGate, int32_t waitScene) {+ Command c;+ c.type = CommandType::TakeRestart;+ c.i0 = static_cast<int32_t>(takeEpoch_);+ c.i1 = (openGate ? 1 : 0) | (waitScene >= 0 ? 2 : 0);+ c.d0 = waitScene;+ commands_.push(c);+ };+ // Shut the capture, then move the capture epoch: a producer that sees the new epoch also+ // sees the gate shut, until the restart command opens it behind the transport moves.+ auto fenceCapture = [&]() {+ captureGate_.store(false, std::memory_order_relaxed);+ captureEpoch_.store(takeEpoch_, std::memory_order_release);+ };+ struct Retrying {+ Engine& e;+ explicit Retrying(Engine& en) : e(en) { e.retryingTake_ = true; }+ ~Retrying() { e.retryingTake_ = false; }+ };++ if (takeAttempt_.session) {+ const int32_t tid = takeAttempt_.sessionTrackId, sc = takeAttempt_.sessionScene;+ // Still counting in from stop: nothing was recorded — start the count-in over, as Stop+ // and a fresh Record into the slot would.+ if (sessionCountIn_ && uiCountIn_.load(std::memory_order_relaxed) > 0.0) {+ sessionCountIn_ = false;+ countInLaunchScene_.store(-1, std::memory_order_release);+ cancelSessionCountIn();+ recordSessionSlot(tid, sc);+ return isRecording() ? 2 : -1;+ }+ const bool audio = recordSessionAudio_;+ discardTake();+ fenceCapture();+ // The take records again from the next launch quantum (now when launching is+ // unquantized); until then the slot shows it is waiting (slot state 5). The slot+ // relaunches whatever its launch mode (a Toggle slot would stop instead).+ const double q = launchQuant();+ const double pos = transport_.uiPositionBeats();+ const double at = q > 0.0 ? std::ceil(pos / q - 1e-9) * q : pos;+ {+ Retrying r(*this);+ forceSlotLaunch_ = true;+ recordSessionSlot(tid, sc);+ forceSlotLaunch_ = false;+ }+ pushTakeRestart(true, audio ? -1 : sc);+ if (!isRecording()) {+ captureGate_.store(true, std::memory_order_relaxed);+ return -1;+ }+ if (at > pos) retryStartBeat_ = at;+ return 2;+ }++ // Arrangement: back to where the transport was started for this take — its start when+ // the take rolled the transport, else where Play was pressed (the punch-in's run-up).+ const bool countedIn = takeAttempt_.countedIn;+ const bool startedTransport = recordStartedTransport_;+ const double restart = startedTransport ? recordReturnBeat_ : transport_.uiAnchorBeats();+ discardTake();+ fenceCapture(); // nothing until the playhead is back+ if (countedIn) {+ transportStop(); // count in again from stop, as the take did+ seekBeats(restart);+ pushTakeRestart(countInBars() <= 0, -1); // else the count-in's end opens the gate+ } else {+ seekBeats(restart); // keep rolling: the run-up plays again+ pushTakeRestart(true, -1);+ }+ bool ok;+ {+ Retrying r(*this);+ ok = startArrangementTake(!countedIn, restart, countedIn);+ }+ recordStartedTransport_ = startedTransport;+ recordReturnBeat_ = restart;+ if (!ok) {+ captureGate_.store(true, std::memory_order_relaxed);+ return -1;+ }+ return 1;+}++} // namespace notadiff --git a/src/native/nota.engine/src/engine/Transport.cpp b/src/native/nota.engine/src/engine/Transport.cppindex a1fa4a86..b39f8aba 100644--- a/src/native/nota.engine/src/engine/Transport.cpp+++ b/src/native/nota.engine/src/engine/Transport.cpp@@ -40,6 +40,7 @@ TransportInfo Transport::transportInfo(double blockStartSamples) const {void Transport::publish() {uiBeats_.store(positionBeats(), std::memory_order_relaxed);uiPlaying_.store(playing_, std::memory_order_relaxed);+ uiAnchorBeats_.store(startAnchorSamples_ / samplesPerBeat(), std::memory_order_relaxed);}static int64_t presentationNow() {diff --git a/src/native/nota.engine/src/engine/Transport.h b/src/native/nota.engine/src/engine/Transport.hindex 1d94c0eb..263fd6cf 100644--- a/src/native/nota.engine/src/engine/Transport.h+++ b/src/native/nota.engine/src/engine/Transport.h@@ -88,6 +88,8 @@ class Transport {// Atomic mirror for the UI (poll these; never touch the private fields).double uiPositionBeats() const { return uiBeats_.load(std::memory_order_relaxed); }bool uiIsPlaying() const { return uiPlaying_.load(std::memory_order_relaxed); }+ // Where Stop rewinds to / Play launched from (the insert marker), in beats.+ double uiAnchorBeats() const { return uiAnchorBeats_.load(std::memory_order_relaxed); }// Publish once per completed block; readers may skip a frame, never delay audio.void publishPresentation(double startSamples, int32_t playingFrames, int32_t leadingFrames, int32_t windowFrames);@@ -108,6 +110,7 @@ class Transport {std::atomic<double> uiBeats_{0.0};std::atomic<bool> uiPlaying_{false};+ std::atomic<double> uiAnchorBeats_{0.0};// Atomic payloads avoid data races even when a reader overlaps the writer.// A bounded version check rejects mixed blocks. Release/acquire on each fielddiff --git a/tests/Nota.SmokeTest/LocalizationAllowList.txt b/tests/Nota.SmokeTest/LocalizationAllowList.txtindex 248945fb..6f40115d 100644--- a/tests/Nota.SmokeTest/LocalizationAllowList.txt+++ b/tests/Nota.SmokeTest/LocalizationAllowList.txt@@ -2583,6 +2583,7 @@ Nota.Application/Palette/CommandCatalog.cs snapshot history commit # data: searcNota.Application/Palette/CommandCatalog.cs track list side left right swap mirror ableton # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs track mode whole track all clips every clip piano roll # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs undo history versions snapshots # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)+Nota.Application/Palette/CommandCatalog.cs undo restart retry discard take again redo record over punch # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs update upgrade new version download install # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/CommandCatalog.cs zoom vertical rows height # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)Nota.Application/Palette/DeviceCategories.cs Distortion # data: search keywords, device and node names, category ids (FR-004; what is drawn goes through Loc)diff --git a/tests/Nota.SmokeTest/Program.cs b/tests/Nota.SmokeTest/Program.csindex 6f62b6dc..12d7839f 100644--- a/tests/Nota.SmokeTest/Program.cs+++ b/tests/Nota.SmokeTest/Program.cs@@ -720,6 +720,14 @@ if (args.Length >= 1 && args[0] == "--group-link")Console.WriteLine(failures == 0 ? "GROUP LINK PASSED" : $"GROUP LINK FAILED ({failures})");return failures == 0 ? 0 : 1;}+// Discard and retry a take alone (fast iteration): `--retry-take`. Also part of the full run.+if (args.Length >= 1 && args[0] == "--retry-take")+{+ Console.WriteLine("-- retry take --");+ foreach (var (ok, label) in RetryTakeTests.Run()) Check(ok, label);+ Console.WriteLine(failures == 0 ? "RETRY TAKE PASSED" : $"RETRY TAKE FAILED ({failures})");+ return failures == 0 ? 0 : 1;+}// Live MIDI recording alone (fast iteration): `--live-record`. Also part of the full run.if (args.Length >= 1 && args[0] == "--live-record"){@@ -15417,6 +15425,8 @@ Console.WriteLine("-- mpe: per-note expression --");foreach (var (ok, label) in MpeTests.Run()) Check(ok, label);Console.WriteLine("-- live midi recording --");foreach (var (ok, label) in LiveRecordTests.Run()) Check(ok, label);+Console.WriteLine("-- retry take --");+foreach (var (ok, label) in RetryTakeTests.Run()) Check(ok, label);Console.WriteLine("-- midi controllers --");foreach (var (ok, label) in MidiControllerTests.Run()) Check(ok, label);Console.WriteLine("-- sustain pedal --");diff --git a/tests/Nota.SmokeTest/RetryTakeTests.cs b/tests/Nota.SmokeTest/RetryTakeTests.csnew file mode 100644index 00000000..4d448ad1--- /dev/null+++ b/tests/Nota.SmokeTest/RetryTakeTests.cs@@ -0,0 +1,624 @@+// SPDX-License-Identifier: AGPL-3.0-only+// Copyright (c) 2026 Egor Khindikaynen (Nota). See LICENSES/ for license terms.+//+// Discard and retry a take (#185, specs/078): the take in progress goes with no undo or redo+// step and records again — the Arrangement from where the transport was started (counting in+// again when the take did), a Session slot from the next launch quantum while the other clips+// keep playing. Device-free: MIDI takes from live notes, audio takes from internal resampling.++using Nota.Application;+using Nota.Infrastructure;++namespace Nota.SmokeTest;++internal static class RetryTakeTests+{+ private const double Sr = 48000.0;+ private const double Spb = Sr * 60.0 / 120.0; // frames per beat at 120 BPM+ private const int Chunk = 256;++ public static IEnumerable<(bool, string)> Run()+ {+ foreach (var r in Catalog()) yield return r;+ foreach (var r in NothingRecording()) yield return r;+ foreach (var r in MidiFromStopWithCountIn()) yield return r;+ foreach (var r in OverdubIntoClip()) yield return r;+ foreach (var r in PunchIn()) yield return r;+ foreach (var r in HeldAcrossRetry()) yield return r;+ foreach (var r in Automation()) yield return r;+ foreach (var r in AudioTake()) yield return r;+ foreach (var r in LoopPasses()) yield return r;+ foreach (var r in SessionMidi()) yield return r;+ foreach (var r in SessionAudio()) yield return r;+ foreach (var r in SessionCountIn()) yield return r;+ foreach (var r in AutomationOnAnotherTrack()) yield return r;+ foreach (var r in EditsMadeMeanwhile()) yield return r;+ foreach (var r in DisarmedTakeIsKept()) yield return r;+ foreach (var r in SessionHeldIntoRelaunch()) yield return r;+ foreach (var r in SessionToggleSlot()) yield return r;+ foreach (var r in SessionAudioTempoChange()) yield return r;+ foreach (var r in DisarmOneOfTwo()) yield return r;+ foreach (var r in StoppedWhilePending()) yield return r;+ foreach (var r in NoEmptyUndoAfterPartialKeep()) yield return r;+ }++ // Audio and MIDI into empty tracks, audio disarmed (kept), MIDI retried and kept: two undo+ // steps, each one undoing a recording — no step left that changes nothing.+ private static IEnumerable<(bool, string)> NoEmptyUndoAfterPartialKeep()+ {+ using var e = Resampling(out int rec);+ int t = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(t, 0);+ e.SetTrackArmed(t, true);+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.ClearUndoHistory();+ e.SetRecording(true);+ Beats(e, 0.5);+ Tap(e, 60, 0.5);+ e.SetTrackArmed(rec, false); // the audio take is kept+ e.Poll();+ e.RetryTake();+ Beats(e, 0.5);+ Tap(e, 64, 0.5);+ e.SetRecording(false);+ e.Poll();+ e.StopTransport();+ bool u1 = e.Undo();+ bool midiGone = Notes(e, t).Count == 0 && AudioClips(e, rec) == 1;+ bool u2 = e.Undo();+ bool audioGone = AudioClips(e, rec) == 0;+ yield return (u1 && midiGone && u2 && audioGone && !e.CanUndo,+ $"retry after a partial keep: two undo steps, none empty (midi undone {midiGone}, audio undone {audioGone}, more {e.CanUndo})");+ }++ // Recording audio and MIDI together, one track disarmed: its take is kept, the other can+ // still be retried.+ private static IEnumerable<(bool, string)> DisarmOneOfTwo()+ {+ using var e = Resampling(out int rec);+ int t = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(t, 0);+ e.SetTrackArmed(t, true);+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 0.5);+ Tap(e, 60, 0.5);+ e.SetTrackArmed(rec, false); // the audio take ends here and is kept+ e.Poll();+ int audio = AudioClips(e, rec);+ var r = e.RetryTake();+ Beats(e, 0.01);+ yield return (audio == 1 && r == RetryTakeResult.Arrangement && AudioClips(e, rec) == 1 && Notes(e, t).Count == 0,+ $"retry after disarming one of two: the kept audio stays, the MIDI is retried ({r}, audio clips {AudioClips(e, rec)}, notes {Notes(e, t).Count})");+ e.SetRecording(false);+ e.StopTransport();+ }++ // A Session MIDI retry stopped before its slot relaunched: the next ordinary take records.+ private static IEnumerable<(bool, string)> StoppedWhilePending()+ {+ using var e = Armed(out int t);+ e.SetLaunchQuant(4.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 0.5);+ e.RecordSessionSlot(t, 0);+ Beats(e, 4.0);+ e.RetryTake(); // waits for beat 8+ Beats(e, 0.5);+ e.StopSessionRecord();+ e.StopAllSession();+ e.StopTransport();+ e.BackToArrangement();+ Beats(e, 0.05);+ e.SetCountIn(0);+ e.Seek(16.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 0.5);+ Tap(e, 67, 0.5);+ e.SetRecording(false);+ e.Poll();+ yield return (Notes(e, t).Any(n => n.Note.Pitch == 67),+ $"retry session stopped while pending: the next Arrangement take still records ({string.Join(",", Notes(e, t).Select(n => n.Note.Pitch))})");+ e.StopTransport();+ }++ // Review of #486. A lane written on a track the take doesn't record goes with the take too.+ private static IEnumerable<(bool, string)> AutomationOnAnotherTrack()+ {+ using var e = Armed(out int t);+ int o = e.AddInstrumentTrack();+ int lanes = e.AutomationLaneCount(o);+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 0.5);+ e.BeginAutomationWrite(o, AutomationTarget.Volume, -1, -1, "");+ Beats(e, 0.5);+ e.EndAutomationWrite(o, AutomationTarget.Volume, -1, -1, "");+ bool wrote = e.AutomationLaneCount(o) > lanes;+ e.RetryTake();+ Beats(e, 0.01);+ yield return (wrote && e.AutomationLaneCount(o) == lanes,+ $"retry automation elsewhere: another track's lane written in the take goes too ({lanes} → {e.AutomationLaneCount(o)})");+ e.SetRecording(false);+ e.StopTransport();+ }++ // An edit made during the take keeps its undo step, and undoing it doesn't bring the take back.+ private static IEnumerable<(bool, string)> EditsMadeMeanwhile()+ {+ using var e = Armed(out int t);+ int o = e.AddInstrumentTrack();+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 0.5);+ Tap(e, 60, 0.5);+ e.AddMidiClip(o, 8, 4); // the user's own edit, mid-take+ e.RetryTake();+ Beats(e, 0.5);+ Tap(e, 62, 0.5);+ e.SetRecording(false);+ e.Poll();+ e.StopTransport();+ bool kept = Clips(e, o).Count == 1;+ e.Undo(); // the kept take+ bool takeGone = Notes(e, t).Count == 0 && Clips(e, o).Count == 1;+ e.Undo(); // the edit made during the discarded take+ bool editGone = Clips(e, o).Count == 0 && Notes(e, t).All(n => n.Note.Pitch != 60);+ yield return (kept && takeGone && editGone,+ $"retry: an edit made meanwhile keeps its undo step, without the discarded take in it (kept {kept}, take undone {takeGone}, edit undone {editGone})");+ }++ // Disarming the track ends (and keeps) its take: a retry afterwards has nothing to discard.+ private static IEnumerable<(bool, string)> DisarmedTakeIsKept()+ {+ using var e = Armed(out int t);+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 0.5);+ Tap(e, 60, 0.5);+ e.SetTrackArmed(t, false);+ e.Poll();+ var r = e.RetryTake();+ yield return (r == RetryTakeResult.None && Notes(e, t).Any(n => n.Note.Pitch == 60),+ $"retry after disarm: the kept take stays ({r})");+ e.SetRecording(false);+ e.StopTransport();+ }++ // A key pressed while the retried slot waits and released after it relaunched: the new+ // take holds it from the relaunch — no note wrapped round the open-ended slot.+ private static IEnumerable<(bool, string)> SessionHeldIntoRelaunch()+ {+ using var e = Armed(out int t);+ e.SetLaunchQuant(4.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 0.5);+ e.RecordSessionSlot(t, 0);+ Beats(e, 4.0); // recording from beat 4+ Tap(e, 60, 0.5);+ e.RetryTake(); // waits for beat 8+ Beats(e, 1.0);+ e.SendController(1, 0.7f); // played while pending: not part of the take+ e.NoteOn(64, 0.8f);+ Beats(e, 2.5); // past the relaunch at 8+ e.NoteOff(64);+ Beats(e, 0.1);+ e.StopSessionRecord();+ Beats(e, 0.05);+ var notes = e.GetSessionNotes(t, 0);+ var n64 = notes.Where(n => n.Pitch == 64).ToList();+ yield return (notes.All(n => n.Pitch != 60) && n64.Count == 1 && n64[0].StartBeat < 0.1 && n64[0].LengthBeats < 1.0,+ $"retry session held key: starts with the relaunched take ({string.Join(",", notes.Select(n => $"{n.Pitch}@{n.StartBeat:F2}+{n.LengthBeats:F2}"))})");+ e.StopAllSession();+ e.StopTransport();+ }++ // A Toggle slot relaunches for the retried take instead of stopping.+ private static IEnumerable<(bool, string)> SessionToggleSlot()+ {+ using var e = Armed(out int t);+ e.AddSessionMidiClip(t, 0, 4);+ e.TryGetSessionClipProps(t, 0, out var p);+ p.LaunchMode = 2; // Toggle+ e.SetSessionClipProps(t, 0, p);+ e.SetLaunchQuant(4.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 0.5);+ e.RecordSessionSlot(t, 0);+ Beats(e, 4.0);+ e.RetryTake();+ Beats(e, 4.0); // past the relaunch at 8+ yield return (e.SessionPlayingSlot(t) == 0 && e.SessionSlotState(t, 0) == 4,+ $"retry toggle slot: relaunches and records (playing {e.SessionPlayingSlot(t)}, state {e.SessionSlotState(t, 0)})");+ e.StopSessionRecord();+ e.StopAllSession();+ e.StopTransport();+ }++ // A tempo change after the boundary doesn't move where the retried audio take begins.+ private static IEnumerable<(bool, string)> SessionAudioTempoChange()+ {+ using var e = Resampling(out int rec);+ e.SetCountIn(0);+ e.SetLaunchQuant(4.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 0.5);+ e.RecordSessionSlot(rec, 0);+ Beats(e, 0.5);+ e.RetryTake(); // boundary at 4+ Beats(e, 4.0); // ~1 beat past it at 120 BPM: 24000 frames+ e.SetBpm(60);+ Beats(e, 0.01);+ var b = new float[Chunk * 2];+ for (int done = 0; done < 48000; done += Chunk) { e.RenderOffline(b, Chunk, Sr); e.Poll(); } // 1 s more+ e.StopSessionRecord();+ Beats(e, 0.01);+ int idx = e.SessionSlotToArrangement(rec, 0, 32.0);+ long frames = idx >= 0 && e.TryGetAudioClipInfo(rec, idx, out var ci) && e.TryGetSampleInfo(ci.SampleId, out var si) ? si.Frames : -1;+ yield return (Math.Abs(frames - 72000) < 2500,+ $"retry session audio + tempo change: keeps what followed the boundary ({frames} frames, ~72000 expected)");+ e.StopAllSession();+ e.StopTransport();+ }++ // A retry during a Session count-in starts the count-in over; nothing was recorded yet.+ private static IEnumerable<(bool, string)> SessionCountIn()+ {+ using var e = Armed(out int t);+ e.SetLaunchQuant(4.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetCountIn(1);+ e.RecordSessionSlot(t, 0);+ Beats(e, 2.5);+ double left = e.CountInBeats;+ var r = e.RetryTake();+ Beats(e, 0.01);+ double again = e.CountInBeats;+ yield return (r == RetryTakeResult.Session && left < 2.0 && again > 3.5 && !e.IsPlaying && e.IsRecording,+ $"retry session count-in: the count-in starts over ({left:F2} → {again:F2} beats left)");+ Beats(e, 4.5);+ yield return (e.IsPlaying && e.SessionPlayingSlot(t) == 0, "retry session count-in: then the slot records as it runs out");+ e.StopSessionRecord();+ e.StopAllSession();+ e.StopTransport();+ }++ private static void Beats(NotaEngine e, double beats)+ {+ var b = new float[Chunk * 2];+ int frames = (int)Math.Round(beats * Spb);+ for (int done = 0; done < frames; done += Chunk) { e.RenderOffline(b, Chunk, Sr); e.Poll(); }+ }++ private static NotaEngine Armed(out int track)+ {+ var e = new NotaEngine();+ e.SetBpm(120);+ e.SetMetronome(false);+ track = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(track, 0);+ e.SetTrackArmed(track, true);+ e.StopTransport();+ e.RenderOffline(new float[Chunk * 2], Chunk, Sr);+ return e;+ }++ // An instrument track sounding a long note, recorded into an armed audio track.+ private static NotaEngine Resampling(out int rec)+ {+ var e = new NotaEngine();+ e.SetBpm(120);+ e.SetMetronome(false);+ int src = e.AddBassSynthTrack();+ int mc = e.AddMidiClip(src, 0, 64);+ e.SetClipNotes(src, mc, new[] { new NotaNote(36, 0.0, 64.0, 1.0f) });+ rec = e.AddAudioTrack();+ e.SetTrackRecordInput(rec, src);+ e.SetTrackArmed(rec, true);+ e.StopTransport();+ e.RenderOffline(new float[Chunk * 2], Chunk, Sr);+ return e;+ }++ private static List<(NotaClipInfo Info, NotaNote[] Notes)> Clips(NotaEngine e, int track)+ {+ var all = new List<(NotaClipInfo, NotaNote[])>();+ for (int c = 0; c < 64 && e.TryGetClipInfo(track, c, out var ci); c++) all.Add((ci, e.GetClipNotes(track, c)));+ return all;+ }++ private static List<(double Abs, NotaNote Note)> Notes(NotaEngine e, int track)+ => Clips(e, track).SelectMany(c => c.Notes.Select(n => (c.Info.StartBeat + n.StartBeat, n))).ToList();++ private static int AudioClips(NotaEngine e, int track)+ {+ int n = 0;+ while (n < 64 && e.TryGetAudioClipInfo(track, n, out _)) n++;+ return n;+ }++ private static void Tap(NotaEngine e, int pitch, double holdBeats)+ {+ e.NoteOn(pitch, 0.8f);+ Beats(e, holdBeats);+ e.NoteOff(pitch);+ Beats(e, 0.05);+ }++ private static bool Near(double a, double b, double tol = 0.05) => Math.Abs(a - b) <= tol;++ // ⌘. (Ctrl+. elsewhere) runs it, from the Transport group; "retry" / "undo restart" find it.+ private static IEnumerable<(bool, string)> Catalog()+ {+ var c = Nota.Application.Palette.CommandCatalog.Create().FirstOrDefault(x => x.Id == "transport.retryTake");+ yield return (c is not null && c.Gesture == "⌘." && c.Aliases.Contains("retry") && c.Aliases.Contains("restart"),+ $"retry: the catalog holds transport.retryTake on ⌘. ({c?.Gesture ?? "missing"})");+ }++ private static IEnumerable<(bool, string)> NothingRecording()+ {+ using var e = Armed(out int t);+ bool undo = e.CanUndo, redo = e.CanRedo;+ var r = e.RetryTake();+ yield return (r == RetryTakeResult.None && !e.IsRecording && !e.IsPlaying && e.CanUndo == undo && e.CanRedo == redo && Clips(e, t).Count == 0,+ $"retry: nothing recording changes nothing ({r})");+ }++ // The issue's case: a take from stop with a count-in. Retry drops it (and the clip it made),+ // returns to the take start, counts in again and records; the kept take is one undo step.+ private static IEnumerable<(bool, string)> MidiFromStopWithCountIn()+ {+ using var e = Armed(out int t);+ e.Seek(8.0);+ Beats(e, 0.01);+ e.SetCountIn(1);+ e.SetRecording(true);+ Beats(e, 4.5); // the bar of count-in, then half a beat of take+ Tap(e, 60, 0.5);+ yield return (Notes(e, t).Any(n => n.Note.Pitch == 60), "retry count-in: the first take recorded a note");++ var r = e.RetryTake();+ Beats(e, 0.01);+ // The new take opens its clip at the start, as any take does: empty, the first take's note gone.+ yield return (r == RetryTakeResult.Arrangement && e.IsRecording && Clips(e, t).Count <= 1 && Notes(e, t).Count == 0,+ $"retry count-in: the take's notes are gone, recording again ({r}, clips {Clips(e, t).Count}, notes {Notes(e, t).Count})");+ yield return (e.CountInBeats > 0 && !e.IsPlaying && Near(e.PositionBeats, 8.0),+ $"retry count-in: counting in again at the take start (count-in {e.CountInBeats:F2}, at {e.PositionBeats:F2})");+ yield return (!e.CanRedo, "retry count-in: no redo step");++ Beats(e, 4.5);+ Tap(e, 64, 0.5);+ e.SetRecording(false);+ e.Poll();+ var notes = Notes(e, t);+ var n64 = notes.FirstOrDefault(n => n.Note.Pitch == 64);+ yield return (notes.All(n => n.Note.Pitch != 60) && notes.Any(n => n.Note.Pitch == 64) && Near(n64.Abs, 8.5, 0.06),+ $"retry count-in: only the second take is kept, where it was played ({string.Join(",", notes.Select(n => $"{n.Note.Pitch}@{n.Abs:F2}"))})");+ e.StopTransport();+ bool undone = e.Undo();+ yield return (undone && Clips(e, t).Count == 0, "retry count-in: one undo removes the kept take — the discarded one left no step");+ bool redone = e.Redo();+ yield return (redone && Notes(e, t).Any(n => n.Note.Pitch == 64) && !e.CanRedo,+ "retry count-in: redo brings back only the kept take");+ }++ // Overdubbing into a clip: the retry gives the clip its notes back, nothing more.+ private static IEnumerable<(bool, string)> OverdubIntoClip()+ {+ using var e = Armed(out int t);+ int c = e.AddMidiClip(t, 0, 16);+ e.SetClipNotes(t, c, new[] { new NotaNote(50, 2.0, 1.0, 0.7f) });+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 1.0);+ Tap(e, 60, 0.5);+ var r = e.RetryTake();+ Beats(e, 0.01);+ var notes = Notes(e, t);+ yield return (r == RetryTakeResult.Arrangement && Clips(e, t).Count == 1 && notes.Count == 1 && notes[0].Note.Pitch == 50,+ $"retry overdub: the clip holds what it held before the take ({string.Join(",", notes.Select(n => n.Note.Pitch))})");+ yield return (e.IsPlaying && e.PositionBeats < 0.5, $"retry overdub: rolling again from the take start (at {e.PositionBeats:F2})");+ e.SetRecording(false);+ e.StopTransport();+ }++ // Punched in during playback: the retry goes back to where Play was pressed and keeps rolling.+ private static IEnumerable<(bool, string)> PunchIn()+ {+ using var e = Armed(out int t);+ e.SetCountIn(1); // set, but a punch-in never counts in+ e.Seek(4.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 4.0); // ~beat 8+ e.SetRecording(true);+ Beats(e, 0.5);+ Tap(e, 60, 0.5);+ var r = e.RetryTake();+ Beats(e, 0.05);+ yield return (r == RetryTakeResult.Arrangement && e.IsRecording && e.IsPlaying && e.CountInBeats <= 0 && Near(e.PositionBeats, 4.05, 0.05),+ $"retry punch-in: back to where Play was pressed, rolling, no count-in ({r}, at {e.PositionBeats:F2}, count-in {e.CountInBeats:F2})");+ Beats(e, 0.45);+ Tap(e, 62, 0.5);+ e.SetRecording(false);+ e.Poll();+ var notes = Notes(e, t);+ yield return (notes.All(n => n.Note.Pitch != 60) && notes.Any(n => n.Note.Pitch == 62 && Near(n.Abs, 4.5, 0.06)),+ $"retry punch-in: only the new take, recorded from the run-up ({string.Join(",", notes.Select(n => $"{n.Note.Pitch}@{n.Abs:F2}"))})");+ e.StopTransport();+ }++ // A key held through the retry joins the new take at its start, not at its old press beat.+ private static IEnumerable<(bool, string)> HeldAcrossRetry()+ {+ using var e = Armed(out int t);+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 1.0);+ e.NoteOn(60, 0.8f);+ Beats(e, 0.5);+ e.RetryTake();+ Beats(e, 1.0);+ e.NoteOff(60);+ Beats(e, 0.05);+ e.SetRecording(false);+ e.Poll();+ var n60 = Notes(e, t).Where(n => n.Note.Pitch == 60).ToList();+ yield return (n60.Count == 1 && n60[0].Abs < 0.05 && Near(n60[0].Note.LengthBeats, 1.0, 0.06),+ $"retry held key: starts with the new take ({(n60.Count > 0 ? $"{n60[0].Abs:F2}+{n60[0].Note.LengthBeats:F2}" : "none")}, n={n60.Count})");+ e.StopTransport();+ }++ // Automation written while the record button is down goes with the take.+ private static IEnumerable<(bool, string)> Automation()+ {+ using var e = Armed(out int t);+ int lanes = e.AutomationLaneCount(t);+ e.SetCountIn(0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 0.5);+ e.BeginAutomationWrite(t, AutomationTarget.Pan, -1, -1, "");+ Beats(e, 0.5);+ e.EndAutomationWrite(t, AutomationTarget.Pan, -1, -1, "");+ bool wrote = e.AutomationLaneCount(t) > lanes;+ e.RetryTake();+ Beats(e, 0.01);+ yield return (wrote && e.AutomationLaneCount(t) == lanes && e.AutomationRecording,+ $"retry automation: the lane the take wrote is gone, record stays on (lanes {lanes} → {e.AutomationLaneCount(t)})");+ e.SetRecording(false);+ e.StopTransport();+ }++ // An audio take: no clip survives the retry; the kept take sits where the first began.+ private static IEnumerable<(bool, string)> AudioTake()+ {+ using var e = Resampling(out int rec);+ e.SetCountIn(0);+ e.Seek(2.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 1.0);+ var r = e.RetryTake();+ Beats(e, 0.01);+ yield return (r == RetryTakeResult.Arrangement && AudioClips(e, rec) == 0 && e.IsRecording,+ $"retry audio: the capture is dropped unmaterialised ({r}, clips {AudioClips(e, rec)})");+ Beats(e, 1.0);+ e.SetRecording(false);+ e.Poll();+ bool one = AudioClips(e, rec) == 1 && e.TryGetAudioClipInfo(rec, 0, out var ci) && Near(ci.StartBeat, 2.0, 0.01);+ e.TryGetAudioClipInfo(rec, 0, out var info);+ yield return (one, $"retry audio: one clip, at the original start (clips {AudioClips(e, rec)}, start {info.StartBeat:F3})");+ e.StopTransport();+ }++ // A loop take of several passes: none of them stays as a take lane.+ private static IEnumerable<(bool, string)> LoopPasses()+ {+ using var e = Resampling(out int rec);+ e.SetCountIn(0);+ e.SetLoop(true, 0.0, 2.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.SetRecording(true);+ Beats(e, 5.0); // two full passes and a half+ var r = e.RetryTake();+ Beats(e, 0.01);+ yield return (r == RetryTakeResult.Arrangement && e.TakeCount(rec) == 0 && AudioClips(e, rec) == 0,+ $"retry loop: no pass is kept (takes {e.TakeCount(rec)}, clips {AudioClips(e, rec)})");+ e.SetRecording(false);+ e.StopTransport();+ }++ // Session MIDI: only the recording slot is dropped; the other track's clip plays on, the+ // slot waits for the next quantum (state 5), then records; stop keeps the new take only.+ private static IEnumerable<(bool, string)> SessionMidi()+ {+ using var e = Armed(out int t);+ int d = e.AddInstrumentTrack();+ e.SetTrackBuiltinInstrument(d, 0);+ e.AddSessionMidiClip(d, 0, 4);+ e.SetSessionNotes(d, 0, new[] { new NotaNote(40, 0.0, 1.0, 0.8f) });+ e.SetLaunchQuant(4.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.LaunchSlot(d, 0);+ Beats(e, 1.0);+ e.RecordSessionSlot(t, 1);+ Beats(e, 3.5); // past the quantum at 4+ Tap(e, 60, 0.5);+ bool first = e.GetSessionNotes(t, 1).Any(n => n.Pitch == 60);++ var r = e.RetryTake();+ int pending = e.SessionSlotState(t, 1);+ yield return (first && r == RetryTakeResult.Session && pending == 5 && !e.GetSessionNotes(t, 1).Any(n => n.Pitch == 60),+ $"retry session: the slot's take is dropped and waits for the quantum ({r}, state {pending})");+ Beats(e, 0.5);+ yield return (e.SessionSlotState(d, 0) == 3 && e.IsPlaying, "retry session: the other track's clip keeps playing");+ Beats(e, 2.5); // past the quantum at 8+ yield return (e.SessionSlotState(t, 1) == 4, $"retry session: recording from the quantum (state {e.SessionSlotState(t, 1)})");+ Tap(e, 62, 0.5);+ e.StopSessionRecord();+ Beats(e, 0.1);+ var notes = e.GetSessionNotes(t, 1);+ yield return (notes.Any(n => n.Pitch == 62) && notes.All(n => n.Pitch != 60) && e.SessionSlotState(d, 0) == 3,+ $"retry session: stop keeps only the new take ({string.Join(",", notes.Select(n => n.Pitch))})");+ e.StopAllSession();+ e.StopTransport();+ }++ // Session audio: the retried take starts on the launch quantum — what came before is trimmed.+ private static IEnumerable<(bool, string)> SessionAudio()+ {+ using var e = Resampling(out int rec);+ e.SetCountIn(0);+ e.SetLaunchQuant(4.0);+ e.Seek(0.0);+ Beats(e, 0.01);+ e.Play();+ Beats(e, 0.5);+ e.RecordSessionSlot(rec, 0);+ Beats(e, 0.5); // ~beat 1+ var r = e.RetryTake();+ Beats(e, 0.01);+ int pending = e.SessionSlotState(rec, 0);+ yield return (r == RetryTakeResult.Session && pending == 5, $"retry session audio: waits for the quantum ({r}, state {pending})");+ Beats(e, 3.5); // ~beat 4.5+ int recording = e.SessionSlotState(rec, 0);+ Beats(e, 1.5); // ~beat 6+ e.StopSessionRecord();+ Beats(e, 0.05);+ int idx = e.SessionSlotToArrangement(rec, 0, 32.0);+ long frames = idx >= 0 && e.TryGetAudioClipInfo(rec, idx, out var ci) && e.TryGetSampleInfo(ci.SampleId, out var si) ? si.Frames : -1;+ double beats = frames / Spb;+ yield return (recording == 4 && Near(beats, 2.0, 0.1),+ $"retry session audio: the take starts on the quantum ({beats:F2} beats kept, state then {recording})");+ e.StopAllSession();+ e.StopTransport();+ }+}