// 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 AVFoundationimportCottonKitimportCottonValuesimport XCTest@testable importCottonUI// MARK: - The doubles@MainActorprivatefinalclassFakeCapture: MeetingCapture {var onInterruption: ((MeetingCaptureInterruption) -> Void)?private(set) var opened: [URL] = []private(set) var log: [String] = []var refusesToOpen = falsevar refusesToResume = falsevar level: Double = 0funcopen(at url: URL) throws {if refusesToOpen { throwMeetingCaptureFailure.wouldNotStart } opened.append(url) log.append("open") }func pause() { log.append("pause") }func resume() throws {if refusesToResume { throwMeetingCaptureFailure.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).privatestructStubExport: MeetingAudioExporting {let refuses: Boolfunc export( _ captured: URL,as named: String, watching: @escaping @Sendable (Double) -> Void ) asyncthrows -> URL {if refuses { throwMeetingAudioExportFailure.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 {privatevar waiting: [CheckedContinuation<Void, Never>] = []privatevar released = falsefunc wait() async {guard !released else { return }await withCheckedContinuation { waiting.append($0) } }func finish() { released = truefor one in waiting { one.resume() } waiting = [] }}privatestructHeldExport: MeetingAudioExporting {let gate: ExportGatefunc export( _ captured: URL,as named: String, watching: @escaping @Sendable (Double) -> Void ) asyncthrows -> URL { watching(0.25)await gate.wait()return captured.deletingLastPathComponent().appendingPathComponent(named) }}/// The App Group's text slots, in memory.privatefinalclassFakeMarkerStorage: ShareMailboxStorage, @unchecked Sendable {privatelet lock = NSLock()privatevar 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() }iflet 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.privatestructTempAudioStore: MeetingAudioStore {let root: URLfinalclassLedger: @unchecked Sendable {privatelet 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) }funcopen(act: String, named: String) throws -> URL {let directory = root.appendingPathComponent(act, isDirectory: true)tryFileManager.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 rigprivatelet start = Date(timeIntervalSince1970: 1_789_000_000)privatelet meetingId = "11111111-2222-4333-8444-555555555555"privatelet createdRoute = Route.meetingsMeeting(id: meetingId)privatelet meetingAnswer = ScriptedCore.Reply.ok( #"{"id":"\#(meetingId)","route":"/meetings/meeting/\#(meetingId)","key":"ws-1/meetings/\#(meetingId)/full.m4a"}"#)@MainActorprivatefinalclassClock {var now = startfunc move(_ seconds: Double) { now = now.addingTimeInterval(seconds) }}@MainActorprivatestructRig {let model: MeetingRecorderModellet capture: FakeCapturelet core: ScriptedCorelet markers: FakeMarkerStoragelet store: TempAudioStorelet clock: Clockvar state: MeetingRecorderStage { model.state.stage }}@MainActorprivatefunc 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 } )returnRig( 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.@MainActorprivatefunc settle( _ model: MeetingRecorderModel, until stage: @escaping (MeetingRecorderStage) -> Bool) asyncthrows {for _ in0..<200 {if stage(model.state.stage) { return }tryawaitTask.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.@MainActorprivatefunc settle(until answered: @escaping () -> Bool) asyncthrows {for _ in0..<200 {if answered() { return }tryawaitTask.sleep(for: .milliseconds(5)) } XCTFail("it never happened")}@MainActorprivatefunc recording(_ rig: Rig) asyncthrows { rig.model.appeared()tryawait settle(rig.model) { $0 == .recording }}// MARK: - The cases@MainActorfinalclassMeetingRecorderModelTests: XCTestCase {func testAskingComesFirstAndTheFileIsOpenedInTheHoldingArea() asyncthrows {let found = rig()tryawait 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() asyncthrows {let found = rig(microphone: .denied) found.model.appeared()tryawait settle(found.model) { ifcase .blocked = $0 { returntrue } else { returnfalse } } 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()asyncthrows {let found = rig() found.model.title = "Board review"tryawait 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() asyncthrows {let found = rig()tryawait recording(found) found.clock.move(120) found.model.stop()tryawait 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() asyncthrows {let found = rig() found.model.title = "Board review"tryawait 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()tryawait 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() asyncthrows {let found = rig(exportRefuses: true)tryawait recording(found) found.clock.move(13) found.model.stop()tryawait settle(found.model) { $0.isFinished }let calls = await found.core.callslet 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() asyncthrows {let found = rig()tryawait 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() asyncthrows {let found = rig()tryawait 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() asyncthrows {let found = rig()tryawait recording(found) found.clock.move(10) found.model.stop()tryawait 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() asyncthrows {let found = rig()tryawait 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() asyncthrows {let found = rig()tryawait 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() asyncthrows {let found = rig()tryawait recording(found) found.capture.interrupt(.began) found.capture.refusesToResume = true found.capture.interrupt(.ended)guardcase .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() asyncthrows {let found = rig( reply: .refuse(code: "too_large", message: "this recording is over the ceiling"))tryawait recording(found) found.clock.move(45) found.model.stop()tryawait settle(found.model) { ifcase .failed = $0 { returntrue } else { returnfalse } } 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()tryawait 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() asyncthrows {let found = rig(reply: .ok(#"{"answer":{"id":"m-1"},"rail":"client","queued":1}"#))tryawait recording(found) found.model.stop()tryawait settle(found.model) { ifcase .failed = $0 { returntrue } else { returnfalse } }guardcase .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() asyncthrows {let found = rig() found.capture.refusesToOpen = true found.model.appeared()tryawait settle(found.model) { ifcase .failed = $0 { returntrue } else { returnfalse } } 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() asyncthrows {let gate = ExportGate()let found = rig(exporter: HeldExport(gate: gate))tryawait recording(found) found.clock.move(20) found.model.stop()tryawait 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()tryawait 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() asyncthrows {let found = rig(reply: .refuse(code: "offline", message: "not connected"))tryawait recording(found)let capture = try XCTUnwrap(found.capture.opened.first)tryData("synthetic".utf8).write(to: capture) found.clock.move(30) found.model.stop()tryawait settle(found.model) { ifcase .failed = $0 { returntrue } else { returnfalse } } 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()tryawait 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() asyncthrows {let found = rig() found.capture.level = 0.7tryawait recording(found) XCTAssertEqual(found.model.meter, [], "nothing is drawn before the first tick")for _ in0..<(MeetingRecorderModel.meterWindow + 20) { found.model.tick() } XCTAssertEqual(found.model.meter.count, MeetingRecorderModel.meterWindow) XCTAssertEqual(found.model.meter.last, 0.7) }}privatestructAskedMeeting: Decodable {let path: Stringlet source: Stringlet title: String?let startedAt: String?let durationMs: Int?let mime: String?}