Commit 7bdecfae authored by Kourser's avatar Kourser
Browse files

feat(sync): iCloud — subscriptions, queue and positions with nothing to set up

A third sync service, beside Nextcloud and gpodder.net, for the user who
only wants to go from an iPhone to an iPad: no account, no server. It
goes through iCloud's key-value store in the user's own account — up to
1 MB per user, kept by the system on each device.

What is stored (SyncKit/CloudLibrary, free of iCloud and tested):
- `subscriptions`: every feed ever followed, subscribed or not, with the
  date of that change. The newest change wins, feed by feed; a removal
  stays as such, or a device that had not heard of it would subscribe
  again. Each device also keeps its own merged view, so a change it made
  survives another device overwriting the key from an older one.
  Radios travel too: only Skingomz reads this.
- `positions.<device>`: each device's own latest positions, as gpodder
  play actions within 120 KB. A device writes only its own key — devices
  never overwrite one another — and reads the others' with the merge of
  the previous commit: newest position wins, episodes found by guid then
  by media address without its query. Keys silent for 180 days go.
- `queue`: the whole queue with the date it last changed; the newest
  wins, resolved here by the same matching, refreshing a feed once for
  an episode this device does not know yet.
Turning iCloud on, or another iCloud account, makes the next sync a
first one: both libraries joined, nothing removed.

When: on launch, on every change from another device, at the triggers
of the previous commit (pause, end of an episode, leaving and coming
back to the app), and when subscriptions or the queue change here.

Réglages › Synchronisation gains "Aucune" and "iCloud"; the account
fields only show for a server. The choice is stored when made.

Also fixes a fault of the previous commit, found in testing: a new sync
request cancelled the one under way rather than only its wait, and every
read and request of the cancelled exchange failed silently. The
debounced task now spawns the exchange in a task of its own.

Distribution: the app gains the iCloud key-value entitlement on both
platforms, with the same identifier, so iPhone, iPad and Mac share it.
Apple allows it for Developer ID too, but it then needs a provisioning
profile: release.sh lets Xcode fetch one (-allowProvisioningUpdates).

Verified on two iOS 27 simulators against a DEBUG-only stand-in for the
store (-uiCloudServer, polled every 2 s), since simulators share no
iCloud account: the iPad's first launch took the iPhone's subscriptions
and positions with their dates; a third, simulated device's removal of
a podcast, queue of two real episodes (one found by guid, one by media
address under another token) and newer position reached both; removing
an episode from the iPhone's queue in its UI emptied it from the iPad's
within 5 s; each device rewrote only its own positions key, with no
echo. With the real store the app runs and writes nothing, the
simulators having no iCloud account. 16 new tests. Not tried: real
iCloud between two devices, and the Mac.

