Cotton code
466 lines · 19.5 KB · SwiftRaw
// The promise that audio is never lost silently, held by a test.//// Four things have to be true for a recording that never became a meeting to be// findable on the next launch: the markers round-trip through the App Group// defaults — ONE PER RECORDING, since the walk of 16 Sep 2026 watched a single// slot get overwritten by the next recording and take the only pointer to// somebody's audio with it — the rules that turn one into an OFFER are exact,// a capture no marker names at all is still offered, and the sentences the slip// shows say what actually happened. Each is a section below, and all but the// sweep's own case run with no container, no filesystem and no clock.import CottonKitimport XCTest@testable import CottonUI/// The App Group's text slots, in memory. The same shape the share mailbox's/// own double has, because it is the same seam.private final class FakeMarkerStorage: ShareMailboxStorage, @unchecked Sendable {    private let lock = NSLock()    private var values: [String: String] = [:]    init(_ seed: [String: String] = [:]) { values = seed }    func text(_ key: String) -> String? {        lock.lock()        defer { lock.unlock() }        return values[key]    }    func set(_ key: String, _ value: String?) {        lock.lock()        defer { lock.unlock() }        if let value { values[key] = value } else { values.removeValue(forKey: key) }    }    var keys: Set<String> {        lock.lock()        defer { lock.unlock() }        return Set(values.keys)    }}private let act = "0f1e2d3c-4b5a-4968-8778-695a4b3c2d1e"private let audio = "/container/recordings/\(act)/audio.m4a"private let startedAt = "2026-09-15T12:44:00.000Z"private func marker(    stage: MeetingRecoveryStage = .closed,    durationMs: Int = 930_000,    title: String? = nil,    meetingId: String? = nil) -> MeetingRecoveryMarker {    MeetingRecoveryMarker(        id: act,        path: audio,        startedAt: startedAt,        title: title,        durationMs: durationMs,        stage: stage,        meetingId: meetingId    )}// MARK: - The markers' homefinal class MeetingRecoveryStoreTests: XCTestCase {    func testAMarkerSurvivesTheRoundTripWholeAndIsClearedOnlyOnce() throws {        let storage = FakeMarkerStorage()        let store = MeetingRecoveryStore(storage: storage)        XCTAssertEqual(store.markers(), [], "an empty suite offers nothing")        store.write(marker(stage: .paused, durationMs: 61_000, title: "Standup"))        let read = try XCTUnwrap(store.markers().first)        XCTAssertEqual(read.id, act)        XCTAssertEqual(read.path, audio)        XCTAssertEqual(read.startedAt, startedAt)        XCTAssertEqual(read.title, "Standup")        XCTAssertEqual(read.durationMs, 61_000)        XCTAssertEqual(read.recoveryStage, .paused)        store.clear(id: act)        XCTAssertEqual(store.markers(), [])        XCTAssertEqual(storage.keys, [], "the key is REMOVED, not blanked and left behind")    }    /// **The walk of 16 Sep 2026, as a test.** A note was offering a killed    /// recording; starting a new one overwrote the single slot, the note    /// vanished, and the killed capture stayed on disk with nothing pointing at    /// it. A second recording ADDS a marker.    func testASecondRecordingDoesNotOverwriteThePendingOne() throws {        let store = MeetingRecoveryStore(storage: FakeMarkerStorage())        store.write(marker(stage: .recording, durationMs: 13_000))        store.write(            MeetingRecoveryMarker(                id: "second-act", path: "/container/recordings/second-act/audio.caf",                startedAt: "2026-09-16T09:00:00.000Z", stage: .recording))        XCTAssertEqual(store.markers().map(\.id), [act, "second-act"])    }    /// The same recording moving on replaces ITS OWN row, in place — a    /// transition is not a second recording.    func testATransitionRewritesTheSameRowRatherThanAddingOne() throws {        let store = MeetingRecoveryStore(storage: FakeMarkerStorage())        store.write(marker(stage: .recording, durationMs: 1_000))        store.write(marker(stage: .closed, durationMs: 42_000))        XCTAssertEqual(store.markers().count, 1)        XCTAssertEqual(try XCTUnwrap(store.markers().first).durationMs, 42_000)        XCTAssertEqual(try XCTUnwrap(store.markers().first).recoveryStage, .closed)    }    /// And clearing ONE clears one. This is the rule the bug broke.    func testClearingOneRecordingLeavesTheOthers() {        let store = MeetingRecoveryStore(storage: FakeMarkerStorage())        store.write(marker())        store.write(            MeetingRecoveryMarker(                id: "second-act", path: "/container/recordings/second-act/audio.caf",                startedAt: "2026-09-16T09:00:00.000Z"))        store.clear(id: act)        XCTAssertEqual(store.markers().map(\.id), ["second-act"])        store.clear(id: "nobody")        XCTAssertEqual(store.markers().map(\.id), ["second-act"], "and clearing nothing clears nothing")    }    /// A later build may write a stage this one has not met. The slot is still a    /// pointer at somebody's audio, so it is read as far as it can be — and it    /// is NOT cleared, because a marker this build cannot fully read may be one    /// a later build can.    func testAStageThisBuildDoesNotKnowIsStillAMarker() throws {        let storage = FakeMarkerStorage([            MeetingRecoveryStore.key: """                [{"id":"\(act)","path":"\(audio)","startedAt":"\(startedAt)",\                "durationMs":4000,"stage":"rotating"}]                """        ])        let found = try XCTUnwrap(MeetingRecoveryStore(storage: storage).markers().first)        XCTAssertNil(found.recoveryStage, "the word is not one of ours")        XCTAssertFalse(found.isClosed, "and an unknown stage is never read as closed")        XCTAssertEqual(found.path, audio, "but it still names the audio, which is the point")    }    /// **One bad element never costs the others.** A whole array refused on    /// one corrupt element is every other recording lost with it.    func testOneUnreadableEntryDoesNotTakeTheListWithIt() {        let storage = FakeMarkerStorage([            MeetingRecoveryStore.key: """                ["nonsense",{"id":"a2","path":"\(audio)","startedAt":"\(startedAt)",\                "durationMs":0,"stage":"recording"}]                """        ])        XCTAssertEqual(MeetingRecoveryStore(storage: storage).markers().map(\.id), ["a2"])    }    func testASlotThatIsNotAListAtAllIsNothing() {        let storage = FakeMarkerStorage([MeetingRecoveryStore.key: "not json"])        XCTAssertEqual(MeetingRecoveryStore(storage: storage).markers(), [])    }    func testAMarkerWithNoPathIsNothingBecauseItNamesNoAudio() {        let storage = FakeMarkerStorage([MeetingRecoveryStore.key: #"[{"path":""}]"#])        XCTAssertEqual(MeetingRecoveryStore(storage: storage).markers(), [])    }}// MARK: - What earns an offerfinal class MeetingRecoveryOfferTests: XCTestCase {    func testAClosedRecordingWhoseFileIsThereIsOffered() throws {        let found = try XCTUnwrap(MeetingRecovery.offer(marker(), exists: { $0 == audio }))        XCTAssertEqual(found.marker.path, audio)        XCTAssertTrue(found.isPlayable, "the file was closed, so it is a whole recording")    }    /// Offered ANYWAY, and the offer says which case it is. The person's audio    /// is not this app's to delete on a guess about whether the container is    /// complete.    func testARecordingStillRunningWhenTheAppWentIsOfferedAsNotPlayable() throws {        let found = try XCTUnwrap(            MeetingRecovery.offer(marker(stage: .recording), exists: { _ in true }))        XCTAssertFalse(found.isPlayable)        let paused = try XCTUnwrap(            MeetingRecovery.offer(marker(stage: .paused), exists: { _ in true }))        XCTAssertFalse(paused.isPlayable, "a pause does not close the file either")    }    func testNoMarkerIsNoOffer() {        XCTAssertNil(MeetingRecovery.offer(nil, exists: { _ in true }))    }    /// The crash landed in the gap between the crate's answer and the clear.    /// The row exists; offering it would make a second copy of a meeting that    /// is already there.    func testAMarkerThatAlreadyNamesAMeetingIsNotOfferedAgain() {        XCTAssertNil(MeetingRecovery.offer(marker(meetingId: "meeting-1"), exists: { _ in true }))    }    /// The marker is a claim and the disk is the evidence. iOS evicts files    /// under pressure and a person can clear storage; a claim the disk    /// contradicts is not one.    func testAMarkerWhoseFileIsGoneIsNotOffered() {        XCTAssertNil(MeetingRecovery.offer(marker(), exists: { _ in false }))    }}// MARK: - How long it actually ran/// **The marker's elapsed figure is stale at a kill, and the file is not.**////// The marker is written at transitions — start, pause, resume, stop — so a/// recording the OS took mid-run carries whatever was banked a moment after/// capture opened. The walk of 15 Sep 2026 watched one run to 0:13, killed the/// app, and was offered "About 1 second of it was captured"; the meeting it/// then kept carried that same second.final class MeetingRecoveryLengthTests: XCTestCase {    func testTheFileIsAskedFirstAndTheMarkerIsOnlyTheFallback() {        let stale = marker(stage: .recording, durationMs: 1_000)        XCTAssertEqual(            MeetingRecovery.length(of: stale, probing: { path in                XCTAssertEqual(path, audio, "the probe is asked about the marker's own file")                return 13_400            }),            13_400,            "thirteen seconds of audio is thirteen seconds, whatever the marker banked"        )        XCTAssertEqual(            MeetingRecovery.length(of: stale, probing: { _ in nil }),            1_000,            "a file that answers nothing leaves the marker, which is what is left"        )        XCTAssertEqual(            MeetingRecovery.length(of: stale, probing: { _ in 0 }),            1_000,            "a zero from the probe is not an answer either"        )    }    /// Three honest answers, and no invented fourth: nothing known is `nil`,    /// which the slip says as "Some of it was captured."    func testNothingKnownStaysNothingClaimed() {        XCTAssertNil(MeetingRecovery.length(of: marker(durationMs: 0), probing: { _ in nil }))        XCTAssertNil(MeetingRecovery.length(of: marker(durationMs: 0), probing: { _ in 0 }))    }    /// And the offer CARRIES it, so the slip and the `meetings.create` that    /// follows it are the same number.    func testTheOfferCarriesTheLengthTheFileAnswered() throws {        let found = try XCTUnwrap(            MeetingRecovery.offer(                marker(stage: .recording, durationMs: 1_000),                exists: { _ in true },                probe: { _ in 13_400 }            )        )        XCTAssertEqual(found.durationMs, 13_400)        XCTAssertTrue(MeetingRecoveryWords.detail(found).contains("13"))    }    /// With no probe at all — which is what every rule above runs under — the    /// marker stands, so the offer never goes quiet because a caller forgot to    /// pass one.    func testWithNoProbeTheMarkerStillAnswers() throws {        let found = try XCTUnwrap(            MeetingRecovery.offer(marker(durationMs: 930_000), exists: { _ in true }))        XCTAssertEqual(found.durationMs, 930_000)    }}// MARK: - Every unsaved recording, not just the last one/// **One note per unsaved recording**, and a capture nothing named is still/// somebody's recording.////// The walk of 16 Sep 2026: a note was offering a killed recording, a new/// recording started before Keep or Discard was chosen, and the note went — with/// the only pointer to that audio. Two halves answer it, and both are here: the/// markers are a LIST, and the disk is swept for whatever the list has missed.final class MeetingRecoveryOffersTests: XCTestCase {    private let second = "5c7f1e2d-3b4a-4968-8778-695a4b3c2d1e"    private var secondAudio: String { "/container/recordings/\(second)/audio.caf" }    private func other(        startedAt when: String = "2026-09-16T09:00:00.000Z",        meetingId: String? = nil    ) -> MeetingRecoveryMarker {        MeetingRecoveryMarker(            id: second, path: secondAudio, startedAt: when, durationMs: 4_000,            stage: .recording, meetingId: meetingId)    }    func testTwoUnsavedRecordingsAreTwoNotes() {        let found = MeetingRecovery.offers(            markers: [marker(), other()], exists: { _ in true })        XCTAssertEqual(found.map(\.marker.id), [second, act], "newest first")        XCTAssertEqual(Set(found.map(\.marker.path)), [audio, secondAudio])    }    /// The rules one marker earns an offer by still hold inside the list: a    /// recording that became a meeting is not offered a second time, and one    /// whose file is gone is not offered at all.    func testTheOnesThatEarnNothingAreStillNotOffered() {        XCTAssertEqual(            MeetingRecovery.offers(                markers: [marker(), other(meetingId: "meeting-1")], exists: { _ in true }            ).map(\.marker.id),            [act]        )        XCTAssertEqual(            MeetingRecovery.offers(markers: [marker(), other()], exists: { $0 == audio })                .map(\.marker.id),            [act]        )    }    /// **The marker is the convenience; the file is the truth.** A capture no    /// marker names — a defaults suite that did not survive, a slot a build    /// wrote in a shape this one cannot read — is offered off the disk alone,    /// with the length read from the audio.    func testACaptureNoMarkerNamesIsStillOffered() throws {        let swept = MeetingCaptureOnDisk(            act: second, path: secondAudio, startedAt: "2026-09-16T09:00:00.000Z")        let found = MeetingRecovery.offers(            markers: [], onDisk: [swept], exists: { _ in true }, probe: { _ in 21_000 })        let one = try XCTUnwrap(found.first)        XCTAssertEqual(found.count, 1)        XCTAssertEqual(one.marker.id, second, "and Discard has an id to act on")        XCTAssertEqual(one.durationMs, 21_000, "the audio's own length, since no marker banked one")        XCTAssertFalse(one.isPlayable, "nothing says it was ever closed")    }    /// A marker that HAS spoken for an act answers for it, whatever it decided:    /// the sweep must not resurrect a recording that already became a meeting.    func testTheSweepNeverSecondGuessesAMarkerThatAlreadyAnswered() {        let swept = MeetingCaptureOnDisk(            act: second, path: secondAudio, startedAt: "2026-09-16T09:00:00.000Z")        XCTAssertEqual(            MeetingRecovery.offers(                markers: [other(meetingId: "meeting-1")], onDisk: [swept], exists: { _ in true }),            [],            "the row exists; offering it would make a second copy"        )    }    func testASweptCaptureIsNotOfferedTwiceWhenAMarkerAlsoNamesIt() {        let swept = MeetingCaptureOnDisk(            act: second, path: secondAudio, startedAt: "2026-09-16T09:00:00.000Z")        let found = MeetingRecovery.offers(            markers: [other()], onDisk: [swept], exists: { _ in true })        XCTAssertEqual(found.count, 1)        XCTAssertEqual(found.first?.durationMs, 4_000, "the marker's own figure, not a blank one")    }    /// A stamp nothing could read sorts LAST rather than first: "no date" is not    /// "the newest".    func testARecordingWithNoStampIsOfferedAfterTheOnesThatHaveOne() {        let undated = MeetingCaptureOnDisk(act: "no-date", path: "/container/recordings/no-date/audio.caf", startedAt: "")        let found = MeetingRecovery.offers(            markers: [marker()], onDisk: [undated], exists: { _ in true })        XCTAssertEqual(found.map(\.marker.id), [act, "no-date"])    }    func testNothingHeldIsNothingOffered() {        XCTAssertEqual(MeetingRecovery.offers(markers: [], exists: { _ in true }), [])    }}// MARK: - The sweep of the holding area/// The one case here with a filesystem in it: what `recordings/` answers.final class MeetingCaptureSweepTests: XCTestCase {    private var root = URL(fileURLWithPath: "/")    override func setUpWithError() throws {        root = FileManager.default.temporaryDirectory            .appendingPathComponent("cotton-sweep-\(UUID().uuidString)", isDirectory: true)        try FileManager.default.createDirectory(at: root, withIntermediateDirectories: true)    }    override func tearDownWithError() throws {        try? FileManager.default.removeItem(at: root)    }    private func write(_ act: String, _ names: [String]) throws {        let directory = root.appendingPathComponent(act, isDirectory: true)        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)        for name in names {            try Data("synthetic".utf8).write(to: directory.appendingPathComponent(name))        }    }    func testEveryActWithAudioInItIsACapture() throws {        try write("act-1", ["audio.caf"])        try write("act-2", ["holiday.m4a"])        let found = MeetingFiles.captures(under: root)        XCTAssertEqual(found.map(\.act), ["act-1", "act-2"])        XCTAssertTrue(found[0].path.hasSuffix("act-1/audio.caf"))        XCTAssertTrue(found[1].path.hasSuffix("act-2/holiday.m4a"))        XCTAssertFalse(found[0].startedAt.isEmpty, "the file's own date stands in for a marker's")    }    /// The CAPTURE is the one that is offered where both files are there: an act    /// that reached the encode has the delivered `.m4a` beside it, and the    /// capture is what a marker names.    func testTheCaptureIsPreferredOverTheFileEncodedFromIt() throws {        try write("act-1", ["audio.caf", "audio.m4a"])        XCTAssertTrue(try XCTUnwrap(MeetingFiles.captures(under: root).first).path.hasSuffix("audio.caf"))    }    func testADirectoryWithNothingThisPhoneWouldSendIsNotACapture() throws {        try write("act-1", ["notes.txt"])        try write("act-2", [])        XCTAssertEqual(MeetingFiles.captures(under: root), [])    }    func testAHoldingAreaThatDoesNotExistIsNoCaptures() {        XCTAssertEqual(            MeetingFiles.captures(under: root.appendingPathComponent("nowhere")), [])    }}// MARK: - What the slip saysfinal class MeetingRecoveryWordsTests: XCTestCase {    private let calendar: Calendar = {        var made = Calendar(identifier: .gregorian)        made.timeZone = TimeZone(secondsFromGMT: 0) ?? .gmt        return made    }()    /// **A twelve-second recording is twelve seconds.** The slip is the one    /// place a sub-minute length matters, and "About 0 min of it was captured"    /// reads as "there is nothing here" over a file there is something in (the    /// walk of 15 Sep 2026).    func testAShortRecordingIsSaidInSecondsAndNeverAsZeroMinutes() {        let offer = MeetingRecoveryOffer(            marker: marker(durationMs: 12_400), isPlayable: true, durationMs: 12_400)        let said = MeetingRecoveryWords.detail(offer)        XCTAssertTrue(said.contains("12 seconds"), said)        XCTAssertFalse(said.contains("0 min"), said)    }    /// A length nothing could answer is "we do not know", never "0 min" — the    /// same rule `MeetingFacts.durationLabel` keeps.    func testARecordingWithNoKnownLengthSaysSoRatherThanZero() {        let offer = MeetingRecoveryOffer(            marker: marker(durationMs: 0), isPlayable: true, durationMs: nil)        let said = MeetingRecoveryWords.detail(offer)        XCTAssertFalse(said.isEmpty)        XCTAssertFalse(said.contains("0 min"), said)    }}