Cotton code
376 lines · 16.1 KB · SwiftRaw
// The recorder's effects — the model between `MeetingRecorderMachine` and the// four things that actually happen.//// The machine decides; this runs what it decided, against three seams and// nothing else: the microphone (`MeetingCapture`), the OS's permission// (`CapabilityAuthority`) and the boundary (`ScreenWriter`). Every one of them is injected, so a whole// recording — start, a phone call, a resume, Stop, a refusal, a retry — runs in// a test with no microphone, no session, no XCFramework and no clock.//// **Nothing here reads the wall clock.** `now` is a closure, and every event// the machine takes carries the instant it happened at. A recorder tested// against `Date()` is a test that is approximately right, which for an elapsed// figure is the same as wrong.//// ── The tick ─────────────────────────────────────────────────────────────────//// One loop while capture is open, ten times a second: it moves the elapsed// stamp, pushes one meter reading into a rolling window the waveform draws,// and — once every five seconds, never per tick — writes the running figure// into the recovery marker (`checkpointEvery`).//// **Nothing the recording produces depends on the loop.** The elapsed figure// sent to `meetings.create` is the machine's own banked arithmetic, read at// Stop, not whatever the last tick happened to store; the checkpoint is the// LAST-resort answer for a recording that never reached Stop at all, behind the// capture file's own length.import CottonKitimport CottonValuesimport Foundationimport SwiftUI@MainActor@Observablefinal class MeetingRecorderModel {    /// What the machine says is happening.    private(set) var state = MeetingRecorderState()    /// The elapsed stamp, moved by the tick.    private(set) var elapsedMs: Double = 0    /// How far the encode has got, 0…1 — what the sheet's progress line draws    /// while the stage is `.finishing`. It is the export session's own figure    /// (`MeetingAudioExport.swift`), never a guess from a timer.    private(set) var exportProgress: Double = 0    /// The live meter, newest LAST — what the strip draws. Capped, so an hour    /// of recording is still one screen's worth of bars.    private(set) var meter: [Double] = []    /// What the person has typed. Empty means "you name it": the crate writes    /// no title for a recording, and the screens draw the day for a row that    /// has none.    var title = ""    /// The act this recording is — the directory its audio lives in, and what    /// the recovery marker is tied to.    private(set) var act = MeetingFiles.newActId()    /// The boundary the meeting is filed through — and the one the meetings    /// list under the recorder sheet reads through (`MeetingListFlow`).    let writer: ScreenWriter    private let capture: any MeetingCapture    private let authority: any CapabilityAuthority    private let recovery: MeetingRecoveryStore    private let files: any MeetingAudioStore    private let exporter: any MeetingAudioExporting    private let now: () -> Date    private let tickEvery: Duration    /// Where this recording is being written. Set when capture opens.    private var audioPath: String?    /// The file `meetings.create` is handed, and the type to declare with it —    /// decided once by the encode, and kept, so a refused create retried on the    /// same screen does not transcode the whole recording a second time.    private var delivered: (path: String, mime: String?)?    private var ticker: Task<Void, Never>?    /// When the marker last had the running figure written into it. See    /// ``checkpointEvery``.    private var checkpointedAt: Date?    /// How many bars the strip holds. Enough to fill the widest player on a Mac    /// column at the pitch the meeting list already draws.    static let meterWindow = 180    /// How often the running elapsed figure is written into the recovery    /// marker.    ///    /// **The marker is otherwise banked at TRANSITIONS only** — start, pause,    /// resume, stop — which is exactly right for a recording that ends and    /// useless for one the OS killed while it ran: the marker then says what    /// was true a moment after capture opened. The walk of 15 Sep 2026 killed a    /// recording at 0:13 and was offered "about 1 second".    ///    /// The file's own length is the first answer and this is the second    /// (`MeetingRecovery.length(of:probing:)`), because a capture file torn    /// off mid-packet may still refuse to give a duration. Five seconds is the    /// granularity of the sentence on the slip; a per-tick write would be ten    /// defaults writes a second for a number nobody reads until the next    /// launch.    static let checkpointEvery: TimeInterval = 5    init(        writer: ScreenWriter,        capture: any MeetingCapture,        authority: any CapabilityAuthority,        recovery: MeetingRecoveryStore = MeetingRecoveryStore(),        files: any MeetingAudioStore = AppGroupMeetingAudioStore(),        exporter: any MeetingAudioExporting = SystemMeetingAudioExport(),        tickEvery: Duration = .milliseconds(100),        now: @escaping () -> Date = Date.init    ) {        self.writer = writer        self.capture = capture        self.authority = authority        self.recovery = recovery        self.files = files        self.exporter = exporter        self.tickEvery = tickEvery        self.now = now        capture.onInterruption = { [weak self] kind in            guard let self else { return }            self.send(kind == .began ? .interrupted(at: self.now()) : .interruptionEnded(at: self.now()))        }    }    // ── What the screen calls ─────────────────────────────────────────────    func appeared() { send(.appeared) }    func pause() { send(.personPaused(at: now())) }    func resume() { send(.personResumed(at: now())) }    func stop() { send(.personStopped(at: now())) }    func retry() { send(.retry) }    /// Whether the person threw this recording away (`discard`): the screen    /// leaves, and nothing more is heard from the microphone.    private(set) var discarded = false    /// The person's own Discard, while the microphone is open or paused: the    /// capture closes, its bytes and its recovery marker go, and nothing is    /// filed. The one other path that deletes a recording is Discard on the    /// recovery slip.    func discard() {        switch state.stage {        case .recording, .paused: break        default: return        }        // Whatever an earlier step decided is about a recording that is over.        generation += 1        discarded = true        stopTicking()        capture.close()        recovery.clear(id: act)        files.discard(act: act)    }    /// The screen is going away for good.    ///    /// **It does not stop a recording.** Leaving the screen while recording is    /// not something the screen offers — there is no back circle while capture    /// is open — and a teardown that quietly closed the file would turn a    /// SwiftUI redraw into a lost meeting. What it does is stop the display    /// loop, which is all it owns.    func disappeared() {        ticker?.cancel()        ticker = nil    }    // ── The machine, and its effects ──────────────────────────────────────    /// Which `send` is the current one. An effect may raise an event of its own    /// — the microphone refusing to resume is the case that matters — and when    /// it does, the effects the earlier step decided on are about a stage that    /// is now over. Running them anyway would re-mark a recording that stopped.    private var generation = 0    private func send(_ event: MeetingRecorderEvent) {        // A recording thrown away hears nothing more (a late interruption).        guard !discarded else { return }        generation += 1        let mine = generation        let effects = MeetingRecorderMachine.step(&state, event)        elapsedMs = state.elapsedMs(at: now())        for effect in effects {            run(effect)            guard generation == mine else { return }        }    }    private func run(_ effect: MeetingRecorderEffect) {        switch effect {        case .askForMicrophone:            Task { [authority] in                let answer = await authority.gate([.microphone])                self.send(.gate(answer))            }        case .openCapture:            do {                let file = try files.open(act: act, named: MeetingFiles.capturedFileName)                try capture.open(at: file)                audioPath = file.path(percentEncoded: false)                send(.captureOpened(at: now()))                startTicking()            } catch {                // The take never started: its holding folder goes with it, so                // the list offers no "wasn't saved" card for a recording                // that holds nothing.                files.discard(act: act)                send(.captureFailed(at: now(), why: sentence(error)))            }        case .pauseCapture:            capture.pause()            stopTicking()        case .resumeCapture:            do {                try capture.resume()                startTicking()            } catch {                send(.captureFailed(at: now(), why: sentence(error)))            }        case .closeCapture:            stopTicking()            capture.close()            send(.captureClosed(at: now()))        case .prepareAudio:            Task { await prepareAudio() }        case .create:            Task { await create() }        case .mark(let stage):            guard let audioPath, let startedAt = state.startedAt else { return }            // Every write resets the checkpoint clock — a transition has just            // banked the figure, so the next checkpoint is owed five seconds            // from here rather than five seconds from the last tick.            checkpointedAt = now()            recovery.write(                MeetingRecoveryMarker(                    id: act,                    path: audioPath,                    startedAt: CottonDate.format(startedAt),                    title: title.isBlank ? nil : title,                    durationMs: state.elapsed(at: now()),                    stage: stage                )            )        case .clearMark:            recovery.clear(id: act)            // The crate has copied the bytes into the store, so this app's copy            // has done its job. The ONLY other path that deletes a recording is            // the person's own Discard on the recovery slip.            files.discard(act: act)        }    }    /// **The capture becomes the file that is filed.**    ///    /// The capture is linear PCM in a CAF — the format a killed process leaves    /// readable — and what a meeting is delivered in is an AAC `.m4a` encoded    /// from it. That is a transcode over the whole recording, so the sheet has a    /// stage for it and the session's own fraction is what the progress line    /// draws.    ///    /// **An export that fails is not a failure**: the capture file is a    /// container the crate accepts, so it is filed as it is    /// (`MeetingAudioDelivery`). Either way the machine hears one event, because    /// either way there is now a file to file.    private func prepareAudio() async {        guard let audioPath else { return send(.audioPrepared) }        if delivered != nil { return send(.audioPrepared) }        exportProgress = 0        delivered = await MeetingAudioDelivery.prepare(            audioPath,            exporting: exporter,            watching: { [weak self] fraction in                Task { @MainActor in self?.exportProgress = fraction }            }        )        send(.audioPrepared)    }    /// `meetings.create`, with what the recording knows about itself.    ///    /// **A refusal keeps everything**: the file, the marker, and a stage that    /// carries a retry. The crate's own sentence is what the screen shows —    /// the ceiling and the accepted containers are its rules.    private func create() async {        guard let audioPath, let startedAt = state.startedAt else {            send(.refused(ShellLines.line("capture", "meeting.nothing_to_file")))            return        }        // Decided by the encode (`prepareAudio`), never here: the marker still        // names the CAPTURE, so a refusal retried later goes back through that        // step rather than depending on a file some earlier attempt made.        let filed = delivered ?? (path: audioPath, mime: MeetingAudioFormats.mime(forFileName: audioPath))        do {            let created = try await writer.call(                CottonMethod.meetingsCreate,                MeetingCreateRequest(                    path: filed.path,                    source: .record,                    // Sent only when the person typed one. The crate draws no                    // English for a recording's title and the summariser writes                    // a real one when the meeting goes ready; a placeholder sent                    // as a value would be this screen naming every meeting the                    // same thing.                    title: title,                    startedAt: CottonDate.format(startedAt),                    durationMs: state.elapsed(at: now()),                    // **The type follows the FILE that is being sent**, not a                    // constant: an export that could not run files the capture                    // file itself, and telling the crate `audio/mp4` over CAF                    // bytes would be this phone lying about its own recording.                    mime: filed.mime                ),                as: MeetingCreated.self            )            send(.created(created.landing))        } catch let error as CottonCallError {            send(.refused(error.message))        } catch {            send(.refused(sentence(error)))        }    }    // ── The display loop ──────────────────────────────────────────────────    private func startTicking() {        guard ticker == nil else { return }        ticker = Task { [weak self] in            guard let self else { return }            while !Task.isCancelled {                try? await Task.sleep(for: self.tickEvery)                guard !Task.isCancelled else { return }                await MainActor.run { self.tick() }            }        }    }    private func stopTicking() {        ticker?.cancel()        ticker = nil    }    /// One frame of the display loop. Internal rather than private so a test    /// drives the strip a tick at a time instead of sleeping — the loop is the    /// one thing here that a clock closure cannot fake.    func tick() {        guard state.stage.isCapturing else { return }        elapsedMs = state.elapsedMs(at: now())        meter.append(capture.meter())        if meter.count > Self.meterWindow { meter.removeFirst(meter.count - Self.meterWindow) }        checkpointMarker()    }    /// Write the running elapsed figure into the recovery marker, at most once    /// every ``checkpointEvery`` seconds. See that constant for why.    private func checkpointMarker() {        let at = now()        if let checkpointedAt, at.timeIntervalSince(checkpointedAt) < Self.checkpointEvery {            return        }        checkpointedAt = at        run(.mark(.recording))    }    /// An error as a sentence somebody can read. `LocalizedError` first,    /// because every failure this file raises is one; the description is the    /// last resort rather than the first, since `String(describing:)` on an    /// `NSError` is a paragraph of domain and code.    private func sentence(_ error: Error) -> String {        (error as? LocalizedError)?.errorDescription ?? String(describing: error)    }}