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
@@ -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()
}
}