Cotton code
638 lines · 25.7 KB · SwiftRaw
// A whole recording, driven end to end — with no microphone, no audio session,// no App Group and no clock.//// `MeetingRecorderMachineTests` holds the rules; this holds the WIRING: that// the effects the machine returns actually reach the four seams, in the order// they have to, and that what goes over the boundary at Stop is what the// recording knows about itself.//// Every seam is a double. The microphone is a `FakeCapture` that records what// it was told; the permission is `ScriptedCapabilityAuthority`; the boundary is// a `ScriptedCore` behind a real `ScreenWriter`; the holding area is a// temporary directory; and `now` is a variable this file moves by hand.import AVFoundationimport CottonKitimport CottonValuesimport XCTest@testable import CottonUI// MARK: - The doubles@MainActorprivate final class FakeCapture: MeetingCapture {    var onInterruption: ((MeetingCaptureInterruption) -> Void)?    private(set) var opened: [URL] = []    private(set) var log: [String] = []    var refusesToOpen = false    var refusesToResume = false    var level: Double = 0    func open(at url: URL) throws {        if refusesToOpen { throw MeetingCaptureFailure.wouldNotStart }        opened.append(url)        log.append("open")    }    func pause() { log.append("pause") }    func resume() throws {        if refusesToResume { throw MeetingCaptureFailure.wouldNotStart }        log.append("resume")    }    func close() { log.append("close") }    func meter() -> Double { level }    /// The OS, doing what only the OS can.    func interrupt(_ kind: MeetingCaptureInterruption) { onInterruption?(kind) }}/// The encode that turns the capture file into the one that gets filed./// Renames rather than transcodes, and reports the two ends of the fraction;/// refuses on demand, which is the killed-capture case/// (`MeetingAudioDeliveryTests` has the measurements).private struct StubExport: MeetingAudioExporting {    let refuses: Bool    func export(        _ captured: URL,        as named: String,        watching: @escaping @Sendable (Double) -> Void    ) async throws -> URL {        if refuses { throw MeetingAudioExportFailure.wouldNotExport }        watching(0.5)        watching(1)        return captured.deletingLastPathComponent().appendingPathComponent(named)    }}/// An export that waits to be let go, so a test can stand inside the/// "finishing…" stage and look at it.private actor ExportGate {    private var waiting: [CheckedContinuation<Void, Never>] = []    private var released = false    func wait() async {        guard !released else { return }        await withCheckedContinuation { waiting.append($0) }    }    func finish() {        released = true        for one in waiting { one.resume() }        waiting = []    }}private struct HeldExport: MeetingAudioExporting {    let gate: ExportGate    func export(        _ captured: URL,        as named: String,        watching: @escaping @Sendable (Double) -> Void    ) async throws -> URL {        watching(0.25)        await gate.wait()        return captured.deletingLastPathComponent().appendingPathComponent(named)    }}/// The App Group's text slots, in memory.private final class FakeMarkerStorage: ShareMailboxStorage, @unchecked Sendable {    private let lock = NSLock()    private var values: [String: String] = [:]    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) }    }}/// The holding area, under a temporary directory rather than an App Group the/// test process does not have.private struct TempAudioStore: MeetingAudioStore {    let root: URL    final class Ledger: @unchecked Sendable {        private let lock = NSLock()        private(set) var discarded: [String] = []        func drop(_ act: String) {            lock.lock()            defer { lock.unlock() }            discarded.append(act)        }    }    let ledger = Ledger()    func captures() -> [MeetingCaptureOnDisk] { MeetingFiles.captures(under: root) }    func open(act: String, named: String) throws -> URL {        let directory = root.appendingPathComponent(act, isDirectory: true)        try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true)        return directory.appendingPathComponent(named)    }    func discard(act: String) {        ledger.drop(act)        try? FileManager.default.removeItem(at: root.appendingPathComponent(act, isDirectory: true))    }}// MARK: - The rigprivate let start = Date(timeIntervalSince1970: 1_789_000_000)private let meetingId = "11111111-2222-4333-8444-555555555555"private let createdRoute = Route.meetingsMeeting(id: meetingId)private let meetingAnswer = ScriptedCore.Reply.ok(    #"{"id":"\#(meetingId)","route":"/meetings/meeting/\#(meetingId)","key":"ws-1/meetings/\#(meetingId)/full.m4a"}"#)@MainActorprivate final class Clock {    var now = start    func move(_ seconds: Double) { now = now.addingTimeInterval(seconds) }}@MainActorprivate struct Rig {    let model: MeetingRecorderModel    let capture: FakeCapture    let core: ScriptedCore    let markers: FakeMarkerStorage    let store: TempAudioStore    let clock: Clock    var state: MeetingRecorderStage { model.state.stage }}@MainActorprivate func rig(    microphone: CapabilityAccess = .authorized,    reply: ScriptedCore.Reply = meetingAnswer,    exportRefuses: Bool = false,    exporter: (any MeetingAudioExporting)? = nil,    tickEvery: Duration = .seconds(10)) -> Rig {    let core = ScriptedCore([CottonMethod.meetingsCreate: reply])    let capture = FakeCapture()    let markers = FakeMarkerStorage()    let clock = Clock()    let store = TempAudioStore(        root: FileManager.default.temporaryDirectory            .appendingPathComponent("cotton-meetings-\(UUID().uuidString)", isDirectory: true)    )    let model = MeetingRecorderModel(        writer: ScreenWriter(core: core),        capture: capture,        authority: ScriptedCapabilityAuthority(statuses: [.microphone: microphone]),        recovery: MeetingRecoveryStore(storage: markers),        files: store,        exporter: exporter ?? StubExport(refuses: exportRefuses),        // The display loop is not what most of these cases are about, and a        // ten-second tick keeps it from firing inside one. The checkpoint cases        // drive `tick()` by hand instead.        tickEvery: tickEvery,        now: { clock.now }    )    return Rig(        model: model, capture: capture, core: core,        markers: markers, store: store, clock: clock)}/// The machine's effects run through `Task`s in two places — the gate and the/// create — so a case waits for the stage it is about to assert on rather than/// sleeping.@MainActorprivate func settle(    _ model: MeetingRecorderModel,    until stage: @escaping (MeetingRecorderStage) -> Bool) async throws {    for _ in 0..<200 {        if stage(model.state.stage) { return }        try await Task.sleep(for: .milliseconds(5))    }    XCTFail("the recorder stayed at \(model.state.stage)")}/// The same, for anything that is not a stage — a fraction the export reported,/// a file that appeared.@MainActorprivate func settle(until answered: @escaping () -> Bool) async throws {    for _ in 0..<200 {        if answered() { return }        try await Task.sleep(for: .milliseconds(5))    }    XCTFail("it never happened")}@MainActorprivate func recording(_ rig: Rig) async throws {    rig.model.appeared()    try await settle(rig.model) { $0 == .recording }}// MARK: - The cases@MainActorfinal class MeetingRecorderModelTests: XCTestCase {    func testAskingComesFirstAndTheFileIsOpenedInTheHoldingArea() async throws {        let found = rig()        try await recording(found)        XCTAssertEqual(found.capture.log, ["open"])        let file = try XCTUnwrap(found.capture.opened.first)        // **The CAPTURE container**, which is the one that survives a kill —        // the MPEG-4 is encoded from it at Stop (`MeetingAudioExport.swift`).        XCTAssertEqual(file.pathExtension, "caf")        XCTAssertTrue(            file.path.contains(found.model.act),            "the audio sits in the act's own directory, so a marker and its bytes stay matchable"        )    }    /// **A refusal is a state.** Nothing platform is built, and nothing retries.    func testADeniedMicrophoneOpensNothing() async throws {        let found = rig(microphone: .denied)        found.model.appeared()        try await settle(found.model) { if case .blocked = $0 { return true } else { return false } }        XCTAssertEqual(found.state, .blocked(.microphone, .denied))        XCTAssertEqual(found.capture.log, [], "the microphone was never touched")        XCTAssertNil(MeetingRecoveryStore(storage: found.markers).markers().first)    }    // ── The marker, at every transition ───────────────────────────────────    func testTheMarkerIsWrittenAsSoonAsAnythingIsCapturedAndFollowsEachTransition()        async throws    {        let found = rig()        found.model.title = "Board review"        try await recording(found)        let store = MeetingRecoveryStore(storage: found.markers)        let atStart = try XCTUnwrap(store.markers().first)        XCTAssertEqual(atStart.recoveryStage, .recording)        XCTAssertEqual(atStart.id, found.model.act)        XCTAssertEqual(atStart.title, "Board review")        XCTAssertEqual(atStart.startedAt, CottonDate.format(start))        // The marker names the CAPTURE file: it is the one that exists while a        // recording is running, and the one recovery has to find.        XCTAssertTrue(atStart.path.hasSuffix("audio.caf"))        found.clock.move(90)        found.model.pause()        let paused = try XCTUnwrap(store.markers().first)        XCTAssertEqual(paused.recoveryStage, .paused)        XCTAssertEqual(paused.durationMs, 90_000, "and it remembers what was captured")    }    func testTheMarkerIsClearedAndTheCopyDroppedOnlyWhenTheMeetingExists() async throws {        let found = rig()        try await recording(found)        found.clock.move(120)        found.model.stop()        try await settle(found.model) { $0.isFinished }        XCTAssertEqual(found.state, .saved(createdRoute))        XCTAssertNil(            MeetingRecoveryStore(storage: found.markers).markers().first,            "the row exists, so the marker has done its job"        )        XCTAssertEqual(found.store.ledger.discarded, [found.model.act])    }    // ── What goes over the boundary ───────────────────────────────────────    func testStopSendsThePathTheStartAndWhatWasActuallyCaptured() async throws {        let found = rig()        found.model.title = "Board review"        try await recording(found)        found.clock.move(60)        found.model.pause()        found.clock.move(600)  // ten minutes of nothing        found.model.resume()        found.clock.move(30)        found.model.stop()        try await settle(found.model) { $0.isFinished }        let calls = await found.core.calls        XCTAssertEqual(calls.map(\.method), [CottonMethod.meetingsCreate])        let sent = try JSONDecoder().decode(            AskedMeeting.self, from: Data(calls[0].requestJSON.utf8))        XCTAssertEqual(sent.source, "record")        XCTAssertEqual(sent.title, "Board review")        XCTAssertEqual(sent.startedAt, CottonDate.format(start))        XCTAssertEqual(sent.mime, "audio/mp4")        XCTAssertEqual(            sent.durationMs, 90_000,            "ninety seconds of audio, not the eleven and a half minutes the screen was up"        )        XCTAssertTrue(sent.path.hasSuffix("audio.m4a"), "the ENCODE is what is filed, not the capture")    }    /// The capture file a kill tore off may refuse to export — the measurement    /// is in `MeetingAudioDeliveryTests`. It is still filed, as it is, and the    /// type follows the file: `.caf` is a container the crate accepts, and a    /// recording nobody can file is the worse failure.    func testACaptureThatWillNotExportIsStillFiledAsRecorded() async throws {        let found = rig(exportRefuses: true)        try await recording(found)        found.clock.move(13)        found.model.stop()        try await settle(found.model) { $0.isFinished }        let calls = await found.core.calls        let sent = try JSONDecoder().decode(            AskedMeeting.self, from: Data(calls[0].requestJSON.utf8))        XCTAssertTrue(sent.path.hasSuffix("audio.caf"))        XCTAssertEqual(sent.mime, "audio/x-caf", "never audio/mp4 over CAF bytes")        XCTAssertEqual(found.state, .saved(createdRoute))    }    // ── The marker, between transitions ───────────────────────────────────    /// **The checkpoint.** The marker is otherwise banked at transitions only,    /// so a recording the OS killed mid-run carried whatever was true a moment    /// after capture opened — the walk of 15 Sep 2026 was offered "about 1    /// second" over thirteen. The capture file's own length is the first    /// answer, and a killed CAF gives 0.000 s, so this is the one that ends up    /// on the slip.    func testTheRunningFigureIsCheckpointedIntoTheMarkerEveryFiveSeconds() async throws {        let found = rig()        try await recording(found)        let store = MeetingRecoveryStore(storage: found.markers)        XCTAssertEqual(try XCTUnwrap(store.markers().first).durationMs, 0)        // Four seconds in, one tick: too soon, and the marker still says what        // the start said.        found.clock.move(4)        found.model.tick()        XCTAssertEqual(try XCTUnwrap(store.markers().first).durationMs, 0)        // Six: the checkpoint is owed and the marker moves.        found.clock.move(2)        found.model.tick()        XCTAssertEqual(try XCTUnwrap(store.markers().first).durationMs, 6_000)        XCTAssertEqual(try XCTUnwrap(store.markers().first).recoveryStage, .recording)        // And it is a CADENCE, not every tick: a second later, nothing.        found.clock.move(1)        found.model.tick()        XCTAssertEqual(try XCTUnwrap(store.markers().first).durationMs, 6_000)        found.clock.move(5)        found.model.tick()        XCTAssertEqual(try XCTUnwrap(store.markers().first).durationMs, 12_000)    }    /// A pause banks the figure itself, and the tick does not run while paused    /// — so nothing checkpoints over the stage the person is actually in.    func testNothingIsCheckpointedWhileThePersonHasPaused() async throws {        let found = rig()        try await recording(found)        found.clock.move(30)        found.model.pause()        let store = MeetingRecoveryStore(storage: found.markers)        XCTAssertEqual(try XCTUnwrap(store.markers().first).recoveryStage, .paused)        found.clock.move(60)        found.model.tick()        XCTAssertEqual(try XCTUnwrap(store.markers().first).recoveryStage, .paused)        XCTAssertEqual(try XCTUnwrap(store.markers().first).durationMs, 30_000)    }    /// The crate writes no title for a recording it was not given one for, and    /// the summariser writes a real one when the meeting goes ready. A screen    /// that sent its placeholder would name every meeting the same thing.    func testAnUntypedNameIsNotSentAtAll() async throws {        let found = rig()        try await recording(found)        found.clock.move(10)        found.model.stop()        try await settle(found.model) { $0.isFinished }        let calls = await found.core.calls        XCTAssertFalse(calls[0].requestJSON.contains("title"), calls[0].requestJSON)    }    // ── A phone call ──────────────────────────────────────────────────────    func testAPhoneCallPausesCaptureAndGivingTheMicrophoneBackResumesIt() async throws {        let found = rig()        try await recording(found)        found.clock.move(20)        found.capture.interrupt(.began)        XCTAssertEqual(found.state, .paused(.interruption))        XCTAssertEqual(found.capture.log, ["open", "pause"])        found.clock.move(40)        found.capture.interrupt(.ended)        XCTAssertEqual(found.state, .recording)        XCTAssertEqual(found.capture.log, ["open", "pause", "resume"])    }    /// A call ending never resumes a recording the person deliberately paused.    func testAnEndedCallDoesNotLiftThePersonsOwnPause() async throws {        let found = rig()        try await recording(found)        found.model.pause()        found.capture.interrupt(.ended)        XCTAssertEqual(found.state, .paused(.person))        XCTAssertEqual(found.capture.log, ["open", "pause"], "nothing resumed")    }    /// The session may still belong to the call. That is visible, not    /// swallowed — and the file is still there to file.    func testASessionThatWillNotComeBackIsAFailureWithTheAudioIntact() async throws {        let found = rig()        try await recording(found)        found.capture.interrupt(.began)        found.capture.refusesToResume = true        found.capture.interrupt(.ended)        guard case .failed(let why) = found.state else {            return XCTFail("expected a failure, got \(found.state)")        }        XCTAssertTrue(why.contains("microphone"), why)        XCTAssertNotNil(            MeetingRecoveryStore(storage: found.markers).markers().first,            "the marker still names the file, so the next launch offers it"        )        XCTAssertEqual(found.store.ledger.discarded, [], "and nothing deleted the audio")    }    // ── A refusal at Stop ─────────────────────────────────────────────────    func testARefusedCreateKeepsTheFileTheMarkerAndARetry() async throws {        let found = rig(            reply: .refuse(code: "too_large", message: "this recording is over the ceiling"))        try await recording(found)        found.clock.move(45)        found.model.stop()        try await settle(found.model) { if case .failed = $0 { return true } else { return false } }        XCTAssertEqual(found.state, .failed("this recording is over the ceiling"))        XCTAssertEqual(            found.store.ledger.discarded, [],            "bytes nobody else is holding are not deleted because a call failed"        )        let held = try XCTUnwrap(MeetingRecoveryStore(storage: found.markers).markers().first)        XCTAssertEqual(held.recoveryStage, .closed, "and the file was closed, so it will play")        await found.core.answer(CottonMethod.meetingsCreate, meetingAnswer)        found.model.retry()        try await settle(found.model) { $0.isFinished }        XCTAssertEqual(found.state, .saved(createdRoute))        XCTAssertEqual(found.store.ledger.discarded, [found.model.act])    }    /// **An answer the app cannot read is a SENTENCE on the sheet, never the    /// answer itself.**    ///    /// The walk of 15 Sep 2026 read the FFI's write envelope — braces, quotes    /// and an object key — written in red handwriting on the record screen    /// where the reason a recording had not been filed belonged. The crate's    /// answer shape is fixed; this is what stops the next one being drawn.    func testAnAnswerTheAppCannotReadIsASentenceAndNotItsOwnJSON() async throws {        let found = rig(reply: .ok(#"{"answer":{"id":"m-1"},"rail":"client","queued":1}"#))        try await recording(found)        found.model.stop()        try await settle(found.model) { if case .failed = $0 { return true } else { return false } }        guard case .failed(let why) = found.state else {            return XCTFail("expected a failure, got \(found.state)")        }        XCTAssertFalse(why.contains("{"), "no JSON on the sheet: \(why)")        XCTAssertFalse(why.contains("rail"), why)        XCTAssertFalse(why.contains("\"id\""), why)        XCTAssertTrue(why.hasSuffix("."), "a sentence: \(why)")        XCTAssertEqual(            found.store.ledger.discarded, [],            "and the recording is still there, with a retry on the screen")    }    // ── The microphone that will not open ─────────────────────────────────    func testAMicrophoneThatWillNotStartIsAFailureAndNotASilentIdleScreen() async throws {        let found = rig()        found.capture.refusesToOpen = true        found.model.appeared()        try await settle(found.model) { if case .failed = $0 { return true } else { return false } }        XCTAssertNil(MeetingRecoveryStore(storage: found.markers).markers().first, "nothing was captured")    }    // ── Finishing: the encode between Stop and the call ───────────────────    /// **The screen says so while it runs.** The capture is linear PCM and what    /// is filed is an AAC `.m4a` encoded from it, which on a long meeting is a    /// transcode a person waits through; a sheet that said "filing…" through it    /// would be a sheet that looks stuck.    func testStopShowsTheFinishingStageWhileTheCaptureIsBeingEncoded() async throws {        let gate = ExportGate()        let found = rig(exporter: HeldExport(gate: gate))        try await recording(found)        found.clock.move(20)        found.model.stop()        try await settle(until: { found.model.exportProgress > 0 })        XCTAssertEqual(found.state, .finishing)        XCTAssertEqual(found.capture.log, ["open", "close"], "the file is closed first")        XCTAssertEqual(found.model.exportProgress, 0.25, "the sheet draws the export's own fraction")        let asked = await found.core.calls        XCTAssertTrue(asked.isEmpty, "nothing is filed until there is a file to file")        await gate.finish()        try await settle(found.model) { $0.isFinished }        XCTAssertEqual(found.state, .saved(createdRoute))    }    /// **The capture is deleted only once the meeting exists.** Not when the    /// export lands — a `meetings.create` that then failed would have taken the    /// only copy of the audio with it.    func testThePcmCaptureOutlivesTheExportAndGoesOnlyOnceTheMeetingExists() async throws {        let found = rig(reply: .refuse(code: "offline", message: "not connected"))        try await recording(found)        let capture = try XCTUnwrap(found.capture.opened.first)        try Data("synthetic".utf8).write(to: capture)        found.clock.move(30)        found.model.stop()        try await settle(found.model) { if case .failed = $0 { return true } else { return false } }        XCTAssertTrue(            FileManager.default.fileExists(atPath: capture.path(percentEncoded: false)),            "the export landed and the call did not — the capture is the only copy left"        )        XCTAssertEqual(found.store.ledger.discarded, [])        await found.core.answer(CottonMethod.meetingsCreate, meetingAnswer)        found.model.retry()        try await settle(found.model) { $0.isFinished }        XCTAssertEqual(            found.store.ledger.discarded, [found.model.act],            "and now the crate has the bytes, the whole act's directory goes"        )        XCTAssertFalse(FileManager.default.fileExists(atPath: capture.path(percentEncoded: false)))    }    // ── What the microphone is actually told to write ─────────────────────    /// **Linear PCM, 16-bit, mono, 24 kHz.** The whole of the fix of 16 Sep    /// 2026: AAC inside a CAF reads `audio packets: 0` after a kill, because its    /// packet table is only written at `stop()`, while PCM's fixed-size packets    /// need no table at all. The measurements are in `MeetingAudioDeliveryTests`    /// and Cotton note "The phone and Mac app — how a screen is built".    func testTheMicrophoneIsToldToWriteLinearPcm() {        let settings = SystemMeetingRecorder.settings        XCTAssertEqual(settings[AVFormatIDKey] as? Int, Int(kAudioFormatLinearPCM))        XCTAssertEqual(settings[AVSampleRateKey] as? Double, 24_000)        XCTAssertEqual(settings[AVNumberOfChannelsKey] as? Int, 1)        XCTAssertEqual(settings[AVLinearPCMBitDepthKey] as? Int, 16)        XCTAssertEqual(settings[AVLinearPCMIsFloatKey] as? Bool, false)        XCTAssertNil(            settings[AVEncoderBitRateKey],            "there is no encoder in the capture path any more — the encode happens at Stop")    }    // ── The strip ─────────────────────────────────────────────────────────    /// The only waveform in this app drawn from real bytes. It is a DISPLAY    /// loop: the elapsed figure that reaches the wire is the machine's banked    /// arithmetic, not whatever the last tick stored.    func testTheStripFillsFromTheMicrophoneAndIsCappedToOneScreensWorth() async throws {        let found = rig()        found.capture.level = 0.7        try await recording(found)        XCTAssertEqual(found.model.meter, [], "nothing is drawn before the first tick")        for _ in 0..<(MeetingRecorderModel.meterWindow + 20) { found.model.tick() }        XCTAssertEqual(found.model.meter.count, MeetingRecorderModel.meterWindow)        XCTAssertEqual(found.model.meter.last, 0.7)    }}private struct AskedMeeting: Decodable {    let path: String    let source: String    let title: String?    let startedAt: String?    let durationMs: Int?    let mime: String?}