Persist I/O + input via the rig, not UserDefaults

The rig snapshot already stores inputSource + input/output channel counts and
syncs them via the autosave envelope and the iCloud rig library. Make that the
single source of truth instead of the parallel UserDefaults path.

- RigStore.restore applies the saved channel layout (applyChannelLayout) before
  loadRig, while stopped at launch, so a saved live-input channel validates
  against the restored count instead of falling back to the test loop. The
  general loadRig policy (don't force layout mid-session) is unchanged.
- applyInputSource and the engine-config onConfigApplied now autosave, so input
  and I/O changes are captured into the rig immediately.
- Remove the UserDefaults keys and read/write sites: ShoeGaze.inputSelection
  (builder view + iOS model) and the ShoeGaze.inputChannels/outputChannels keys
  added earlier (EngineConfigView + both app targets build at the default layout
  now; RigStore.restore supplies the rig's layout).
- Fresh-launch default: the seed paths set inputSource = liveInput(0) when the
  engine has an input channel, so a first launch listens to the instrument. A
  restored rig keeps its own saved input; the view's on-appear hook only requests
  mic access for a restored live selection (test-loop fallback on denial).

Test: RigStore.restoreAppliesSavedChannelLayoutAndInput. 461 tests pass; both
app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-11 15:34:23 -07:00
parent 5987ec7b78
commit cc3a986cde
7 changed files with 121 additions and 133 deletions
+9 -34
View File
@@ -33,26 +33,6 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
private static let inputChannels: Int = 1
private static let numAudioBuses: Int = 256
/// UserDefaults keys persisting the last-used engine channel counts. Must match the keys
/// written by the builder's engine-config UI (`EngineConfigView.inputChannelsDefaultsKey` /
/// `outputChannelsDefaultsKey`) so the choice survives relaunch.
private static let inputChannelsDefaultsKey: String = "ShoeGaze.inputChannels"
private static let outputChannelsDefaultsKey: String = "ShoeGaze.outputChannels"
/// Reads a persisted channel count, clamped to `[minimum, 8]`, falling back to `fallback` when
/// no value has been saved yet.
private static func persistedChannelCount(
forKey key: String,
fallback: Int,
minimum: Int
) -> Int {
let defaults: UserDefaults = UserDefaults.standard
guard defaults.object(forKey: key) != nil else { return fallback }
let stored: Int = defaults.integer(forKey: key)
let maximumChannels: Int = 8
return max(minimum, min(stored, maximumChannels))
}
// MARK: - Window geometry constants
private static let windowWidth: CGFloat = 1_400
@@ -115,23 +95,13 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
override init() {
let coreDriver: CoreAudioDriver = CoreAudioDriver()
// Seed I/O from the last-used counts so a multi-input/output setup survives relaunch (and a
// saved live-input channel stays valid). Falls back to the built-in defaults on first launch.
let restoredOutputs: Int = AppDelegate.persistedChannelCount(
forKey: AppDelegate.outputChannelsDefaultsKey,
fallback: AppDelegate.outputChannels,
minimum: 1
)
let restoredInputs: Int = AppDelegate.persistedChannelCount(
forKey: AppDelegate.inputChannelsDefaultsKey,
fallback: AppDelegate.inputChannels,
minimum: 0
)
// The engine is built with the default layout; the autosaved rig's saved I/O layout (if any)
// is applied by `RigStore.restore` below, so a multi-channel setup survives relaunch.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: AppDelegate.blockSize,
sampleRate: AppDelegate.sampleRate,
numOutputChannels: restoredOutputs,
numInputChannels: restoredInputs,
numOutputChannels: AppDelegate.outputChannels,
numInputChannels: AppDelegate.inputChannels,
numAudioBuses: AppDelegate.numAudioBuses,
driver: coreDriver
)
@@ -159,6 +129,11 @@ final class AppDelegate: NSObject, NSApplicationDelegate, NSMenuDelegate {
/// Seeds one board with a single pedal so the builder opens with an audible starting point.
private static func seedInitialBoard(into shoeGaze: ShoeGaze) {
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio,
// so the app comes up listening to the instrument. A restored rig keeps its own saved input.
if shoeGaze.engine.numInputChannels > 0 {
shoeGaze.inputSource = .liveInput(channel: 0)
}
var created: PedalBoard?
do {
let board: PedalBoard = try shoeGaze.addBoard()
@@ -34,15 +34,6 @@ final class ShoeGazeBuilderiOSAppModel {
private static let numAudioBuses: Int = 256
private static let seedPedalType: PedalType = .overdrive
/// UserDefaults key persisting the input selection. Must match the key written by the
/// builder view (`ShoeGazeBuilderView.inputSelectionDefaultsKey`).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// UserDefaults key persisting the last-used output-channel count. Must match the key written by
/// the builder's engine-config UI (`EngineConfigView.outputChannelsDefaultsKey`).
private static let outputChannelsDefaultsKey: String = "ShoeGaze.outputChannels"
/// Persisted value meaning "live input, channel 0".
private static let liveInputChannelZeroTag: Int = 0
// MARK: - Owned objects
/// The active ShoeGaze builder session. Swapped out when live input is enabled (the engine
@@ -147,17 +138,12 @@ final class ShoeGazeBuilderiOSAppModel {
) -> (engine: SynthesisEngine, driver: iOSAudioDriver, shoeGaze: ShoeGaze) {
let sampleRate: Double = AVAudioSession.sharedInstance().sampleRate
let driver: iOSAudioDriver = iOSAudioDriver()
// Restore the last-used output count so it survives relaunch (input stays on the
// permission-gated rebuild flow). Falls back to the default on first launch.
let defaults: UserDefaults = UserDefaults.standard
let maximumChannels: Int = 8
let restoredOutputs: Int = defaults.object(forKey: outputChannelsDefaultsKey) != nil
? max(1, min(defaults.integer(forKey: outputChannelsDefaultsKey), maximumChannels))
: ShoeGazeBuilderiOSAppModel.outputChannels
// The engine is built with the default layout; the autosaved rig's saved I/O (if any) is
// applied by `RigStore.restore`, so an output change survives relaunch.
let engine: SynthesisEngine = SynthesisEngine(
blockSize: ShoeGazeBuilderiOSAppModel.blockSize,
sampleRate: sampleRate,
numOutputChannels: restoredOutputs,
numOutputChannels: ShoeGazeBuilderiOSAppModel.outputChannels,
numInputChannels: inputChannels,
numAudioBuses: ShoeGazeBuilderiOSAppModel.numAudioBuses,
driver: driver
@@ -232,14 +218,12 @@ final class ShoeGazeBuilderiOSAppModel {
if wasRunning { try? engine.start() }
}
/// Selects live input on channel 0 and persists the choice for restore-on-relaunch.
/// Selects live input on channel 0 and autosaves so the rig (the source of truth for the input
/// selection) records it for restore-on-relaunch.
private func selectLiveInputAndPersist() {
do {
try shoeGaze.setInputSource(.liveInput(channel: 0))
UserDefaults.standard.set(
ShoeGazeBuilderiOSAppModel.liveInputChannelZeroTag,
forKey: ShoeGazeBuilderiOSAppModel.inputSelectionDefaultsKey
)
save()
} catch {
print("[ShoeGazeBuilderiOS] selecting live input failed: \(error)")
}
@@ -247,6 +231,11 @@ final class ShoeGazeBuilderiOSAppModel {
/// Seeds a single default board so the rig is never empty after a failed restore.
private static func seedFallbackBoard(into shoeGaze: ShoeGaze) {
// Fresh launch (no autosaved rig): default to live In 0 rather than the test-loop arpeggio.
// A restored rig keeps its own saved input selection.
if shoeGaze.engine.numInputChannels > 0 {
shoeGaze.inputSource = .liveInput(channel: 0)
}
do {
let board: PedalBoard = try shoeGaze.addBoard()
board.label = "Board 1"
@@ -85,15 +85,29 @@ public enum RigStore {
do {
let data: Data = try Data(contentsOf: url)
let decoder: JSONDecoder = JSONDecoder()
let state: ShoeGazeState
let rigID: UUID?
if let envelope: AutosaveEnvelope = try? decoder.decode(AutosaveEnvelope.self, from: data) {
try shoeGaze.loadRig(from: envelope.state)
shoeGaze.currentRigID = envelope.currentRigID
state = envelope.state
rigID = envelope.currentRigID
} else {
// Pre-envelope autosave: a bare ShoeGazeState with no recorded source rig.
let state: ShoeGazeState = try decoder.decode(ShoeGazeState.self, from: data)
try shoeGaze.loadRig(from: state)
shoeGaze.currentRigID = nil
state = try decoder.decode(ShoeGazeState.self, from: data)
rigID = nil
}
// Unlike a mid-session rig load — where forcing the layout would fight the global engine
// config and the iOS enable-live-input flow — a launch restore SHOULD reinstate the
// rig's saved I/O layout so a multi-channel setup (and a saved live-input channel)
// survives relaunch. Apply it first, while the engine is stopped, so `loadRig`'s
// input-channel validation runs against the restored count. A failure here is
// non-fatal — fall through to `loadRig`, which still rebuilds the boards.
do {
try shoeGaze.applyChannelLayout(from: state)
} catch {
print("[RigStore] channel-layout restore failed (continuing): \(error)")
}
try shoeGaze.loadRig(from: state)
shoeGaze.currentRigID = rigID
return !shoeGaze.boards.isEmpty
} catch {
print("[RigStore] restore failed: \(error)")
@@ -31,10 +31,6 @@ public struct EngineConfigView: View {
/// Channel-count stepper bounds.
private static let maxInputs: Int = 8
private static let maxOutputs: Int = 8
/// UserDefaults keys persisting the last-used engine channel counts so they survive relaunch.
/// The app targets read these when constructing the engine (fallback to their own defaults).
static let inputChannelsDefaultsKey: String = "ShoeGaze.inputChannels"
static let outputChannelsDefaultsKey: String = "ShoeGaze.outputChannels"
/// Sample-rate comparison tolerance in Hz.
private static let rateEpsilon: Double = 0.5
private static let rowSpacing: CGFloat = 12
@@ -166,21 +162,12 @@ public struct EngineConfigView: View {
outputChannels: pendingOutputs
)
}
persistChannelCounts()
onConfigApplied()
} catch {
print("[EngineConfigView] live reconfigure failed: \(error)")
}
}
/// Persists the current channel counts so the next launch rebuilds the engine with the same
/// I/O. Read by the app targets at engine-construction time.
private func persistChannelCounts() {
let defaults: UserDefaults = UserDefaults.standard
defaults.set(pendingInputs, forKey: EngineConfigView.inputChannelsDefaultsKey)
defaults.set(pendingOutputs, forKey: EngineConfigView.outputChannelsDefaultsKey)
}
private func label(_ text: String) -> some View {
Text(text)
.font(.subheadline)
@@ -205,7 +192,6 @@ public struct EngineConfigView: View {
outputChannels: pendingOutputs
)
}
persistChannelCounts()
}
try shoeGaze.engine.start()
} catch {
@@ -59,8 +59,6 @@ public struct ShoeGazeBuilderView: View {
private static let backgroundGreen: Double = 0.07
private static let backgroundBlue: Double = 0.06
private static let testLoopTag: Int = -1
/// UserDefaults key persisting the last input selection (`-1` = test loop, `>= 0` = channel).
private static let inputSelectionDefaultsKey: String = "ShoeGaze.inputSelection"
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
private static let maxCrossfadeSeconds: Double = 10.0
/// Highest board reachable via a ⌘-number switch shortcut.
@@ -745,7 +743,7 @@ public struct ShoeGazeBuilderView: View {
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() },
onConfigApplied: { transportTick.toggle(); autosave() },
transportOnly: true
)
#if !os(macOS)
@@ -892,7 +890,7 @@ public struct ShoeGazeBuilderView: View {
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() }
onConfigApplied: { transportTick.toggle(); autosave() }
)
Divider().overlay(Color.white.opacity(ShoeGazeBuilderView.dividerOpacity))
@@ -1122,7 +1120,7 @@ public struct ShoeGazeBuilderView: View {
EngineConfigView(
shoeGaze: shoeGaze,
hardwareSampleRate: hardwareSampleRate,
onConfigApplied: { transportTick.toggle() }
onConfigApplied: { transportTick.toggle(); autosave() }
)
}
.frame(height: TempoView.enabledHeight)
@@ -1370,7 +1368,7 @@ public struct ShoeGazeBuilderView: View {
if wasRunning { shoeGaze.engine.stop() }
do {
try shoeGaze.setInputSource(source)
persistInputSelection(source)
autosave() // the rig is the source of truth for the input selection; record it now
} catch {
print("[ShoeGazeBuilderView] setInputSource failed: \(error)")
}
@@ -1380,49 +1378,26 @@ public struct ShoeGazeBuilderView: View {
transportTick.toggle()
}
// MARK: - Input persistence
// MARK: - Input restore
/// Saves the current input choice so it is restored on the next launch.
private func persistInputSelection(_ source: InputSource) {
let value: Int
switch source {
case .testLoop:
value = ShoeGazeBuilderView.testLoopTag
case .liveInput(let channel):
value = channel
}
UserDefaults.standard.set(value, forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
}
/// Restores the saved input choice once on appear. With no saved choice, defaults to live
/// input when the microphone is already authorised and the engine has an input channel —
/// otherwise stays on the test loop. A saved live channel that no longer fits the engine, or
/// a since-revoked permission, falls back to the test loop via `switchInput(to:)`.
/// Reconciles the microphone permission with the input source the rig already restored.
///
/// The rig (autosave envelope / library entry) is the single source of truth for the input
/// selection — `RigStore.restore` / `loadRig` set `shoeGaze.inputSource` before this view
/// appears, and a fresh-launch seed defaults it to live In 0. This runs once on appear only to
/// make a restored live-input selection actually audible: it requests mic access (surfacing the
/// prompt at launch rather than at the first Start) and falls back to the test loop on denial.
/// A restored test-loop selection is honoured untouched.
private func restoreInputSelection() {
guard !didRestoreInput else { return }
didRestoreInput = true
let defaults: UserDefaults = UserDefaults.standard
if defaults.object(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey) != nil {
let stored: Int = defaults.integer(forKey: ShoeGazeBuilderView.inputSelectionDefaultsKey)
if stored >= 0, stored < shoeGaze.engine.numInputChannels {
switchInput(to: .liveInput(channel: stored))
} else if stored >= 0, shoeGaze.engine.numInputChannels == 0,
MicrophonePermission.isAuthorized, let onEnableLiveInput {
// iOS: a live choice was saved and the mic is already authorised — rebuild the
// engine with an input channel silently (no prompt, since access is granted).
onEnableLiveInput()
guard case .liveInput = shoeGaze.inputSource else { return }
MicrophonePermission.request { granted in
if !granted {
showMicDeniedAlert = true
applyInputSource(.testLoop)
}
// A test-loop choice (or live with no host hook / no permission) leaves the test loop.
} else if shoeGaze.engine.numInputChannels > 0 {
// First launch, no saved choice → default to live input In 0 rather than the test-loop
// arpeggio. `switchInput` requests mic access and falls back to the test loop on denial.
switchInput(to: .liveInput(channel: 0))
} else if let onEnableLiveInput, MicrophonePermission.isAuthorized {
// iOS first launch with no input channel yet but mic already granted → rebuild with a
// live input silently. (Undetermined permission stays on the test loop to avoid an
// unprompted rebuild; the user can enable live input explicitly.)
onEnableLiveInput()
}
}
@@ -83,6 +83,41 @@ struct RigStoreTests {
#expect(b.currentRigID == rigID, "restore must carry the source-rig id so the UI highlights it")
}
/// A launch restore reinstates the rig's saved I/O layout so a multi-channel setup survives
/// relaunch, and a saved live-input channel that only fits the wider layout stays selected
/// (rather than falling back to the test loop against the fresh engine's default count).
@Test func restoreAppliesSavedChannelLayoutAndInput() throws {
let autosave: URL = try isolateAutosave()
defer {
RigStore.autosaveURLOverride = nil
try? FileManager.default.removeItem(at: autosave.deletingLastPathComponent())
}
RigStore.clear()
// Save a rig on a 2-in / 2-out engine with live input on channel 1.
let (engineA, urlA): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05, numOutputChannels: 2, numInputChannels: 2, numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: urlA) }
let a: ShoeGaze = ShoeGaze(engine: engineA, inputSource: .liveInput(channel: 1))
let board: PedalBoard = try a.addBoard()
try a.appendPedal(.overdrive, to: board)
try a.finalizeBoard(board)
#expect(RigStore.save(a))
// Restore into a fresh engine built with the default single input channel.
let (engineB, urlB): (SynthesisEngine, URL) = makeNRTEngine(
duration: 0.05, numOutputChannels: 2, numInputChannels: 1, numAudioBuses: 64
)
defer { try? FileManager.default.removeItem(at: urlB) }
let b: ShoeGaze = ShoeGaze(engine: engineB)
#expect(RigStore.restore(into: b))
#expect(b.engine.numInputChannels == 2, "restore must reapply the rig's saved input count")
#expect(b.inputSource == .liveInput(channel: 1),
"the saved live-input channel must survive because the layout was restored first")
}
@Test func restoreReturnsFalseWhenNoAutosave() throws {
let autosave: URL = try isolateAutosave()
defer {
@@ -45,25 +45,39 @@ call `engine.start()` directly and are unaffected — they preserve the current
mic access and selects `.liveInput(channel: 0)` (falling back to test loop on denial / no
input), instead of only auto-selecting when already authorised.
## (b) Persist In/Out channel counts (+ reliable last-input)
## (b) Persist In/Out + input via the rig (iCloud), not UserDefaults
The last-used input **selection** already persists (`ShoeGaze.inputSelection`), but the
engine's **channel counts** do not — so on relaunch the engine reverts to the app default
(1 in / 2 out). A saved input channel `>=` the smaller default count then fails validation
and silently falls back to the test loop. That is the "In doesn't persist" bug.
The rig snapshot (`ShoeGazeState`) **already** persists `inputSource`, `numInputChannels`,
and `numOutputChannels`, and the autosave envelope + rig library (iCloud) already carry
them. Two problems remained:
Fix: persist the channel counts too.
1. `loadRig(from:)` deliberately does **not** apply the saved channel layout (forcing it on
every mid-session load would fight the global engine config / the iOS live-input rebuild).
So at **launch**, the engine kept the app default (1 in / 2 out); a saved live-input
channel `>=` that count failed validation and fell back to the test loop — the "In
doesn't persist" bug.
2. A **second, competing** persistence path (`ShoeGazeBuilderView`'s UserDefaults
`ShoeGaze.inputSelection`, plus the iOS model's copy) fought the rig's own `inputSource`.
- WRITE: `EngineConfigView` persists `pendingInputs` / `pendingOutputs` to UserDefaults
(`ShoeGaze.inputChannels` / `ShoeGaze.outputChannels`) whenever they change while stopped.
- READ/APPLY at launch, where the engine is actually constructed:
- macOS `AppDelegate`: seed `numInputChannels` / `numOutputChannels` from the saved values
(fallback 1 / 2).
- iOS `ShoeGazeBuilderiOSAppModel`: seed `numOutputChannels` from saved (fallback 2). Input
stays on the existing permission-gated rebuild flow.
Fix — make the rig the single source of truth:
Key strings are duplicated in the app targets with a "must match" comment, matching the
existing convention for `inputSelectionDefaultsKey`.
- **Launch applies the saved layout.** `RigStore.restore` calls
`applyChannelLayout(from: state)` **before** `loadRig`, while the engine is stopped, so the
input-channel validation runs against the restored count. A launch restore is exactly the
place this is wanted (unlike a mid-session load), so the general `loadRig` policy is
unchanged.
- **Input changes autosave.** `applyInputSource` / the engine-config `onConfigApplied` call
`autosave()`, so a changed input or I/O layout is captured into the rig immediately.
- **Removed both UserDefaults paths.** The `ShoeGaze.inputSelection` / `ShoeGaze.inputChannels`
/ `ShoeGaze.outputChannels` keys and their read/write sites (view + both app targets) are
deleted. The app targets build the engine at the default layout; `RigStore.restore` supplies
the rig's layout.
- **Fresh-launch default.** When there is no autosaved rig, the seed paths
(`AppDelegate.seedInitialBoard` / iOS `seedFallbackBoard`) set `inputSource = .liveInput(0)`
when the engine has an input channel, so a first launch listens to the instrument rather
than the test loop. A restored rig keeps its own saved input. The builder view's on-appear
hook now only requests mic access for a restored live-input selection (falling back to the
test loop on denial).
## Tests