Co-Authored-By: default avatarClaude Opus 5.5 <noreply@anthropic.com>
parent 2ca810fc
Loading
Loading
Loading
Loading
+11
Changes for CHANGELOG.md: 11 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -7,6 +7,17 @@ adopte le [versionnage sémantique](https://semver.org/lang/fr/).

## [Non publié]

### Ajouté
- **Synchronisation iCloud** : un nouveau choix dans Réglages › Synchronisation,
  sans compte ni serveur à configurer. Abonnements (radios comprises), file
  d'attente et positions de lecture passent d'un appareil à l'autre par le
  compte iCloud de l'utilisateur. La position la plus récente gagne, épisode par
  épisode ; un abonnement ajouté ou retiré sur un appareil l'est sur les autres ;
  la file modifiée en dernier remplace les autres. À la première activation, les
  bibliothèques sont réunies et rien n'est supprimé. Les identifiants des flux
  privés restent à saisir sur chaque appareil. Un choix « Aucune » permet aussi
  de désactiver la synchronisation.

### Corrigé
- **Synchronisation de la position de lecture** (Nextcloud et gpodder.net) :
  - une position plus ancienne pouvait écraser la plus récente. Chaque position
+17
Changes for Packages/Core/Sources/StorageKit/LibraryStore+QueueDownload.swift: 17 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -57,6 +57,23 @@ extension LibraryStore {
        }
    }

    /// Makes the queue exactly these episodes, in this order, at once —
    /// another device's queue arriving through iCloud. Unknown ids are skipped.
    public func replaceQueue(with ids: [UUID]) async throws {
        try await dbQueue.write { db in
            try QueueRecord.deleteAll(db)
            var position = 0
            var seen = Set<String>()
            for id in ids {
                let episodeId = id.uuidString
                guard seen.insert(episodeId).inserted,
                      try EpisodeRecord.exists(db, key: episodeId) else { continue }
                try QueueRecord(episodeId: episodeId, position: position).insert(db)
                position += 1
            }
        }
    }

    public func clearQueue() async throws {
        _ = try await dbQueue.write { db in
            try QueueRecord.deleteAll(db)
+277
Changes for Packages/Core/Sources/SyncKit/CloudLibrary.swift: 277 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import PodcastModel

// The library as kept in iCloud's key-value store, shared by the user's
// devices — and the rules for merging it, free of iCloud so they can be tested.
//
// Three kinds of keys:
// - `subscriptions`: every feed ever followed, each marked subscribed or not,
//   with the date of that change. The newest change wins, feed by feed. A
//   removal stays as such rather than disappearing, or a device that had not
//   heard of it would subscribe again.
// - `positions.<device>`: each device's own latest positions, as gpodder `play`
//   actions. A device writes only its own key, so devices never overwrite one
//   another; each reads the others' and keeps, episode by episode, the newest
//   position (`ProgressSync`).
// - `queue`: the whole queue, with the date it last changed. The newest wins.

/// An episode as another device can find it: the feed it belongs to, and what
/// that feed says of it.
public struct CloudEpisodeRef: Codable, Sendable, Equatable {
    public var feed: String
    public var guid: String?
    public var media: String?

    public init(feed: String, guid: String?, media: String?) {
        self.feed = feed
        self.guid = guid
        self.media = media
    }

    public init(episode: Episode, feedURL: URL) {
        self.init(feed: feedURL.absoluteString, guid: episode.guid, media: episode.enclosureURL?.absoluteString)
    }

    /// Two references to the same episode compare equal here, whatever token
    /// a host appended to its media address on either device.
    public var matchKey: String {
        let feedKey = URL(string: feed).map(ProgressSync.feedKey) ?? feed
        if let guid { return feedKey + "#g:" + guid }
        guard let media, var components = URLComponents(string: media) else { return feedKey + "#" }
        components.query = nil
        components.fragment = nil
        return feedKey + "#m:" + (components.string ?? media)
    }
}

/// A feed followed — or no longer followed — on some device.
public struct CloudSubscription: Codable, Sendable, Equatable {
    public var url: String
    public var title: String?
    public var imageURL: String?
    /// A radio is a stream URL, not a feed: it is added, not fetched.
    public var isRadio: Bool
    public var subscribed: Bool
    /// When it was subscribed to or unsubscribed from.
    public var date: Date

    public init(url: String, title: String?, imageURL: String?, isRadio: Bool, subscribed: Bool, date: Date) {
        self.url = url
        self.title = title
        self.imageURL = imageURL
        self.isRadio = isRadio
        self.subscribed = subscribed
        self.date = date
    }

    public init(podcast: Podcast, date: Date) {
        self.init(url: podcast.feedURL.absoluteString, title: podcast.title,
                  imageURL: podcast.imageURL?.absoluteString, isRadio: podcast.isRadio,
                  subscribed: true, date: date)
    }
}

/// One device's latest positions.
public struct CloudDevicePositions: Codable, Sendable, Equatable {
    /// When the device last wrote them: a device silent for months is gone,
    /// and its key is removed to make room.
    public var updatedAt: Date
    public var actions: [EpisodeAction]

    public init(updatedAt: Date, actions: [EpisodeAction]) {
        self.updatedAt = updatedAt
        self.actions = actions
    }
}

public struct CloudQueue: Codable, Sendable, Equatable {
    /// When the queue last changed, on whichever device changed it.
    public var date: Date
    public var episodes: [CloudEpisodeRef]

    public init(date: Date, episodes: [CloudEpisodeRef]) {
        self.date = date
        self.episodes = episodes
    }

    func sameEpisodes(as refs: [CloudEpisodeRef]) -> Bool {
        episodes.map(\.matchKey) == refs.map(\.matchKey)
    }
}

/// What to do to the library here, and what to store in iCloud.
public struct SubscriptionPlan: Sendable, Equatable {
    /// The merged view, to keep on this device and write to iCloud.
    public var entries: [String: CloudSubscription]
    /// Feeds to subscribe to here.
    public var subscribe: [CloudSubscription]
    /// Feeds to unsubscribe from here, by `ProgressSync.feedKey`.
    public var unsubscribe: Set<String>
}

public enum QueueDecision: Sendable, Equatable {
    case keep
    /// Write this queue to iCloud.
    case push(CloudQueue)
    /// Make the local queue this one; it changed at `date`.
    case apply([CloudEpisodeRef], date: Date)
    /// Both: a first sync, where the two queues are joined.
    case applyAndPush(CloudQueue)
}

public enum CloudLibrary {
    public static let subscriptionsKey = "subscriptions"
    public static let queueKey = "queue"
    public static let positionsPrefix = "positions."

    /// Room for one device's positions. iCloud gives an app 1 MB in all:
    /// enough for several devices, the subscriptions and the queue.
    public static let positionsByteBudget = 120_000
    /// A device that has not written its positions for this long is gone.
    public static let staleDeviceAge: TimeInterval = 180 * 24 * 3600
    /// Removals older than this are forgotten: every device has long applied them.
    public static let tombstoneAge: TimeInterval = 365 * 24 * 3600

    public static func positionsKey(device: String) -> String { positionsPrefix + device }

    // MARK: Coding

    public static func encode<T: Encodable>(_ value: T) -> Data? {
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .secondsSince1970
        encoder.outputFormatting = .sortedKeys
        return try? encoder.encode(value)
    }

    public static func decode<T: Decodable>(_ type: T.Type, from data: Data?) -> T? {
        guard let data else { return nil }
        let decoder = JSONDecoder()
        decoder.dateDecodingStrategy = .secondsSince1970
        return try? decoder.decode(type, from: data)
    }

    // MARK: Subscriptions

    /// Merges what this device knew, what iCloud holds and what is subscribed
    /// here, into what to do here and what to store.
    ///
    /// - Parameters:
    ///   - known: the merged view this device stored last time.
    ///   - cloud: the view in iCloud now — possibly written by a device that
    ///     had not seen this one's latest changes.
    ///   - local: the subscriptions here now.
    ///   - baseline: the feeds subscribed here after the last sync, by feed
    ///     key; `nil` for a first sync, which joins both sides and removes
    ///     nothing.
    public static func reconcileSubscriptions(
        known: [String: CloudSubscription],
        cloud: [String: CloudSubscription],
        local: [Podcast],
        baseline: Set<String>?,
        now: Date
    ) -> SubscriptionPlan {
        var entries = known
        for (key, entry) in cloud where entries[key].map({ entry.date > $0.date }) ?? true {
            entries[key] = entry
        }
        let localByKey = Dictionary(local.map { (ProgressSync.feedKey($0.feedURL), $0) },
                                    uniquingKeysWith: { first, _ in first })
        let localKeys = Set(localByKey.keys)

        if let baseline {
            // Changed here since the last sync: these win, being the newest.
            for key in localKeys.subtracting(baseline) where entries[key]?.subscribed != true {
                entries[key] = CloudSubscription(podcast: localByKey[key]!, date: now)
            }
            for key in baseline.subtracting(localKeys) {
                if var entry = entries[key], entry.subscribed {
                    entry.subscribed = false
                    entry.date = now
                    entries[key] = entry
                }
            }
        } else {
            for key in localKeys where entries[key]?.subscribed != true {
                entries[key] = CloudSubscription(podcast: localByKey[key]!, date: now)
            }
        }
        // Followed here and unknown to every view: another device overwrote
        // the key without having seen it. Said again.
        for key in localKeys where entries[key] == nil {
            entries[key] = CloudSubscription(podcast: localByKey[key]!, date: now)
        }
        entries = entries.filter { $0.value.subscribed || now.timeIntervalSince($0.value.date) < tombstoneAge }

        return SubscriptionPlan(
            entries: entries,
            subscribe: entries.filter { $0.value.subscribed && !localKeys.contains($0.key) }
                .map(\.value).sorted { $0.date < $1.date },
            unsubscribe: Set(entries.filter { !$0.value.subscribed && localKeys.contains($0.key) }.keys)
        )
    }

    // MARK: Positions

    /// This device's positions, newest first, as many as fit in the budget.
    public static func devicePositions(
        from progress: [EpisodeProgress],
        now: Date,
        byteBudget: Int = positionsByteBudget
    ) -> CloudDevicePositions {
        let newestFirst = ProgressSync.actions(for: progress, changedAfter: nil).reversed()
        var actions = Array(newestFirst)
        func size(_ count: Int) -> Int {
            encode(CloudDevicePositions(updatedAt: now, actions: Array(actions.prefix(count))))?.count ?? .max
        }
        if size(actions.count) > byteBudget {
            // The largest count that fits.
            var low = 0, high = actions.count
            while low < high {
                let middle = (low + high + 1) / 2
                if size(middle) <= byteBudget { low = middle } else { high = middle - 1 }
            }
            actions = Array(actions.prefix(low))
        }
        return CloudDevicePositions(updatedAt: now, actions: actions)
    }

    /// The other devices' keys gone silent for too long, to remove.
    public static func staleDeviceKeys(_ devices: [String: CloudDevicePositions], now: Date) -> [String] {
        devices.filter { now.timeIntervalSince($0.value.updatedAt) > staleDeviceAge }.map(\.key).sorted()
    }

    // MARK: Queue

    /// - Parameters:
    ///   - local: the queue here.
    ///   - localChangedAt: when it last changed here, or was last made like
    ///     iCloud's; `nil` if it never was, for a first sync.
    public static func queueDecision(
        local: [CloudEpisodeRef],
        localChangedAt: Date?,
        cloud: CloudQueue?,
        now: Date
    ) -> QueueDecision {
        guard let cloud else {
            guard localChangedAt != nil || !local.isEmpty else { return .keep }
            return .push(CloudQueue(date: localChangedAt ?? now, episodes: local))
        }
        guard let localChangedAt else {
            // First sync: iCloud's queue, then what is queued only here.
            let known = Set(cloud.episodes.map(\.matchKey))
            let joined = cloud.episodes + local.filter { !known.contains($0.matchKey) }
            if joined.count == cloud.episodes.count {
                return cloud.sameEpisodes(as: local) ? .keep : .apply(cloud.episodes, date: cloud.date)
            }
            return .applyAndPush(CloudQueue(date: now, episodes: joined))
        }
        if cloud.sameEpisodes(as: local) { return .keep }
        if localChangedAt.timeIntervalSince(cloud.date) >= 1 {
            return .push(CloudQueue(date: localChangedAt, episodes: local))
        }
        if cloud.date.timeIntervalSince(localChangedAt) >= 1 {
            return .apply(cloud.episodes, date: cloud.date)
        }
        return .keep
    }
}
+10
Changes for Packages/Core/Tests/StorageKitTests/QueueDownloadTests.swift: 10 added lines, 0 removed lines.
Original line number Diff line number Diff line
@@ -54,6 +54,16 @@ private func storeWithThreeEpisodes() async throws -> (LibraryStore, [Episode])
        #expect(queued.map(\.title) == ["Ep 1", "Ep 2", "Ep 0"])
    }

    @Test func replaceSetsOrderSkipsUnknownAndDuplicates() async throws {
        let (store, eps) = try await storeWithThreeEpisodes()
        try await store.enqueue(episodeID: eps[0].id)
        try await store.replaceQueue(with: [eps[2].id, UUID(), eps[1].id, eps[2].id])
        #expect(try await store.queuedEpisodes().map(\.id) == [eps[2].id, eps[1].id])
        // Positions stay contiguous: an append lands right after.
        try await store.enqueue(episodeID: eps[0].id)
        #expect(try await store.queuedEpisodes().map(\.id) == [eps[2].id, eps[1].id, eps[0].id])
    }

    @Test func clearEmptiesQueue() async throws {
        let (store, eps) = try await storeWithThreeEpisodes()
        for ep in eps { try await store.enqueue(episodeID: ep.id) }
+177
Changes for Packages/Core/Tests/SyncKitTests/CloudLibraryTests.swift: 177 added lines, 0 removed lines.
Original line number Diff line number Diff line
import Foundation
import Testing
import PodcastModel
@testable import SyncKit

@Suite struct CloudSubscriptionTests {
    private let monday = Date(timeIntervalSince1970: 1_790_000_000)
    private var tuesday: Date { monday.addingTimeInterval(86_400) }

    private func podcast(_ url: String, title: String = "Cast", radio: Bool = false) -> Podcast {
        Podcast(feedURL: URL(string: url)!, title: title, isRadio: radio)
    }

    private func key(_ url: String) -> String { ProgressSync.feedKey(URL(string: url)!) }

    private func entry(_ url: String, subscribed: Bool = true, at date: Date) -> (String, CloudSubscription) {
        (key(url), CloudSubscription(url: url, title: "Cast", imageURL: nil, isRadio: false, subscribed: subscribed, date: date))
    }

    @Test func firstDeviceWritesItsLibrary() {
        let plan = CloudLibrary.reconcileSubscriptions(
            known: [:], cloud: [:], local: [podcast("https://a.example/feed"), podcast("https://radio.example/live", radio: true)],
            baseline: nil, now: monday)
        #expect(plan.entries.count == 2)
        #expect(plan.entries[key("https://radio.example/live")]?.isRadio == true)
        #expect(plan.subscribe.isEmpty && plan.unsubscribe.isEmpty)
    }

    @Test func firstSyncJoinsBothSidesAndRemovesNothing() {
        let cloud = Dictionary(uniqueKeysWithValues: [entry("https://a.example/feed", at: monday),
                                                      entry("https://gone.example/feed", subscribed: false, at: monday)])
        let plan = CloudLibrary.reconcileSubscriptions(
            known: [:], cloud: cloud,
            local: [podcast("https://b.example/feed"), podcast("https://gone.example/feed")],
            baseline: nil, now: tuesday)
        #expect(plan.subscribe.map(\.url) == ["https://a.example/feed"])
        #expect(plan.unsubscribe.isEmpty)
        #expect(plan.entries[key("https://b.example/feed")]?.subscribed == true)
        // Followed here at the first sync: it stays, and says so.
        #expect(plan.entries[key("https://gone.example/feed")]?.subscribed == true)
    }

    @Test func removalElsewhereIsAppliedHere() {
        let known = Dictionary(uniqueKeysWithValues: [entry("https://a.example/feed", at: monday)])
        let cloud = Dictionary(uniqueKeysWithValues: [entry("https://a.example/feed", subscribed: false, at: tuesday)])
        let plan = CloudLibrary.reconcileSubscriptions(
            known: known, cloud: cloud, local: [podcast("https://a.example/feed")],
            baseline: [key("https://a.example/feed")], now: tuesday.addingTimeInterval(60))
        #expect(plan.unsubscribe == [key("https://a.example/feed")])
    }

    @Test func removalHereBecomesARemovalForEveryone() {
        let known = Dictionary(uniqueKeysWithValues: [entry("https://a.example/feed", at: monday)])
        let plan = CloudLibrary.reconcileSubscriptions(
            known: known, cloud: known, local: [],
            baseline: [key("https://a.example/feed")], now: tuesday)
        #expect(plan.entries[key("https://a.example/feed")]?.subscribed == false)
        #expect(plan.entries[key("https://a.example/feed")]?.date == tuesday)
        #expect(plan.subscribe.isEmpty)
    }

    @Test func changeHereSurvivesAnotherDeviceOverwritingTheKey() {
        // This device removed A and added B; another device then wrote the key
        // from an older view, where A is still followed and B unknown.
        let known = Dictionary(uniqueKeysWithValues: [entry("https://a.example/feed", subscribed: false, at: tuesday),
                                                      entry("https://b.example/feed", at: tuesday)])
        let olderCloud = Dictionary(uniqueKeysWithValues: [entry("https://a.example/feed", at: monday)])
        let plan = CloudLibrary.reconcileSubscriptions(
            known: known, cloud: olderCloud, local: [podcast("https://b.example/feed")],
            baseline: [key("https://b.example/feed")], now: tuesday.addingTimeInterval(60))
        #expect(plan.entries[key("https://a.example/feed")]?.subscribed == false)
        #expect(plan.entries[key("https://b.example/feed")]?.subscribed == true)
        #expect(plan.subscribe.isEmpty && plan.unsubscribe.isEmpty)
    }

    @Test func feedUnknownToEveryViewIsSaidAgain() {
        let plan = CloudLibrary.reconcileSubscriptions(
            known: [:], cloud: [:], local: [podcast("https://a.example/feed")],
            baseline: [key("https://a.example/feed")], now: tuesday)
        #expect(plan.entries[key("https://a.example/feed")]?.subscribed == true)
    }

    @Test func oldRemovalsAreForgotten() {
        let ancient = monday.addingTimeInterval(-400 * 86_400)
        let cloud = Dictionary(uniqueKeysWithValues: [entry("https://old.example/feed", subscribed: false, at: ancient)])
        let plan = CloudLibrary.reconcileSubscriptions(known: [:], cloud: cloud, local: [], baseline: [], now: monday)
        #expect(plan.entries.isEmpty)
    }

    @Test func entriesSurviveTheirTripThroughJSON() {
        let entries = Dictionary(uniqueKeysWithValues: [entry("https://a.example/feed", at: monday)])
        let data = CloudLibrary.encode(entries)
        #expect(CloudLibrary.decode([String: CloudSubscription].self, from: data) == entries)
        #expect(CloudLibrary.decode([String: CloudSubscription].self, from: Data("pas du JSON".utf8)) == nil)
    }
}

@Suite struct CloudPositionsTests {
    private let monday = Date(timeIntervalSince1970: 1_790_000_000)

    private func progress(_ count: Int) -> [EpisodeProgress] {
        (0..<count).map { i in
            EpisodeProgress(
                episode: Episode(guid: "ep-\(i)", title: "Ep \(i)",
                                 enclosureURL: URL(string: "https://cdn.example.com/\(i).mp3"), duration: 3600),
                feedURL: URL(string: "https://example.com/feed.xml")!,
                position: TimeInterval(i), isPlayed: false,
                updatedAt: monday.addingTimeInterval(TimeInterval(i)))
        }
    }

    @Test func keepsTheNewestPositionsThatFitTheBudget() {
        let all = CloudLibrary.devicePositions(from: progress(50), now: monday)
        #expect(all.actions.count == 50)
        #expect(all.actions.first?.guid == "ep-49") // newest first

        let trimmed = CloudLibrary.devicePositions(from: progress(50), now: monday, byteBudget: 3_000)
        #expect(trimmed.actions.count < 50)
        #expect(trimmed.actions.count > 0)
        #expect(trimmed.actions.first?.guid == "ep-49")
        #expect((CloudLibrary.encode(trimmed)?.count ?? .max) <= 3_000)
    }

    @Test func silentDevicesAreFoundStale() {
        let devices = [
            "positions.recent": CloudDevicePositions(updatedAt: monday, actions: []),
            "positions.gone": CloudDevicePositions(updatedAt: monday.addingTimeInterval(-200 * 86_400), actions: []),
        ]
        #expect(CloudLibrary.staleDeviceKeys(devices, now: monday) == ["positions.gone"])
    }
}

@Suite struct CloudQueueTests {
    private let monday = Date(timeIntervalSince1970: 1_790_000_000)
    private let feed = "https://example.com/feed.xml"

    private func ref(_ n: Int, token: String = "") -> CloudEpisodeRef {
        CloudEpisodeRef(feed: feed, guid: nil, media: "https://cdn.example.com/\(n).mp3\(token)")
    }

    @Test func sameEpisodeWhateverTheTokenInItsAddress() {
        #expect(ref(1, token: "?_=1").matchKey == ref(1, token: "?_=2").matchKey)
        #expect(ref(1).matchKey != ref(2).matchKey)
        let byGuid = CloudEpisodeRef(feed: feed, guid: "g", media: "https://a/1.mp3")
        #expect(byGuid.matchKey == CloudEpisodeRef(feed: feed + "/", guid: "g", media: "https://b/1.mp3").matchKey)
    }

    @Test func nothingAnywhereStaysNothing() {
        #expect(CloudLibrary.queueDecision(local: [], localChangedAt: nil, cloud: nil, now: monday) == .keep)
    }

    @Test func firstDeviceWritesItsQueue() {
        #expect(CloudLibrary.queueDecision(local: [ref(1)], localChangedAt: nil, cloud: nil, now: monday)
                == .push(CloudQueue(date: monday, episodes: [ref(1)])))
    }

    @Test func firstSyncJoinsBothQueues() {
        let cloud = CloudQueue(date: monday, episodes: [ref(1), ref(2)])
        let later = monday.addingTimeInterval(60)
        #expect(CloudLibrary.queueDecision(local: [ref(2, token: "?_=9"), ref(3)], localChangedAt: nil, cloud: cloud, now: later)
                == .applyAndPush(CloudQueue(date: later, episodes: [ref(1), ref(2), ref(3)])))
        // Nothing of its own: it takes iCloud's.
        #expect(CloudLibrary.queueDecision(local: [], localChangedAt: nil, cloud: cloud, now: later)
                == .apply([ref(1), ref(2)], date: monday))
    }

    @Test func newestQueueWins() {
        let cloud = CloudQueue(date: monday, episodes: [ref(1), ref(2)])
        let later = monday.addingTimeInterval(60)
        #expect(CloudLibrary.queueDecision(local: [ref(2)], localChangedAt: later, cloud: cloud, now: later)
                == .push(CloudQueue(date: later, episodes: [ref(2)])))
        #expect(CloudLibrary.queueDecision(local: [ref(3)], localChangedAt: monday.addingTimeInterval(-60), cloud: cloud, now: later)
                == .apply([ref(1), ref(2)], date: monday))
        #expect(CloudLibrary.queueDecision(local: [ref(1), ref(2, token: "?_=5")], localChangedAt: later, cloud: cloud, now: later)
                == .keep)
    }
}
Loading