feat(preboard): shared pre-board chain feeding every board

Add a pre-board stage: one linear pedal chain that processes the input once,
before the board split, and feeds every board — for front-of-chain gates /
drive / EQ, and multi-board "voice spray" rigs (one source → N panned boards →
Blend).

Routing: a stable mono feed bus every board taps. `FeedPassThrough` copies the
input source — or, when a pre-chain exists, that chain's mono output — onto the
feed bus (`ensureFeed`/`buildFeed`/`tearDownFeed`). The pre-chain is modeled as
an unfinalized `PedalBoard` fed from the source; a stereo tail folds to mono
(board heads are mono). Empty pre-chain = passthrough, byte-for-byte
behavior-preserving. addBoard taps the feed bus; teardown releases it
remove-before-release.

State: additive `ShoeGazeState.preChain` (`decodeIfPresent` → nil for old rigs,
no format bump; `hasSameRigContent` includes it). `captureState` reads the LIVE
pre-pedals so knob tweaks are saved; `rebuildAllBoards` sets the pre-chain
before building boards.

Edit API: appendPrePedal / insertPrePedal / removePrePedal / movePrePedal —
each folds in live knob values, then a full ordering-safe rig rebuild
(`setPreBoardChain`, mirrors setInputSource; rolls back on failure). Undo: a
pre-chain topology change (compared by id sequence, so knob-only edits stay on
the surgical path) rebuilds from the snapshot, stopping/starting the engine.
`allPedals()` now includes the pre-chain so pre-pedal knob undo resolves.

UI: an inline pre-board strip above the boards — hidden to a "+ Pre" button when
empty; otherwise the pre-pedals (keyed by stable id) with a per-pedal remove and
a "feeds all boards" divider. Palette adds route to the pre-board via a flag
(reset on any dismissal). Add / remove go through the undo wrapper.

Known scope: a pre-board edit resets transient/looper state (full rebuild, like
input-switch — setup-time); chain-router branches read the input directly and
are not fed by the pre-board. Both documented.

