// The recorder's decision layer — PURE, so every rule the "never lose audio" // promise rests on is testable without a microphone, a session or a clock. // // The model owns effects and nothing else: it turns the screen's taps and the // OS's notifications into events, hands them here, and runs the effects that // come back. Everything that DECIDES — what a phone call does to an open // recording, whether an ended interruption resumes, what Stop does from a // paused state, where the elapsed figure comes from — lives in this file. // // It is a cut-down descendant of the previous runtime's recorder machine // (deleted in 1b6523df; `src/tools/meetings/recorder/machine.ts`). That one // rotated segments, because it uploaded while it recorded. This one writes ONE // file and hands the path over at Stop, so rotation, the manifest, the gap // ledger and the upload queue are all gone — the crate copies the file and the // device-local `_media` ledger carries the upload, which is the same lane every // other byte on this phone already rides. // // THE THREE RULES THAT SURVIVED, and they survived because each one was learnt // the expensive way: // // 1. **A person's pause is STICKY.** A call ending, or an interruption // ending, never resumes a recording the person deliberately paused. Only // the person's own Resume does. // 2. **An ended interruption ALWAYS attempts a resume.** iOS routinely omits // the `.shouldResume` option after a phone call, and treating that flag as // a gate is how a recording stays silently paused for the rest of a // meeting. The flag is telemetry; it is not read here at all, which is why // no event carries it. // 3. **A refusal at Stop is not the end of the audio.** The file stays, the // recovery marker stays, and the stage is a failure a person can retry — // never a state that deletes bytes because a call did not answer. // // The elapsed figure is BANKED plus RUNNING: whole spans that are over, plus // the span that is not. Nothing here reads a clock — `elapsedMs(at:)` takes its // `now`, so a fixed-`now` test is exact rather than approximately right. import Foundation /// Why a recording is paused. Not decoration: the two answer an ended /// interruption differently (rule 1), and they say different things on screen. public enum MeetingPause: Equatable, Sendable { /// The person tapped Pause. case person /// The OS took the microphone — a phone call, another app's session. case interruption } /// Where the recorder stands. public enum MeetingRecorderStage: Equatable, Sendable { /// Nothing has been asked for yet. case idle /// The microphone prompt is up, or the standing answer is being read. case asking /// **A refusal is a STATE, not an error.** Nothing retries against a /// decision only the person can make; the screen says which capability and /// offers Settings when Settings would help. case blocked(DeviceCapability, CapabilityAccess) /// Permission is in hand and the file is being opened. case opening case recording case paused(MeetingPause) /// Stop was tapped: the file is closing, and then the capture is being /// ENCODED into the container a meeting is filed in. /// /// **A stage of its own because it takes time.** The capture is linear PCM /// — the only format a killed process leaves readable — and what is filed /// is an AAC `.m4a` made from it, which is a real transcode over a file /// that may be hundreds of megabytes. A person watching a screen say /// "filing…" for a minute is a person watching a screen that looks stuck. case finishing /// The audio is ready and `meetings.create` is in flight. case saving /// The recorder or the crate said no. **The audio is still on disk** and /// the marker still names it, so this stage carries a retry. case failed(String) /// The meeting exists. The screen hands this route to the navigator, which /// REPLACES the recorder in the stack — going back to a finished recorder /// would be going back to a microphone that is no longer open. case saved(Route) /// True while the microphone is actually open — what the meter and the /// "don't leave" rule key on. public var isCapturing: Bool { self == .recording } /// True once nothing more will happen without the person. public var isFinished: Bool { if case .saved = self { return true } return false } } /// What the machine asks the model to do. public enum MeetingRecorderEffect: Equatable, Sendable { /// Gate the microphone — `CapabilityAuthority`, never an OS call of the /// model's own. case askForMicrophone /// Configure the session and open the file. Nothing platform is built /// before this, which is the app's one order (`DeviceCapability.swift`). case openCapture case pauseCapture case resumeCapture case closeCapture /// Encode the capture into the container a meeting is delivered in, and /// decide which file is actually filed (`MeetingAudioDelivery`). It never /// fails: an export that will not run files the capture as recorded. case prepareAudio /// `meetings.create`, with the path, the start and the elapsed figure. case create /// Write the recovery marker at this stage. Every transition writes one: /// the transition nobody wrote down is the one the crash happens after. case mark(MeetingRecoveryStage) /// The meeting exists; the marker has done its job. case clearMark } /// Everything that happens to a recording. public enum MeetingRecorderEvent: Equatable, Sendable { /// The screen appeared. case appeared case gate(CapabilityGateResult) /// The file is open and bytes are reaching it. case captureOpened(at: Date) /// The session or the file would not open, or fell over mid-recording. /// It carries its instant for the same reason every other event does: the /// running span has to be banked somewhere truthful, and "when it broke" is /// the only honest end for it. case captureFailed(at: Date, why: String) case personPaused(at: Date) case personResumed(at: Date) /// The OS took the microphone. case interrupted(at: Date) /// It gave it back. **No `shouldResume` rides here** — see rule 2. case interruptionEnded(at: Date) case personStopped(at: Date) /// The file is closed and playable. case captureClosed(at: Date) /// The file to file has been decided — the export landed, or it did not and /// the capture is what goes. case audioPrepared case created(Route) /// `meetings.create` refused, in the crate's own words. case refused(String) /// The person tapped the retry a failure carries. case retry } /// The recorder, as a value. public struct MeetingRecorderState: Equatable, Sendable { public var stage: MeetingRecorderStage = .idle /// When the FIRST second was captured — what the meeting row is stamped /// with, and what the recovery offer names. `nil` until capture opened. public var startedAt: Date? /// Spans that are over, in milliseconds. public var bankedMs: Double = 0 /// When the span that is not over began, or `nil` while paused. public var runningSince: Date? public init() {} /// How long has been captured. Banked plus running — never `now - startedAt`, /// which would count a pause as recorded audio and put a length on the row /// the file does not have. public func elapsedMs(at now: Date) -> Double { guard let runningSince else { return bankedMs } return bankedMs + max(0, now.timeIntervalSince(runningSince) * 1000) } /// The same figure as whole milliseconds, for the wire. public func elapsed(at now: Date) -> Int { Int(elapsedMs(at: now).rounded()) } /// Bank the running span and stop the clock. fileprivate mutating func bank(at now: Date) { bankedMs = elapsedMs(at: now) runningSince = nil } } /// The reducer. `step` is the whole of the recorder's behaviour. public enum MeetingRecorderMachine { /// Apply one event. The state is changed in place and the effects to run /// come back in the order they must run in. /// /// **An event the current stage has no answer for changes nothing and /// returns nothing.** That is not laxity: the events arrive from a screen, /// from `AVAudioSession` and from an async call, and a duplicate or a /// late one is ordinary — an interruption that ends twice, a Stop tapped /// while the file is already closing. Making each of those a no-op is how /// the machine stays a description of what happens rather than a list of /// guards every caller has to remember. @discardableResult public static func step( _ state: inout MeetingRecorderState, _ event: MeetingRecorderEvent ) -> [MeetingRecorderEffect] { switch event { case .appeared: // Asking twice would be a second prompt over a decision already // made, which iOS does not show and a person reads as broken. guard state.stage == .idle else { return [] } state.stage = .asking return [.askForMicrophone] case .gate(let result): guard state.stage == .asking else { return [] } switch result { case .ready: state.stage = .opening return [.openCapture] case .blocked(let capability, let access): state.stage = .blocked(capability, access) return [] } case .captureOpened(let at): guard state.stage == .opening else { return [] } state.startedAt = at state.runningSince = at state.stage = .recording return [.mark(.recording)] case .captureFailed(let at, let why): // From `.finishing` this is the CLOSE failing, which is a different // sentence but the same posture: the stage carries a retry and // nothing deletes the file. switch state.stage { case .opening, .recording, .paused, .finishing, .saving: state.bank(at: at) state.stage = .failed(why) return [] default: return [] } case .personPaused(let at): guard state.stage == .recording else { return [] } state.bank(at: at) state.stage = .paused(.person) return [.pauseCapture, .mark(.paused)] case .interrupted(let at): // RULE 1, the half that matters here: a person's pause is never // relabelled. It is already paused and it stays THEIRS, so an // interruption arriving on top of one changes nothing. guard state.stage == .recording else { return [] } state.bank(at: at) state.stage = .paused(.interruption) return [.pauseCapture, .mark(.paused)] case .interruptionEnded(let at): // RULE 1, the other half: only the OS's own pause is resumed by // the OS. RULE 2: it is always attempted — the flag iOS may or may // not send is not consulted, and is not even carried on the event. guard state.stage == .paused(.interruption) else { return [] } state.runningSince = at state.stage = .recording return [.resumeCapture, .mark(.recording)] case .personResumed(let at): guard case .paused = state.stage else { return [] } state.runningSince = at state.stage = .recording return [.resumeCapture, .mark(.recording)] case .personStopped(let at): switch state.stage { case .recording: state.bank(at: at) case .paused: break default: return [] } state.stage = .finishing return [.closeCapture] case .captureClosed: guard state.stage == .finishing else { return [] } return [.mark(.closed), .prepareAudio] case .audioPrepared: guard state.stage == .finishing else { return [] } state.stage = .saving return [.create] case .created(let route): state.stage = .saved(route) return [.clearMark] case .refused(let why): guard state.stage == .saving else { return [] } // RULE 3. The file stays, the marker stays: the next launch will // offer it even if this screen is never seen again. state.stage = .failed(why) return [] case .retry: guard case .failed = state.stage else { return [] } // Two failures wear the same verb and they are not the same act. // A recording that captured something failed at FILING, and the // retry is the same call again over the same file. A recorder that // never opened captured nothing, so `create` would refuse it for // having no audio and the verb would loop; the retry there is the // microphone again. guard state.startedAt != nil else { state.stage = .opening return [.openCapture] } // Back through the encode, not straight to the call: the file that // was filed is decided there, and a retry after an export that fell // over is a retry of the export too. state.stage = .finishing return [.prepareAudio] } } }