// Cotton Meetings' recorder, owned by the APP rather than by a screen (voice// plan, 17 Nov 2026): one tap on the first screen, the Action Button, the// lock screen's control or a Shortcut all start the same recording, and the// Live Activity's Pause, Resume, Mark and Stop act on it with the app never// opened. So nothing here is a view's state: the meetings screen reads this// object, and the intents (`CottonMeetingsLive`) reach it through the app.//// Every DECISION is the shell recorder's (`MeetingRecorderMachine`, its// three rules: a person's pause is sticky, an ended interruption always// resumes, a refusal at Stop keeps the audio). This file runs its effects the// way `MeetingRecorderModel` does, with what an app-owned recorder adds://// * a KIND, meeting or memo (a memo is the same thing with one speaker);// * MARKS, a moment tapped while recording, kept beside the audio// (`marks.json` in the act's folder) so a killed app keeps them too;// * the LIVE state handed out on every change (`onLive`), which the app// turns into the Live Activity;// * waiting: `start` answers once the microphone is open or refused, so an// intent can say what happened.//// THE CORE NAMES THE FILE (meetings-core, `apps/meetings/CORE.md`):// `meetings.record.start` makes the meeting's row at `recording` from the// first second and answers the path to write, a 16 kHz mono 16-bit WAV whose// header the core rewrites at stop or recovery, so a killed take is whole up// to its last sample. A take's id IS its meeting's id. Every ~10 s// `meetings.record.tick` says how long it has run. At Stop the WAV is encoded// to AAC in place (what goes up is ~15 times smaller) and `meetings.record.// stop` says which (`m4a`, or `wav` where the encode failed). At launch// `meetings.record.recover` finishes every take a killed process left.// While the core answers `not_yet`, the take is written to this app's own// folder and its row is a plain record (`MeetingsCore`).#if os(iOS)import AVFoundationimportCottonKitimportCottonValuesimportFoundationimportSwiftUI/// A meeting or a memo. A memo is a meeting with one speaker.publicenumMeetingKind: String, Sendable, Codable, Equatable, CaseIterable {case meetingcase memo}/// What the lock screen and the Dynamic Island draw, as the app hands it out./// The words are the kit's (`meetings` lines), resolved here so the widget/// extension carries no core and no line set.publicstructMeetingsLive: Equatable, Sendable {publicvar kind: MeetingKindpublicvar startedAt: Date/// Whole spans that are over, in milliseconds.publicvar bankedMs: Double/// When the running span began; `nil` while paused.publicvar runningSince: Date?publicvar marks: Int/// What the Activity says it is doing ("Recording a meeting", "Paused").publicvar headline: Stringpublicvar words: WordspublicstructWords: Equatable, Sendable {publicvar pause: Stringpublicvar resume: Stringpublicvar stop: Stringpublicvar mark: String }publicvar paused: Bool { runningSince == nil }}/// What an act from outside (an intent, the Live Activity) can ask.publicenumMeetingsAct: Equatable, Sendable {case start(MeetingKind)case pausecase resumecase markcase stop}/// What `start` answers, for an intent to say.publicenumMeetingsStartAnswer: Equatable, Sendable {case recordingcase blockedcase failed(String)}@MainActor@ObservablepublicfinalclassMeetingsEngine {publicstaticlet shared = MeetingsEngine()publicprivate(set) var state = MeetingRecorderState()publicprivate(set) var kind: MeetingKind = .meetingpublicprivate(set) var marks: [Int] = []publicprivate(set) var elapsedMs: Double = 0publicprivate(set) var meter: [Double] = []/// Bumped each time a recording is filed, so the list reads again.publicprivate(set) var filed = 0/// The meeting the last Stop made.publicprivate(set) var lastMeetingId: String?/// The act (folder) of the recording in hand.publicprivate(set) var act = MeetingFiles.newActId()/// Told on every change worth drawing on the lock screen; `nil` when no/// recording is in hand. Set by the app (`CottonMeetingsLive`). @ObservationIgnored publicvar onLive: (@MainActor (MeetingsLive?) -> Void)? @ObservationIgnored privatevar coreProvider: (@Sendable () async -> (any CottonCalling)?)? @ObservationIgnored privatevar capture: any MeetingCapture @ObservationIgnored privatelet authority: any CapabilityAuthority @ObservationIgnored privatelet recovery: MeetingRecoveryStore @ObservationIgnored privatelet files: any MeetingAudioStore @ObservationIgnored privatelet exporter: any MeetingAudioExporting @ObservationIgnored privatelet now: () -> Date @ObservationIgnored privatevar audioPath: String? @ObservationIgnored privatevar ticker: Task<Void, Never>? @ObservationIgnored privatevar checkpointedAt: Date? @ObservationIgnored privatevar tickedAt: Date?/// True when the core named the file (`meetings.record.start` answered). @ObservationIgnored privatevar inCore = false/// The file Stop hands the core and its format: the AAC encoded from the/// take, or the WAV as recorded where the encode failed. @ObservationIgnored privatevar format: String? @ObservationIgnored privatevar filedPath: String? @ObservationIgnored privatevar waiting: [CheckedContinuation<MeetingsStartAnswer, Never>] = [] @ObservationIgnored privatevar generation = 0staticlet meterWindow = 120staticlet checkpointEvery: TimeInterval = 5staticlet tickEvery: TimeInterval = 10/// The take's file in this app's own folder, while the core has no body/// for `meetings.record.start`.staticlet localFileName = "audio.wav"init( capture: (any MeetingCapture)? = nil, authority: any CapabilityAuthority = SystemCapabilityAuthority(), recovery: MeetingRecoveryStore = MeetingRecoveryStore(), files: any MeetingAudioStore = AppGroupMeetingAudioStore(), exporter: any MeetingAudioExporting = SystemMeetingAudioExport(), now: @escaping () -> Date = Date.init ) {self.capture = capture ?? MeetingsCaptureChoice.make()self.authority = authorityself.recovery = recoveryself.files = filesself.exporter = exporterself.now = now wire() }/// How the engine reaches the core once the app has opened it.publicfunc attach(_ provider: @escaping @Sendable () async -> (any CottonCalling)?) { coreProvider = provider }// MARK: - Acts/// True while a recording is in hand: recording, paused or being filed.publicvar isBusy: Bool {switch state.stage {case .idle, .blocked, .saved: returnfalsecase .failed: return state.startedAt != nildefault: returntrue } }publicfunc perform(_ act: MeetingsAct) async {switch act {case .start(let kind): _ = await start(kind)case .pause: pause()case .resume: resume()case .mark: mark()case .stop: stop() } }/// Start a recording, and answer once the microphone is open or refused./// A recording already in hand is left alone and answered as recording. @discardableResultpublicfunc start(_ kind: MeetingKind) async -> MeetingsStartAnswer {if isBusy { return .recording } reset()self.kind = kindreturnawait withCheckedContinuation { continuation in waiting.append(continuation) send(.appeared) } }publicfunc pause() { send(.personPaused(at: now())) }publicfunc resume() { send(.personResumed(at: now())) }publicfunc stop() { send(.personStopped(at: now())) }publicfunc retry() { send(.retry) }/// Mark the moment: the elapsed millisecond, kept beside the audio.publicfunc mark() {guardcase .recording = state.stage else {ifcase .paused = state.stage { marks.append(state.elapsed(at: now())); keepMarks(); live() }return } marks.append(state.elapsed(at: now())) keepMarks() live() }/// Discard the recording in hand. The only path that deletes audio the/// person did not file, and only on their word.publicfunc discard() {switch state.stage {case .recording, .paused, .failed: breakdefault: return } generation += 1 stopTicking() capture.close() recovery.clear(id: act) files.discard(act: act) reset() }// MARK: - The machineprivatefunc reset() { generation += 1 stopTicking() state = MeetingRecorderState() marks = [] elapsedMs = 0 meter = [] audioPath = nil format = nil filedPath = nil inCore = false checkpointedAt = nil tickedAt = nil act = MeetingFiles.newActId() wire() live() }privatefunc wire() { capture.onInterruption = { [weakself] kind inguardletselfelse { return }self.send(kind == .began ? .interrupted(at: self.now()) : .interruptionEnded(at: self.now())) } }privatefunc send(_ event: MeetingRecorderEvent) { generation += 1let mine = generationlet effects = MeetingRecorderMachine.step(&state, event) elapsedMs = state.elapsedMs(at: now()) answerWaiters() live()for effect in effects { run(effect)guard generation == mine else { return } } }privatefunc answerWaiters() {let answer: MeetingsStartAnswer?switch state.stage {case .recording: answer = .recordingcase .blocked: answer = .blockedcase .failed(let why): answer = .failed(why)default: answer = nil }guardlet answer, !waiting.isEmpty else { return }let held = waiting waiting = []for one in held { one.resume(returning: answer) } }privatefunc run(_ effect: MeetingRecorderEffect) {switch effect {case .askForMicrophone:Task { [authority] inlet answer = await authority.gate([.microphone])self.send(.gate(answer)) }case .openCapture:let mine = generationTask { await openCapture(mine) }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):guardlet audioPath, let startedAt = state.startedAt else { return } checkpointedAt = now() recovery.write(MeetingRecoveryMarker( id: act, path: audioPath, startedAt: CottonDate.format(startedAt), title: nil, durationMs: state.elapsed(at: now()), stage: stage ) )case .clearMark: recovery.clear(id: act)// The core holds the bytes now.iflet audioPath { MeetingsMarks.remove(besideAudio: audioPath) } files.discard(act: act) } }/// Ask the core where to write, then open the microphone there.privatefunc openCapture(_ mine: Int) async {let core = await coreProvider?()var file: URLiflet core, let started = try? awaitMeetingsCore(core: core).recordStart(kind: kind, id: act, startedAt: now()) {guard generation == mine else { return } act = started.meeting file = URL(fileURLWithPath: started.audio_path) inCore = truetry? FileManager.default.createDirectory(at: file.deletingLastPathComponent(), withIntermediateDirectories: true) } else {guard generation == mine else { return }do { file = try files.open(act: act, named: Self.localFileName) } catch {return send(.captureFailed(at: now(), why: sentence(error))) } }do {try capture.open(at: file) } catch {if !inCore { files.discard(act: act) }return send(.captureFailed(at: now(), why: sentence(error))) } audioPath = file.path(percentEncoded: false) keepMarks() send(.captureOpened(at: now())) startTicking() }/// Encode the take to AAC in place: the core is told `m4a`; where the/// encode fails the WAV stays as recorded and the core is told `wav`.privatefunc prepareAudio() async {guardlet audioPath, format == nilelse { return send(.audioPrepared) }let encoded = awaitSelf.encode(URL(fileURLWithPath: audioPath), exporter: exporter) (format, filedPath) = (encoded.format, encoded.url.path(percentEncoded: false)) send(.audioPrepared) }/// The take as AAC beside it (`<name>.m4a`); the WAV goes once the AAC is/// whole. Where the encode fails, the WAV as recorded.staticfunc encode(_ wav: URL, exporter: any MeetingAudioExporting) async -> (format: String, url: URL) {do {let made = tryawait exporter.export( wav, as: wav.deletingPathExtension().lastPathComponent + ".m4a", watching: { _ in })let beside = wav.deletingPathExtension().appendingPathExtension("m4a")if made != beside {try? FileManager.default.removeItem(at: beside)tryFileManager.default.moveItem(at: made, to: beside) }try? FileManager.default.removeItem(at: wav)return ("m4a", beside) } catch {Log.warn("meetings: the take could not be encoded, it goes as recorded: \(error)")return ("wav", wav) } }privatefunc create() async {guardlet audioPath, let startedAt = state.startedAt else { send(.refused(MeetingsWords.line("recorder.failed", ["why": ShellLines.line("capture", "meeting.nothing_to_file")])))return }guardlet core = await coreProvider?() else { send(.refused(MeetingsWords.line("recorder.no_database")))return }do {let duration = state.elapsed(at: now())let meetings = MeetingsCore(core: core)let finish = MeetingsCore.Finish( id: act, path: filedPath ?? audioPath, format: format ?? "wav", duration_ms: duration, marks: marks, ended_at: CottonDate.format(startedAt.addingTimeInterval(Double(duration) / 1000)))if inCore {tryawait meetings.recordStop(finish) } else {// The start never reached the core: the row is made now and// the take finished as a recovered one would be. _ = tryawait meetings.recordStart(kind: kind, id: act, startedAt: startedAt)tryawait meetings.recordRecover(finish) } lastMeetingId = act send(.created(.meetingsMeeting(id: act)))self.filed += 1// The next tap records again: a filed recording is not "in hand". reset() } catchlet error asCottonCallError { send(.refused(error.message)) } catch { send(.refused(sentence(error))) } }// MARK: - A recording the app never finished/// Every recording left on this phone by a process that ended mid-way,/// newest first; never the one in hand.publicfunc recoveryOffers() -> [MeetingRecoveryOffer] {let busyAct = isBusy ? act : nilreturnMeetingRecovery.offers( markers: recovery.markers(), onDisk: files.captures(), exists: { ((try? FileManager.default.attributesOfItem(atPath: $0)[.size]) as? NSNumber)?.intValue ?? 0 > 0 }, probe: { MeetingAudioLength.milliseconds(atPath: $0) } ).filter { $0.marker.id != busyAct } }/// Keep it: the same encode and the same filing Stop would have done,/// with the marks kept beside it. Answers whether it was filed.publicfunc keepRecovered(_ offer: MeetingRecoveryOffer) async -> Bool {let marker = offer.markerguardlet core = await coreProvider?() else { returnfalse }let held = MeetingsMarks.read(besideAudio: marker.path)let duration = offer.durationMs ?? marker.durationMslet startedAt = CottonDate.parse(marker.startedAt) ?? now()do {let meetings = MeetingsCore(core: core) _ = tryawait meetings.recordStart(kind: held?.kind ?? .meeting, id: marker.id, startedAt: startedAt)tryawait meetings.recordRecover(MeetingsCore.Finish( id: marker.id, path: marker.path, format: URL(fileURLWithPath: marker.path).pathExtension.lowercased(), duration_ms: duration, marks: held?.marks ?? [], ended_at: CottonDate.format(startedAt.addingTimeInterval(Double(duration) / 1000)))) lastMeetingId = marker.id recovery.clear(id: marker.id)MeetingsMarks.remove(besideAudio: marker.path) files.discard(act: marker.id) filed += 1returntrue } catch {Log.warn("meetings: a recovered recording was not filed: \(error)")returnfalse } }/// Once at launch: every take a killed process left is finished by the/// core — each one this app holds by name, with its kind and marks/// (`meetings.record.recover {id, path, …}`), then a sweep for any/// `recording` row left with its audio. A take the core would not take/// stays offered on the first screen.publicfunc recoverAtLaunch() async {guardlet core = await coreProvider?() else { return }for offer in recoveryOffers() { _ = await keepRecovered(offer) }// A transcription the system ended with the app is said, not left held.awaitMeetingsPhoneStep.shared.settleInterrupted(core: core)iflet swept = awaitMeetingsCore(core: core).recordRecover() {for meeting in swept { recovery.clear(id: meeting) }if !swept.isEmpty { filed += 1 } } }/// Discard it, on the person's word.publicfunc discardRecovered(_ offer: MeetingRecoveryOffer) { files.discard(act: offer.marker.id) recovery.clear(id: offer.marker.id) }// MARK: - Marks, beside the audioprivatefunc keepMarks() {guardlet audioPath else { return }MeetingsMarks.write(MeetingsMarks(kind: kind, marks: marks), besideAudio: audioPath) }// MARK: - The clockprivatefunc startTicking() {guard ticker == nilelse { return } ticker = Task { [weakself] inwhile !Task.isCancelled {try? awaitTask.sleep(for: .milliseconds(200))guard !Task.isCancelled else { return }self?.tick() } } }privatefunc stopTicking() { ticker?.cancel() ticker = nil }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) }if inCore, tickedAt.map({ now().timeIntervalSince($0) >= Self.tickEvery }) ?? true { tickedAt = now()let meeting = act, duration = state.elapsed(at: now())Task { [coreProvider] inguardlet core = await coreProvider?() else { return }awaitMeetingsCore(core: core).recordTick(meeting: meeting, durationMs: duration) } }iflet checkpointedAt, now().timeIntervalSince(checkpointedAt) < Self.checkpointEvery { return } run(.mark(.recording)) }// MARK: - The lock screenprivatefunc live() {guardlet onLive else { return }guardlet startedAt = state.startedAt else { onLive(nil)return }switch state.stage {case .recording, .paused, .finishing, .saving, .failed: breakdefault: onLive(nil)return } onLive(MeetingsLive( kind: kind, startedAt: startedAt, bankedMs: state.bankedMs, runningSince: state.runningSince, marks: marks.count, headline: MeetingsWords.headline(state.stage, kind: kind), words: .init( pause: MeetingsWords.line("recorder.pause"), resume: MeetingsWords.line("recorder.resume"), stop: MeetingsWords.line("recorder.stop"), mark: MeetingsWords.line("recorder.mark")))) }privatefunc sentence(_ error: Error) -> String { (error as? LocalizedError)?.errorDescription ?? String(describing: error) }}/// What a recording is (meeting or memo) and the moments marked in it, in a/// small file beside its audio, so a recording the app never finished keeps/// both.structMeetingsMarks: Codable, Equatable {var kind: MeetingKindvar marks: [Int]/// `<audio's name>.marks.json`, beside it: the core's recordings share/// one folder, so each take's file is named for its own audio.staticfunc url(besideAudio audio: String) -> URL {let file = URL(fileURLWithPath: audio)return file.deletingLastPathComponent().appending(path: file.deletingPathExtension().lastPathComponent + ".marks.json") }staticfunc write(_ held: MeetingsMarks, besideAudio audio: String) {guardlet data = try? JSONEncoder().encode(held) else { return }try? data.write(to: url(besideAudio: audio), options: .atomic) }/// The file holds a kind and the marks' offsets, written by this app:/// read through a handle, no further than `largest` bytes.staticlet largest = 64 * 1024staticfunc read(besideAudio audio: String) -> MeetingsMarks? {guardlet handle = try? FileHandle(forReadingFrom: url(besideAudio: audio)) else { returnnil }defer { try? handle.close() }guardlet data = try? handle.read(upToCount: largest), data.count < largest else { returnnil }returntry? JSONDecoder().decode(MeetingsMarks.self, from: data) }staticfunc remove(besideAudio audio: String) {try? FileManager.default.removeItem(at: url(besideAudio: audio)) }}#endif