Tests: PreBoardChainTests (feeds boards, closed pre-Volume silences every board,
remove restores direct feed, save/load incl. a knob tweak, prior pre-pedal's
knob survives adding another, old-rig decode) + a pre-board undo test. Full
suite 844 green; both demos build. External review + caveman sweep: one blocking
(live knob sync) fixed + regression-tested, all non-blocking addressed.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-11-25 19:18:04 -08:00
parent 1f5b70edc7
commit 9dfadb129d
9 changed files with 592 additions and 28 deletions
@@ -481,4 +481,76 @@ extension ShoeGaze {
let insertionIndex: Int = destinationIndex > sourceIndex ? destinationIndex - 1 : destinationIndex
array.insert(element, at: insertionIndex)
}
// MARK: - Pre-board chain editing
/// Appends a pedal to the end of the pre-board chain — the shared stage that processes the input
/// once, before the board split, and feeds every board.
///
/// - Important: A pre-board edit reshapes the shared feed every board taps, so the whole rig is
/// torn down and rebuilt (ordering-safe). Like ``setInputSource(_:)``, this resets transient
/// live state (solo / bypass) and stateful pedals (looper buffers) — it is a setup-time edit.
/// - Note: The pre-board chain feeds the **main boards** only. Chain-router branches read the
/// input source directly and are not fed by the pre-board chain.
public func appendPrePedal(_ kind: PedalType) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePreBoardStates() // fold in live knob tweaks first
updated.append(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0))
try setPreBoardChain(updated)
}
/// Inserts a pedal at `index` in the pre-board chain (insert-before; `index == count` appends).
public func insertPrePedal(_ kind: PedalType, at index: Int) throws {
let type: String = kind.rawValue
guard PedalRegistry.builtIn[type] != nil else { throw ShoeGazeError.unknownPedalType(type) }
var updated: [PedalState] = capturePreBoardStates()
guard index >= 0 && index <= updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.insert(PedalState(type: type, knobValues: [], switchValues: [], bypass: 0.0), at: index)
try setPreBoardChain(updated)
}
/// Removes the pre-board pedal at `index`.
public func removePrePedal(at index: Int) throws {
var updated: [PedalState] = capturePreBoardStates()
guard index >= 0 && index < updated.count else {
throw ShoeGazeError.pedalIndexOutOfRange(index: index, count: updated.count)
}
updated.remove(at: index)
try setPreBoardChain(updated)
}
/// Moves the pre-board pedal at `sourceIndex` to `destinationIndex` (SwiftUI `onMove` semantics).
public func movePrePedal(from sourceIndex: Int, to destinationIndex: Int) throws {
var updated: [PedalState] = capturePreBoardStates()
try Self.moveWithinArray(&updated, from: sourceIndex, to: destinationIndex)
try setPreBoardChain(updated)
}
/// Replaces the pre-board chain with `newStates` and rebuilds the rig. The pre-chain reshapes the
/// shared feed that every board taps, so the whole rig is torn down and rebuilt (ordering-safe);
/// mirrors ``setInputSource(_:)``, resetting transient / looper state like it does. On failure the
/// previous pre-board states are restored so a later capture never persists a half-applied edit.
private func setPreBoardChain(_ newStates: [PedalState]) throws {
let previous: [PedalState] = preBoardStates
preBoardStates = newStates
let wasRunning: Bool = engine.isRunning
if wasRunning { engine.stop() }
let snapshot: ShoeGazeState = captureState().withPreChain(newStates.isEmpty ? nil : newStates)
teardown()
do {
try rebuildAllBoards(from: snapshot)
} catch {
preBoardStates = previous
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after failed pre-board edit failed: \(error)") }
}
throw error
}
if wasRunning {
do { try engine.start() } catch { print("[ShoeGaze] engine restart after pre-board edit failed: \(error)") }
}
}
}
@@ -38,7 +38,10 @@ extension ShoeGaze {
numOutputChannels: engine.numOutputChannels,
// `nil` rather than `[]` when there are no routers, so a routerless rig's JSON is
// unchanged and byte-identical to one saved before router persistence existed.
routers: routerStates.isEmpty ? nil : routerStates
routers: routerStates.isEmpty ? nil : routerStates,
// Captured from the LIVE pre-pedals (so knob tweaks are saved); `nil` rather than `[]`
// when empty, so a rig without a pre-board chain stays byte-identical to the old format.
preChain: { let s: [PedalState] = capturePreBoardStates(); return s.isEmpty ? nil : s }()
)
}
@@ -178,6 +181,9 @@ extension ShoeGaze {
/// - Throws: `BusAllocatorError`, `EngineAddError`, or `ShoeGazeError` from board construction.
func rebuildAllBoards(from snapshot: ShoeGazeState) throws {
do {
// Set the pre-board chain before building any board: the first board's input tap wires
// through the feed bus, which `ensureFeed()` builds from `preBoardStates`.
preBoardStates = snapshot.preChain ?? []
for boardState: BoardState in snapshot.boards {
let board: PedalBoard = try addBoard()
board.id = boardState.id
@@ -188,6 +194,11 @@ extension ShoeGaze {
for routerState: ChainRouterState in snapshot.routers ?? [] {
try rebuildRouter(routerState)
}
// With no boards to pull the feed into being, build the pre-chain anyway so it isn't an
// invisible accumulation of states (`preBoardPedals` reflects it; a later board taps it).
if boards.isEmpty && !preBoardStates.isEmpty {
_ = try ensureFeed()
}
} catch {
// Leave no partial rig behind: tear down whatever was built, then rethrow.
teardown()
@@ -62,6 +62,11 @@ public struct ShoeGazeState: Codable, Equatable {
/// routers — decode cleanly to `nil` without a format-version bump.
public let routers: [ChainRouterState]?
/// The rig's pre-board chain — pedals that process the input once, before the board split, and
/// feed every board — or `nil` for a rig saved before the pre-board stage existed. Additive:
/// decoded with `decodeIfPresent`, so older rigs decode cleanly to `nil` without a format bump.
public let preChain: [PedalState]?
/// Creates a rig state snapshot.
///
/// - Parameters:
@@ -83,7 +88,8 @@ public struct ShoeGazeState: Codable, Equatable {
inputSource: InputSource? = nil,
numInputChannels: Int? = nil,
numOutputChannels: Int? = nil,
routers: [ChainRouterState]? = nil
routers: [ChainRouterState]? = nil,
preChain: [PedalState]? = nil
) {
self.version = version
self.boards = boards
@@ -94,6 +100,7 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = numInputChannels
self.numOutputChannels = numOutputChannels
self.routers = routers
self.preChain = preChain
}
private enum CodingKeys: String, CodingKey {
@@ -106,6 +113,7 @@ public struct ShoeGazeState: Codable, Equatable {
case numInputChannels
case numOutputChannels
case routers
case preChain
}
/// Decodes a rig snapshot, tolerating an absent, malformed, OR legacy-format `midiMap`.
@@ -139,6 +147,7 @@ public struct ShoeGazeState: Codable, Equatable {
self.numInputChannels = try container.decodeIfPresent(Int.self, forKey: .numInputChannels)
self.numOutputChannels = try container.decodeIfPresent(Int.self, forKey: .numOutputChannels)
self.routers = try container.decodeIfPresent([ChainRouterState].self, forKey: .routers)
self.preChain = try container.decodeIfPresent([PedalState].self, forKey: .preChain)
}
/// Whether two snapshots describe the same **rig** — its boards, routers, MIDI map, and tempo —
@@ -155,5 +164,16 @@ public struct ShoeGazeState: Codable, Equatable {
&& midiMap == other.midiMap
&& bpm == other.bpm
&& tempoEnabled == other.tempoEnabled
&& preChain == other.preChain
}
/// Returns a copy of this snapshot with its `preChain` replaced. Used by the pre-board edit path
/// to force the just-mutated intended chain (rather than a re-read of the still-live pre-pedals).
public func withPreChain(_ preChain: [PedalState]?) -> ShoeGazeState {
ShoeGazeState(
version: version, boards: boards, midiMap: midiMap, bpm: bpm, tempoEnabled: tempoEnabled,
inputSource: inputSource, numInputChannels: numInputChannels,
numOutputChannels: numOutputChannels, routers: routers, preChain: preChain
)
}
}