feat(undo): multi-level structural undo/redo for rig edits

Add UndoCoordinator: 50-deep undo/redo of structural edits (add/insert/
remove/move pedals in any lane, stereo-split/parallel/merge/unzip routing,
add/remove/move boards, Clear Board). Each edit records a named checkpoint
via a perform(label:) wrapper threaded through the builder, board-flow,
board-bar, and boards-sheet views (injected through the SwiftUI environment,
re-injected onto the boards sheet).

Restore is surgical, not a whole-rig reload: it reconciles board-by-board
(remove added / re-add removed / rebuild changed / reorder) using the same
per-board rebuild path as an ordinary edit, so undo never tears the rig down
— recording, looper buffers, other boards' reverb/delay tails, and
bypass/solo state all survive. It also merges live parameter values by pedal
id, so undoing a topology edit never reverts a knob turned afterwards; a
pedal the edit removed returns with its snapshot values. No-op edits record
nothing (compared via hasSameRigContent). History clears on rig load / new /
switch.

UI: macOS Edit menu (Undo ⌘Z / Redo ⇧⌘Z with dynamic "Undo <action>" titles,
deferring to a text field's own editor while typing); iOS visible ↶/↷ buttons
+ ⌘Z/⇧⌘Z. Rig mute moves from ⌘Z to ⌘M. Help text updated.

Fix: every pedal edit rebuilt the board via BoardState(label:segments:)
without id:, regenerating the board UUID and breaking MIDI board bindings
after any edit. Thread id: board.id through all 10 rebuild sites; add
editingPreservesBoardIdentity regression test.

Tests: 12 UndoCoordinator tests (restore correctness, param preservation,
untouched-board identity, multi-board re-add, depth cap, no-op, throwing
action). Full suite 830 green; both demo schemes build (macOS + iPad).

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 10:22:51 -08:00
parent 4c09825c2e
commit a8bd0242a3
14 changed files with 924 additions and 69 deletions
@@ -382,6 +382,25 @@ struct BoardEditAPITests {
#expect(edited.width == 2, "board should remain stereo")
}
// MARK: - Board identity is stable across edits
@Test func editingPreservesBoardIdentity() throws {
let (sg, _, url, board): (ShoeGaze, SynthesisEngine, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// MIDI bindings address a board by its `id`; a pedal edit rebuilds the board and must keep it.
let originalID: UUID = board.id
let afterAppend: PedalBoard = try sg.appendPedal(.reverb, to: board)
#expect(afterAppend.id == originalID, "append must not regenerate the board id")
let afterMove: PedalBoard = try sg.movePedal(from: 0, to: 2, in: afterAppend)
#expect(afterMove.id == originalID, "move must not regenerate the board id")
let afterRemove: PedalBoard = try sg.removePedal(at: 0, from: afterMove)
#expect(afterRemove.id == originalID, "remove must not regenerate the board id")
}
// MARK: - Input source switching
@Test func setInputSourcePreservesRigAndRewiresInput() throws {
@@ -0,0 +1,305 @@
// UndoCoordinatorTests.swift
// Lyrebird
//
// Copyright (c) 2026 Joshua Parmenter / realizedsound
// SPDX-License-Identifier: MIT
import Testing
import Foundation
import LyrebirdSynth
import LyrebirdUI
@testable import LyrebirdShoeGaze
@MainActor
@Suite("Undo coordinator")
struct UndoCoordinatorTests {
/// Builds an NRT-backed `ShoeGaze` with a single finalized board of the given pedal types, plus a
/// coordinator bound to it.
private func makeRig(
pedals: [String],
depth: Int = UndoCoordinator.defaultDepth,
numAudioBuses: Int = 128,
duration: Double = 0.05
) throws -> (ShoeGaze, UndoCoordinator, URL, PedalBoard) {
let (engine, url): (SynthesisEngine, URL) = makeNRTEngine(
duration: duration,
numAudioBuses: numAudioBuses
)
let sg: ShoeGaze = ShoeGaze(engine: engine)
let board: PedalBoard = try sg.addBoard()
for type: String in pedals {
guard let pedal: Pedal = PedalRegistry.makePedal(type: type) else { continue }
try board.add(pedal)
}
try sg.finalizeBoard(board)
let undo: UndoCoordinator = UndoCoordinator(shoeGaze: sg, depth: depth)
return (sg, undo, url, board)
}
/// Current pedal display names on the rig's first board (read from the live `boards` array, since
/// an undo/redo restore replaces board instances wholesale).
private func names(_ sg: ShoeGaze) -> [String] {
guard let board: PedalBoard = sg.boards.first else { return [] }
return board.pedals.map { $0.displayName }
}
// MARK: - Undo / redo of an add
@Test func undoRemovesAnAddedPedalAndRedoBringsItBack() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
#expect(undo.canUndo == false)
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
#expect(names(sg) == ["Overdrive", "Delay", "Reverb"])
#expect(undo.canUndo == true)
#expect(undo.undoActionLabel == "Add Reverb")
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay"], "undo should remove the added pedal")
#expect(undo.canUndo == false)
#expect(undo.canRedo == true)
#expect(undo.redoActionLabel == "Add Reverb")
undo.redo()
#expect(names(sg) == ["Overdrive", "Delay", "Reverb"], "redo should re-add the pedal")
#expect(undo.canUndo == true)
#expect(undo.canRedo == false)
}
// MARK: - Undo of a remove restores parameter values
@Test func undoOfARemoveRestoresThePedalWithItsKnobValues() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// Give the Delay a distinctive first-knob value well inside its range.
let delay: Pedal = board.pedals[1]
let knobRange: ClosedRange<Double> = try #require(delay.knobs.first?.range)
let sentinel: Double = knobRange.lowerBound + (knobRange.upperBound - knobRange.lowerBound) * 0.37
let original: PedalState = delay.captureState()
var newKnobs: [Double] = original.knobValues
try #require(!newKnobs.isEmpty)
newKnobs[0] = sentinel
delay.applyState(
PedalState(
type: original.type,
knobValues: newKnobs,
switchValues: original.switchValues,
bypass: original.bypass
)
)
#expect(abs(board.pedals[1].captureState().knobValues[0] - sentinel) < 1e-9)
try undo.perform("Remove Delay") { try sg.removePedal(at: 1, from: board) }
#expect(names(sg) == ["Overdrive"])
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay"], "undo should bring the removed pedal back")
let restored: Double = try #require(sg.boards.first?.pedals[1].captureState().knobValues.first)
#expect(abs(restored - sentinel) < 1e-9, "the restored pedal should keep its knob value")
}
// MARK: - Undo of a move
@Test func undoReversesAMove() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay", "Reverb"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Move pedal") { try sg.movePedal(from: 0, to: 3, in: board) }
#expect(names(sg) == ["Delay", "Reverb", "Overdrive"])
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay", "Reverb"], "undo should restore the original order")
}
// MARK: - No-op edits record nothing
@Test func aNoOpEditRecordsNoUndoCheckpoint() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
// Moving index 0 to offset 0 leaves the chain unchanged.
try undo.perform("Move pedal") { try sg.movePedal(from: 0, to: 0, in: board) }
#expect(undo.canUndo == false, "a no-op edit should not create an undo entry")
}
// MARK: - A new edit clears the redo stack
@Test func aNewEditClearsRedo() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
undo.undo()
#expect(undo.canRedo == true)
let liveBoard: PedalBoard = try #require(sg.boards.first)
try undo.perform("Add Delay") { try sg.appendPedal(.delay, to: liveBoard) }
#expect(undo.canRedo == false, "a fresh edit should discard the redo stack")
#expect(names(sg) == ["Overdrive", "Delay"])
}
// MARK: - Board-level ops
@Test func undoReversesABoardRemoval() throws {
let (sg, undo, url, _): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
let second: PedalBoard = try sg.addBoard()
try sg.finalizeBoard(second)
#expect(sg.boards.count == 2)
undo.perform("Remove Board") { sg.removeBoard(second) }
#expect(sg.boards.count == 1)
undo.undo()
#expect(sg.boards.count == 2, "undo should restore the removed board")
}
// MARK: - Depth cap
@Test func depthCapDropsOldestHistory() throws {
let cap: Int = 3
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"], depth: cap)
defer { try? FileManager.default.removeItem(at: url) }
// Five successive appends; only the last `cap` remain undoable.
let types: [PedalType] = [.reverb, .delay, .tremolo, .chorus, .flanger]
var current: PedalBoard = board
for type: PedalType in types {
try undo.perform("Add \(type.rawValue)") { try sg.appendPedal(type, to: current) }
current = try #require(sg.boards.first)
}
#expect(names(sg).count == 6)
// Undo exactly `cap` times — all that history holds.
for _ in 0 ..< cap { undo.undo() }
#expect(undo.canUndo == false, "history beyond the depth cap should have been dropped")
// Three undone appends leaves the two oldest adds (reverb, delay) plus the seed Overdrive.
#expect(names(sg) == ["Overdrive", "Reverb", "Delay"])
}
// MARK: - Clear
// MARK: - Undo preserves parameter edits made after the checkpoint
@Test func undoOfAnAddKeepsALaterKnobEditOnASurvivingPedal() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
// AFTER the add, the player turns the Delay's first knob. Undoing the add must not revert it.
let liveBoard: PedalBoard = try #require(sg.boards.first)
let delay: Pedal = liveBoard.pedals[1]
let knobRange: ClosedRange<Double> = try #require(delay.knobs.first?.range)
let sentinel: Double = knobRange.lowerBound + (knobRange.upperBound - knobRange.lowerBound) * 0.42
let delayState: PedalState = delay.captureState()
var newKnobs: [Double] = delayState.knobValues
try #require(!newKnobs.isEmpty)
newKnobs[0] = sentinel
delay.applyState(
PedalState(
id: delayState.id, // keep the pedal's identity, as a real knob turn (via the node) would
type: delayState.type,
knobValues: newKnobs,
switchValues: delayState.switchValues,
bypass: delayState.bypass
)
)
undo.undo()
#expect(names(sg) == ["Overdrive", "Delay"], "undo removes the added Reverb")
let delayKnob: Double = try #require(sg.boards.first?.pedals[1].captureState().knobValues.first)
#expect(abs(delayKnob - sentinel) < 1e-9, "a knob turned after the edit must survive the undo")
}
// MARK: - Undo is surgical (does not tear down untouched boards)
@Test func undoOfAnEditLeavesOtherBoardsUntouched() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
let secondBoard: PedalBoard = try sg.addBoard()
try secondBoard.add(DelayPedal())
try sg.finalizeBoard(secondBoard)
let secondBoardInstance: PedalBoard = try #require(sg.boards.last)
// Edit the FIRST board, then undo it.
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
undo.undo()
// A whole-rig teardown would rebuild every board; the surgical restore must leave the
// untouched second board as the very same instance.
#expect(sg.boards.last === secondBoardInstance, "an unrelated board must not be rebuilt by undo")
#expect(names(sg) == ["Overdrive"], "the edited board is restored")
}
// MARK: - Undo of a multi-board wipe re-adds every board
@Test func undoOfAClearStyleWipeReAddsAllBoards() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive", "Delay"])
defer { try? FileManager.default.removeItem(at: url) }
let second: PedalBoard = try sg.addBoard()
try second.add(ReverbPedal())
try sg.finalizeBoard(second)
#expect(sg.boards.count == 2)
_ = board
// A Clear-style wipe: remove every board, seed one empty board — as one checkpoint.
undo.perform("Clear Board") {
for existing: PedalBoard in Array(sg.boards) { sg.removeBoard(existing) }
if let fresh: PedalBoard = try? sg.addBoard() {
try? sg.finalizeBoard(fresh)
}
}
#expect(sg.boards.count == 1)
#expect(names(sg) == [], "the seeded board is empty")
undo.undo()
#expect(sg.boards.count == 2, "undo re-adds every wiped board")
#expect(names(sg) == ["Overdrive", "Delay"], "first board restored with its pedals")
#expect(sg.boards.last?.pedals.map { $0.displayName } == ["Reverb"], "second board restored too")
}
// MARK: - A throwing action records nothing
@Test func aThrowingActionRecordsNoCheckpoint() throws {
let (_, undo, url, _): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
struct EditFailure: Error {}
#expect(throws: EditFailure.self) {
try undo.perform("Doomed Edit") { throw EditFailure() }
}
#expect(undo.canUndo == false, "a throwing edit must not create an undo entry")
}
@Test func clearDiscardsAllHistory() throws {
let (sg, undo, url, board): (ShoeGaze, UndoCoordinator, URL, PedalBoard) =
try makeRig(pedals: ["Overdrive"])
defer { try? FileManager.default.removeItem(at: url) }
try undo.perform("Add Reverb") { try sg.appendPedal(.reverb, to: board) }
undo.undo()
#expect(undo.canRedo == true)
undo.clear()
#expect(undo.canUndo == false)
#expect(undo.canRedo == false)
#expect(undo.undoActionLabel == nil)
#expect(undo.redoActionLabel == nil)
}
}