feat(ui): Mine/Starters rig toggle + seed starters into existing libraries

Two fixes so shipped starter rigs are actually reachable:

- Seeding no longer requires an empty library. On launch it installs any
  factory rigs whose stable ids are missing, once per FactoryRigLibrary
  .seedVersion (a per-device UserDefaults marker). Existing users therefore
  receive the starters on their next launch; a starter the user later
  deletes stays deleted (the marker has advanced); bumping seedVersion when
  new starters ship re-runs catch-up for just the new ones. Idempotent by id,
  so iCloud-synced devices never duplicate.
- Sidebar gains a segmented Mine / Starters toggle. "Mine" is the flat,
  reorderable user list; "Starters" groups the shipped rigs by category. A
  "Restore Starter Rigs" action (Starters empty-state button + library menu)
  re-installs missing starters on demand via RigLibraryBootstrap.restoreStarterRigs.

Co-Authored-By: Claude Opus 4.8 <noreply@anthropic.com>
This commit is contained in:
2026-08-09 14:11:22 -07:00
parent fba32ff0aa
commit ad6ed41674
4 changed files with 168 additions and 77 deletions
@@ -10,75 +10,101 @@ import LyrebirdShoeGaze
/// Setup of the rig library for an app shell, split so nothing blocks the launch path.
///
/// ``makeStore()`` returns an auto-resolving store instantly (safe to construct in a synchronous
/// initializer and hand to the UI). ``start(_:seedFrom:seedName:)`` then does the blocking work —
/// resolving the iCloud-or-local location and the initial load — off the main thread, and seeds the
/// library from the current working rig **only after** the real (possibly iCloud) contents are
/// known, so a first launch can't create a duplicate "Default" rig on every synced device.
/// initializer and hand to the UI). ``start(_:seedFrom:)`` then does the blocking work — resolving
/// the iCloud-or-local location and the initial load — off the main thread, then performs a one-time
/// catch-up seed of any missing shipped starter rigs.
@MainActor
public enum RigLibraryBootstrap {
/// `UserDefaults` key holding the highest ``FactoryRigLibrary/seedVersion`` this device has
/// already seeded. Per-device (not synced): the seed is idempotent by stable rig id, so a device
/// that receives the rigs via iCloud sync simply finds them already present and seeds nothing.
private static let seedVersionKey: String = "net.realizedsound.shoegaze.factorySeedVersion"
/// Creates an auto-resolving store. Construct this synchronously at launch; call
/// ``start(_:seedFrom:seedName:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
/// ``start(_:seedFrom:)`` afterwards (e.g. from a SwiftUI `.task` or a `Task`).
public static func makeStore() -> RigLibraryStore {
RigLibraryStore()
}
/// Resolves + loads `store` off the main thread, then seeds it from `shoeGaze` if it is still
/// empty after loading (first run). Idempotent enough to call once at launch.
/// Resolves + loads `store` off the main thread, then performs a one-time catch-up seed of any
/// missing shipped starter rigs. Idempotent — safe to call once at every launch.
///
/// Seeding adds only factory rigs whose stable ids are **not already present**, so it never
/// duplicates a rig and never touches the user's own rigs. It runs at most once per
/// ``FactoryRigLibrary/seedVersion``: a first launch seeds every starter; a launch after an
/// update that ships new starters seeds just the new ones; and a starter the user later deletes
/// stays deleted (the version marker has already advanced). This deliberately replaces the old
/// "only seed an empty library" rule so users who already had rigs still receive the starters.
///
/// - Parameters:
/// - store: The store from ``makeStore()``.
/// - shoeGaze: The session whose current rig seeds the library when it is first empty.
/// - seedName: Name for the seeded first rig. Defaults to `"Default"`.
/// - shoeGaze: The working session (currently unused by seeding; kept for call-site stability
/// and future working-rig seeding needs).
public static func start(
_ store: RigLibraryStore,
seedFrom shoeGaze: ShoeGaze,
seedName: String = "Default"
seedFrom shoeGaze: ShoeGaze
) async {
await store.start()
// Seed only after the (possibly iCloud) library has loaded: an empty library here means a
// genuine first run, not a not-yet-synced one.
guard store.entries.isEmpty else { return }
let defaults: UserDefaults = .standard
let seededVersion: Int = defaults.integer(forKey: seedVersionKey) // 0 when never seeded
guard seededVersion < FactoryRigLibrary.seedVersion else { return }
// First run: populate the library with the shipped starter rigs. These are built in
// throwaway offline sessions, so they are independent of the current working graph. The
// working session is intentionally left as-is (no `currentRigID`) — the user picks a starter
// rig from the sidebar to load it, rather than the highlight pointing at a rig the working
// graph has not actually loaded.
// Seed the shipped starter rigs. `store.save` updates the in-memory library synchronously
// (so the session sees every rig immediately) and persists to disk asynchronously — a disk
// failure is logged by the store, not thrown here, so there is no per-entry rollback to do.
// `save` throws only on a synchronous encode failure of this deterministic rig data, which
// should not happen at runtime; if the build or an encode somehow fails, fall back to
// seeding the working rig so the library is never left empty on first run.
// Seed missing starters. Only advance the marker if seeding succeeded, so a transient failure
// (which should not happen for this deterministic data) is retried on the next launch.
if seedMissingFactoryRigs(into: store) {
defaults.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
}
}
/// Adds any shipped starter rig not already in `store`, keyed by stable id. Safe to call anytime.
///
/// Use this to drive a user-facing "Restore Starter Rigs" action: it re-adds starters the user
/// deleted (and any newly-shipped ones) without disturbing their own rigs, and advances the seed
/// marker so automatic catch-up seeding won't fight the manual restore.
///
/// - Parameter store: The library to seed into.
/// - Returns: The number of starter rigs added (0 if all were already present).
@discardableResult
public static func restoreStarterRigs(into store: RigLibraryStore) -> Int {
let added: Int = addMissingFactoryRigs(into: store)
UserDefaults.standard.set(FactoryRigLibrary.seedVersion, forKey: seedVersionKey)
return added
}
/// Seeds missing starters, returning whether the operation completed without a build/encode error
/// (so the caller knows whether to advance the seed marker).
private static func seedMissingFactoryRigs(into store: RigLibraryStore) -> Bool {
do {
let entries: [RigEntry] = try FactoryRigLibrary.makeEntries()
for entry: RigEntry in entries {
try store.save(entry)
}
_ = try addMissingFactoryRigsThrowing(into: store)
return true
} catch {
print("[RigLibraryBootstrap] seeding factory rigs failed: \(error)")
seedWorkingRig(store, seedFrom: shoeGaze, seedName: seedName)
return false
}
}
/// Seeds the working session's current rig as a single named library entry.
///
/// Last-resort fallback used only when the factory rigs could not be built; keeps the library
/// from being left empty on first run.
private static func seedWorkingRig(
_ store: RigLibraryStore,
seedFrom shoeGaze: ShoeGaze,
seedName: String
) {
guard !shoeGaze.boards.isEmpty else { return }
let entry: RigEntry = shoeGaze.captureEntry(name: seedName)
/// Non-throwing convenience: seeds missing starters and returns the count added (0 on error).
private static func addMissingFactoryRigs(into store: RigLibraryStore) -> Int {
do {
try store.save(entry)
shoeGaze.currentRigID = entry.id
return try addMissingFactoryRigsThrowing(into: store)
} catch {
print("[RigLibraryBootstrap] fallback seeding failed: \(error)")
print("[RigLibraryBootstrap] restoring factory rigs failed: \(error)")
return 0
}
}
/// Builds the starter rigs and saves the ones whose ids are missing from `store`.
///
/// - Returns: The number of rigs added.
/// - Throws: Any error from building the rigs or a synchronous encode failure in `store.save`.
private static func addMissingFactoryRigsThrowing(into store: RigLibraryStore) throws -> Int {
let existingIDs: Set<UUID> = Set(store.entries.map { $0.id })
let missing: [RigEntry] = try FactoryRigLibrary.makeEntries().filter { !existingIDs.contains($0.id) }
for entry: RigEntry in missing {
try store.save(entry)
}
return missing.count
}
}