Persist the source rig id inside the autosave; single source of truth

The rig-highlight/graph mismatch kept returning because the highlight (a
UserDefault) and the working graph (the autosave file) were two separate stores
that could diverge — and once an earlier build failed to load and autosaved a
fallback Default over the real graph, the divergence was permanent.

Fix the class of bug: the loaded rig's id now lives on ShoeGaze.currentRigID and
is written *inside* the autosave envelope alongside the graph (one atomic file).
RigStore.restore sets it from the envelope (nil for pre-envelope files or a
fallback seed); the sidebar highlight reads it directly. The separate
UserDefault key, restoreCurrentRig, and persistCurrentRigID are removed. When
the app falls back to seeding Default, no rig is highlighted — honest, and it
can never mislabel the graph again.

339 tests pass; both app targets build.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-07-01 17:11:20 -07:00
parent bab4fdd087
commit d4664b3c1f
4 changed files with 51 additions and 49 deletions
@@ -32,12 +32,26 @@ public enum RigStore {
return dir.appendingPathComponent(fileName)
}
/// Writes the rig's current state to the autosave file. Returns `false` on any failure.
/// The autosave file payload: the working graph plus the id of the rig-library entry it derives
/// from, written together so the two can never drift apart.
private struct AutosaveEnvelope: Codable {
let currentRigID: UUID?
let state: ShoeGazeState
}
/// Writes the rig's current state — plus its source-rig id (``ShoeGaze/currentRigID``) — to the
/// autosave file. Returns `false` on any failure.
@discardableResult
public static func save(_ shoeGaze: ShoeGaze) -> Bool {
guard let url: URL = autosaveURL else { return false }
do {
let data: Data = try shoeGaze.rigData()
let envelope: AutosaveEnvelope = AutosaveEnvelope(
currentRigID: shoeGaze.currentRigID,
state: shoeGaze.captureState()
)
let encoder: JSONEncoder = JSONEncoder()
encoder.outputFormatting = [.prettyPrinted, .sortedKeys]
let data: Data = try encoder.encode(envelope)
try data.write(to: url, options: .atomic)
return true
} catch {
@@ -46,7 +60,11 @@ public enum RigStore {
}
}
/// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet.
/// Restores a previously autosaved rig into `shoeGaze`, which should have no boards yet, and sets
/// ``ShoeGaze/currentRigID`` from the envelope so the highlight matches the restored graph.
///
/// Decodes the current envelope format; falls back to a bare `ShoeGazeState` (pre-envelope
/// autosaves), in which case `currentRigID` is left `nil`.
///
/// - Returns: `true` if an autosave existed and produced at least one board; `false` if there
/// was nothing to restore or the load failed (in which case the caller should seed a default).
@@ -56,7 +74,16 @@ public enum RigStore {
FileManager.default.fileExists(atPath: url.path) else { return false }
do {
let data: Data = try Data(contentsOf: url)
try shoeGaze.loadRig(from: data)
let decoder: JSONDecoder = JSONDecoder()
if let envelope: AutosaveEnvelope = try? decoder.decode(AutosaveEnvelope.self, from: data) {
try shoeGaze.loadRig(from: envelope.state)
shoeGaze.currentRigID = 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
}
return !shoeGaze.boards.isEmpty
} catch {
print("[RigStore] restore failed: \(error)")
+6
View File
@@ -71,6 +71,12 @@ public final class ShoeGaze {
/// Read and mutated by `MIDIController`; survives an input-source switch (same rig).
public var midiMap: MIDIMap?
/// The id of the rig-library entry this working session derives from, or `nil` for an unsaved
/// session. Session provenance only — NOT part of a saved/exported rig; it is written into the
/// autosave envelope (see `RigStore`) alongside the graph so the sidebar highlight and the
/// restored graph can never diverge. The UI mirrors this into the rig-library selection.
public var currentRigID: UUID?
// MARK: - Recording state
/// The folder into which `startRecording()` writes timestamped WAV files.
@@ -43,10 +43,9 @@ public enum RigLibraryBootstrap {
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
do {
try store.save(entry)
UserDefaults.standard.set(
entry.id.uuidString,
forKey: ShoeGazeBuilderView.currentRigDefaultsKey
)
// The seeded entry was captured from the working graph, so it is the session's source
// rig — record it so the sidebar highlights it and the autosave envelope carries it.
shoeGaze.currentRigID = entry.id
} catch {
print("[RigLibraryBootstrap] seeding library failed: \(error)")
}
@@ -56,9 +56,6 @@ public struct ShoeGazeBuilderView: View {
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"
/// UserDefaults key persisting the loaded rig's id (its `uuidString`) so the same rig can be
/// highlighted on the next launch. Read by the app shells to seed `initialRigID`.
public static let currentRigDefaultsKey: String = "ShoeGaze.currentRigID"
/// Maximum crossfade duration honoured by board-switch keyboard shortcuts.
private static let maxCrossfadeSeconds: Double = 10.0
/// Highest board reachable via a ⌘-number switch shortcut.
@@ -116,10 +113,14 @@ public struct ShoeGazeBuilderView: View {
/// The library entry currently loaded into the session, or `nil` for an unsaved/new rig. Drives
/// the sidebar highlight and decides whether Save overwrites or prompts for a name.
@State private var currentRigID: UUID?
/// Guards the one-time `currentRigID` seed from `initialRigID` on appear.
@State private var didRestoreRig: Bool = false
///
/// Backed by ``ShoeGaze/currentRigID`` (the single source of truth), so it is persisted inside
/// the autosave envelope together with the graph and restored consistently — the highlight can
/// never drift from the loaded rig. `@Observable` drives sidebar updates when it changes.
private var currentRigID: UUID? {
get { shoeGaze.currentRigID }
nonmutating set { shoeGaze.currentRigID = newValue }
}
/// Drives the shared rig-name entry alert (New / Save As / Rename / Duplicate).
@State private var namePrompt: RigNamePrompt?
@@ -220,17 +221,14 @@ public struct ShoeGazeBuilderView: View {
.background(boardSwitchShortcuts)
.onAppear {
restoreInputSelection()
restoreCurrentRig()
syncIdleTimer()
maybeWarnICloudUnavailable()
}
.onDisappear { releaseIdleTimer() }
.onChange(of: transportTick) { syncIdleTimer() }
.onChange(of: library.isLoaded) {
restoreCurrentRig()
maybeWarnICloudUnavailable()
}
.onChange(of: currentRigID) { persistCurrentRigID() }
.background(boardsSheetAnchor)
.background(rigExportAnchor)
.background(rigImportAnchor)
@@ -333,7 +331,7 @@ public struct ShoeGazeBuilderView: View {
private var rigSidebar: some View {
RigLibrarySidebarView(
store: library,
currentRigID: $currentRigID,
currentRigID: Binding(get: { shoeGaze.currentRigID }, set: { shoeGaze.currentRigID = $0 }),
onSelect: { entry in requestLoad(entry) },
onNew: { promptNewRig() },
onSave: { saveCurrentRig() },
@@ -718,10 +716,9 @@ public struct ShoeGazeBuilderView: View {
/// Persists the current rig to the autosave file. Called after structural edits so state
/// survives a restart even without an explicit Save; the app shells also save on background.
private func autosave() {
// The autosave envelope records `shoeGaze.currentRigID` alongside the graph, so the highlight
// and the restored graph stay consistent without any separate bookkeeping.
RigStore.save(shoeGaze)
// Pair the current-rig id with every graph write so the persisted highlight can never drift
// from the autosaved graph (the source of the highlight/graph mismatch on restart).
persistCurrentRigID()
}
/// Removes every board, then seeds one fresh empty board so the builder is never boardless.
@@ -897,33 +894,6 @@ public struct ShoeGazeBuilderView: View {
// MARK: - Rig library
/// Highlights the rig the working session derives from, once the library has loaded. Runs once.
///
/// The current rig id is written paired with every autosave (see ``autosave()``), so the stored
/// id always tracks the loaded graph — including after edits such as learning a MIDI binding,
/// which change the graph but not which saved rig it came from. Only highlights when nothing is
/// selected yet and the saved id still exists in the library.
private func restoreCurrentRig() {
guard !didRestoreRig, library.isLoaded else { return }
didRestoreRig = true
guard currentRigID == nil,
let stored: String = UserDefaults.standard.string(
forKey: ShoeGazeBuilderView.currentRigDefaultsKey),
let id: UUID = UUID(uuidString: stored),
library.entries.contains(where: { $0.id == id }) else { return }
currentRigID = id
}
/// Persists `currentRigID` so the same rig is highlighted on the next launch.
private func persistCurrentRigID() {
let defaults: UserDefaults = UserDefaults.standard
if let id: UUID = currentRigID {
defaults.set(id.uuidString, forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
} else {
defaults.removeObject(forKey: ShoeGazeBuilderView.currentRigDefaultsKey)
}
}
/// Loads a library entry into the session, replacing the current rig. Stops/restarts the engine
/// around the rebuild, resets the board selection, and records the entry as current.
private func loadEntry(_ entry: RigEntry) {