Jotley / app · jotley.ai / iOS / Services / AudioRecordingManager.swift
| 1 | import Foundation |
| 2 | import AVFoundation |
| 3 | import Combine |
| 4 | import CoreData |
| 5 | import Darwin |
| 6 | import UIKit |
| 7 | import ActivityKit |
| 8 | import BackgroundTasks |
| 9 | |
| 10 | /// Apple's continued-processing runtime is requested only for an explicit |
| 11 | /// summary action. The OS can still expire it; checkpointed work then resumes |
| 12 | /// in the foreground. No silent audio session is used to keep the app alive. |
| 13 | @MainActor final class SummaryBackgroundRuntime { |
| 14 | private let identifier = (Bundle.main.bundleIdentifier ?? "com.protomota.jotley") + ".summary." + UUID().uuidString |
| 15 | private var assertion: UIBackgroundTaskIdentifier = .invalid |
| 16 | private var continuedTask: BGContinuedProcessingTask? |
| 17 | private var submission: Task<Void, Never>? |
| 18 | private var finished = false |
| 19 | private var currentProgress: LocalSummaryProgress = .preparing |
| 20 | private var priorSections: Int64 = 0 |
| 21 | private var lastPass = 0 |
| 22 | private var lastTotal = 0 |
| 23 | private let expired: @MainActor () -> Void |
| 24 | |
| 25 | init(expired: @escaping @MainActor () -> Void) { self.expired = expired } |
| 26 | func begin() { |
| 27 | assertion = UIApplication.shared.beginBackgroundTask(withName: "Finish Jotley summary") { [weak self] in |
| 28 | self?.expire() // UIKit delivers this handler on the main actor. |
| 29 | } |
| 30 | #if !targetEnvironment(simulator) |
| 31 | let registered = BGTaskScheduler.shared.register(forTaskWithIdentifier: identifier, using: .main) { [weak self] task in |
| 32 | MainActor.assumeIsolated { |
| 33 | guard let self, !self.finished, let task = task as? BGContinuedProcessingTask else { |
| 34 | task.setTaskCompleted(success: false); return |
| 35 | } |
| 36 | self.continuedTask = task |
| 37 | task.progress.totalUnitCount = 2 * Self.unit |
| 38 | task.progress.completedUnitCount = 0 |
| 39 | task.expirationHandler = { [weak self] in Task { @MainActor in self?.expire() } } |
| 40 | self.update(self.currentProgress) |
| 41 | self.endAssertion() |
| 42 | } |
| 43 | } |
| 44 | guard registered else { return } // The short runtime remains available. |
| 45 | let request = BGContinuedProcessingTaskRequest(identifier: identifier, title: "Summarizing your note", subtitle: "Preparing summary") |
| 46 | request.strategy = .fail // Never queue a second copy of the same inference. |
| 47 | submission = Task { [weak self] in |
| 48 | do { try await Self.submit(request) } |
| 49 | catch { /* Fall back to the short runtime and durable checkpoint. */ } |
| 50 | guard let self else { return } |
| 51 | if self.finished { BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: self.identifier) } |
| 52 | } |
| 53 | #endif |
| 54 | } |
| 55 | @concurrent private static func submit(_ request: BGContinuedProcessingTaskRequest) async throws { |
| 56 | try await BGTaskScheduler.shared.submitTaskRequest(request) |
| 57 | } |
| 58 | /// Apple can stop a continued-processing task whose progress stops moving, |
| 59 | /// so progress also advances while the final summary streams in. |
| 60 | private var streamedSnapshots: Int64 = 0 |
| 61 | private static let unit: Int64 = 100 |
| 62 | func update(_ progress: LocalSummaryProgress) { |
| 63 | currentProgress = progress |
| 64 | guard let task = continuedTask else { return } |
| 65 | task.updateTitle("Summarizing your note", subtitle: [progress.title, progress.detail].compactMap { $0 }.joined(separator: " · ")) |
| 66 | let unit = Self.unit |
| 67 | switch progress { |
| 68 | case .reading(let completed, let total, let pass): |
| 69 | if pass != lastPass { priorSections += Int64(lastTotal); lastPass = pass } |
| 70 | lastTotal = total |
| 71 | task.progress.totalUnitCount = (priorSections + Int64(total)) * unit + 2 * unit |
| 72 | task.progress.completedUnitCount = (priorSections + Int64(completed)) * unit |
| 73 | case .writing: |
| 74 | task.progress.totalUnitCount = (priorSections + Int64(lastTotal)) * unit + 2 * unit |
| 75 | task.progress.completedUnitCount = (priorSections + Int64(lastTotal)) * unit + min(unit * 2 - 20, streamedSnapshots / 3) |
| 76 | case .finishing: |
| 77 | task.progress.completedUnitCount = task.progress.totalUnitCount - 10 |
| 78 | default: break |
| 79 | } |
| 80 | } |
| 81 | func streamed() { |
| 82 | streamedSnapshots += 1 |
| 83 | if case .writing = currentProgress { update(.writing) } |
| 84 | } |
| 85 | private func expire() { |
| 86 | guard !finished else { return } |
| 87 | expired() |
| 88 | finish(success: false) |
| 89 | } |
| 90 | func finish(success: Bool) { |
| 91 | guard !finished else { return } |
| 92 | finished = true |
| 93 | if success, let task = continuedTask { task.progress.completedUnitCount = task.progress.totalUnitCount } |
| 94 | continuedTask?.setTaskCompleted(success: success); continuedTask = nil |
| 95 | submission?.cancel(); submission = nil |
| 96 | BGTaskScheduler.shared.cancel(taskRequestWithIdentifier: identifier) |
| 97 | endAssertion() |
| 98 | } |
| 99 | private func endAssertion() { |
| 100 | if assertion != .invalid { UIApplication.shared.endBackgroundTask(assertion); assertion = .invalid } |
| 101 | } |
| 102 | } |
| 103 | |
| 104 | struct MobileSummaryJob: Codable, Sendable { |
| 105 | let noteID: UUID |
| 106 | let templateKey: String |
| 107 | let localeIdentifier: String |
| 108 | var checkpoint: LocalSummaryCheckpoint |
| 109 | var templateDefinition: SummaryTemplateDefinition? |
| 110 | } |
| 111 | |
| 112 | /// Apple Intelligence hardware is required; model setup is checked separately. |
| 113 | enum MobileDeviceEligibility { |
| 114 | static var identifier: String { |
| 115 | #if targetEnvironment(simulator) |
| 116 | return ProcessInfo.processInfo.environment["SIMULATOR_MODEL_IDENTIFIER"] ?? "unknown" |
| 117 | #else |
| 118 | var system = utsname(); uname(&system) |
| 119 | let capacity = MemoryLayout.size(ofValue: system.machine) |
| 120 | return withUnsafePointer(to: &system.machine) { |
| 121 | $0.withMemoryRebound(to: CChar.self, capacity: capacity) { String(cString: $0) } |
| 122 | } |
| 123 | #endif |
| 124 | } |
| 125 | static var unsupportedReason: String? { JotleyAppleIntelligenceEligibility.unsupportedReason } |
| 126 | } |
| 127 | |
| 128 | /// Serialize microphone session changes away from the main actor. Ownership keeps |
| 129 | /// an older session's deactivation from stopping a newer live transcription. |
| 130 | actor LocalAudioSession { |
| 131 | static let shared = LocalAudioSession() |
| 132 | private var owner: UUID? |
| 133 | private var transition: Task<Void, Error>? |
| 134 | private var transitionID: UUID? |
| 135 | private let queue = DispatchQueue(label: "Jotley.AudioSession", qos: .userInitiated) |
| 136 | func activate(owner: UUID) async throws { |
| 137 | let previous = transition, id = UUID() |
| 138 | let next = Task { |
| 139 | _ = try? await previous?.value |
| 140 | try await self.performActivation(owner: owner) |
| 141 | } |
| 142 | transition = next; transitionID = id |
| 143 | defer { if transitionID == id { transition = nil; transitionID = nil } } |
| 144 | try await next.value |
| 145 | } |
| 146 | private func performActivation(owner: UUID) async throws { |
| 147 | try await withCheckedThrowingContinuation { (continuation: CheckedContinuation<Void, Error>) in |
| 148 | queue.async { |
| 149 | do { |
| 150 | let session = AVAudioSession.sharedInstance() |
| 151 | try session.setCategory(.playAndRecord, mode: .default, options: [.defaultToSpeaker, .allowBluetoothHFP]) |
| 152 | try session.setActive(true) |
| 153 | continuation.resume() |
| 154 | } catch { continuation.resume(throwing: error) } |
| 155 | } |
| 156 | } |
| 157 | self.owner = owner |
| 158 | } |
| 159 | func deactivate(owner: UUID) async { |
| 160 | let previous = transition, id = UUID() |
| 161 | let next = Task<Void, Error> { |
| 162 | _ = try? await previous?.value |
| 163 | await self.performDeactivation(owner: owner) |
| 164 | } |
| 165 | transition = next; transitionID = id |
| 166 | defer { if transitionID == id { transition = nil; transitionID = nil } } |
| 167 | _ = try? await next.value |
| 168 | } |
| 169 | private func performDeactivation(owner: UUID) async { |
| 170 | guard self.owner == owner else { return } |
| 171 | self.owner = nil |
| 172 | await withCheckedContinuation { (continuation: CheckedContinuation<Void, Never>) in |
| 173 | queue.async { |
| 174 | try? AVAudioSession.sharedInstance().setActive(false, options: .notifyOthersOnDeactivation) |
| 175 | continuation.resume() |
| 176 | } |
| 177 | } |
| 178 | } |
| 179 | } |
| 180 | |
| 181 | /// Count microphone buffers independently of UI scheduling. Quiet or zero-valued |
| 182 | /// samples are not proof of a disconnected microphone; only absent buffers stall. |
| 183 | final class MicrophoneCaptureProgress: @unchecked Sendable { |
| 184 | private let lock = NSLock() |
| 185 | private var frames: Int64 = 0 |
| 186 | private var lastBufferTime: TimeInterval |
| 187 | init(startedAt: TimeInterval = ProcessInfo.processInfo.systemUptime) { lastBufferTime = startedAt } |
| 188 | func received(frames: Int, at time: TimeInterval = ProcessInfo.processInfo.systemUptime) { |
| 189 | guard frames > 0 else { return } |
| 190 | lock.lock(); defer { lock.unlock() } |
| 191 | self.frames += Int64(frames); lastBufferTime = time |
| 192 | |
| 193 | } |
| 194 | func snapshot(at time: TimeInterval = ProcessInfo.processInfo.systemUptime) -> (frames: Int64, stalled: Bool) { |
| 195 | lock.lock(); defer { lock.unlock() } |
| 196 | return (frames, time - lastBufferTime >= 3) |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | /// Each update replaces the current take's provisional text. Persist volatile |
| 201 | /// words too: without an audio file, an interruption must not discard them. |
| 202 | @MainActor struct MobileTranscriptCheckpoint { |
| 203 | let baseText: String |
| 204 | let baseUtterances: [TranscriptUtterance] |
| 205 | let offset: TimeInterval |
| 206 | func save(_ value: LocalTranscript, to note: Note, in store: SharedPersistenceController) throws -> String { |
| 207 | let text = [baseText, value.displayText].filter { !$0.isEmpty }.joined(separator: " ") |
| 208 | note.transcription = text |
| 209 | // Persist provisional words too. The saved-note display deliberately |
| 210 | // filters interim recognition results, so checkpoints mark them durable. |
| 211 | note.setTranscriptUtterances(utterances(for: value).map { |
| 212 | TranscriptUtterance(id: $0.id, text: $0.text, start: $0.start, end: $0.end, |
| 213 | speaker: $0.speaker, confidence: $0.confidence) |
| 214 | }) |
| 215 | try store.save() |
| 216 | return text |
| 217 | } |
| 218 | func utterances(for value: LocalTranscript) -> [TranscriptUtterance] { |
| 219 | let previous = baseUtterances.isEmpty ? TranscriptUtterance.fallbackUtterances(from: baseText) : baseUtterances |
| 220 | var current = value.utterances.map { |
| 221 | TranscriptUtterance(id: "live-\(offset)-\($0.start)", text: $0.text, |
| 222 | start: offset + $0.start, end: offset + $0.end) |
| 223 | } |
| 224 | if !value.tentative.isEmpty, let start = value.tentativeStart, let end = value.tentativeEnd { |
| 225 | current.append(TranscriptUtterance(id: "live-\(offset)-\(start)", text: value.tentative, |
| 226 | start: offset + start, end: offset + end, isInterim: true)) |
| 227 | } |
| 228 | return previous + current |
| 229 | } |
| 230 | func displayUtterances(for value: LocalTranscript) -> [TranscriptUtterance] { |
| 231 | let all = utterances(for: value) |
| 232 | return TranscriptUtterance.coalescedForDisplay(all.filter { !$0.isInterim }) + all.filter(\.isInterim) |
| 233 | } |
| 234 | } |
| 235 | |
| 236 | enum TranscriptionState { case idle, listening, paused } |
| 237 | |
| 238 | /// The mobile lifecycle can be verified without a simulator speech model. |
| 239 | protocol MobileSpeechSession: Sendable { |
| 240 | func append(_ data: Data, sampleRate: Double) |
| 241 | func finish() async throws -> LocalTranscript |
| 242 | func cancel() async |
| 243 | } |
| 244 | extension LiveSpeechSession: MobileSpeechSession {} |
| 245 | |
| 246 | @MainActor |
| 247 | final class LiveTranscriptionManager: ObservableObject { |
| 248 | static let willBeginTranscription = Notification.Name("JotleyWillBeginLiveTranscription") |
| 249 | @Published private(set) var transcriptionState: TranscriptionState = .idle |
| 250 | @Published private(set) var busy = false |
| 251 | @Published private(set) var transcriptionDuration: TimeInterval = 0 |
| 252 | nonisolated static let waveformSamplesPerSecond = 30.0 |
| 253 | private var waveformPeaks: ArraySlice<Float> = [] |
| 254 | private var lastWaveformPeak: Float = 0 |
| 255 | @Published private(set) var activeNoteID: UUID? |
| 256 | @Published private(set) var liveTranscript = "" |
| 257 | @Published private(set) var liveUtterances: [TranscriptUtterance] = [] |
| 258 | @Published var captureScreenVisible = false |
| 259 | @Published var errorMessage: String? |
| 260 | @Published private(set) var summaryNoteID: UUID? |
| 261 | @Published private(set) var summaryPreview = "" |
| 262 | @Published private(set) var summaryProgress: LocalSummaryProgress = .preparing |
| 263 | let summaryNotifications: JotleySummaryNotifications |
| 264 | private let store: SharedPersistenceController? |
| 265 | private let audioSessionOwner = UUID() |
| 266 | private var pendingInterruption: String? |
| 267 | private var pendingStop: String? |
| 268 | private var engine: AVAudioEngine? |
| 269 | private var tapInstalled = false |
| 270 | private var speech: (any MobileSpeechSession)? |
| 271 | private var stopRequests = 0 |
| 272 | private var transitionWaiters: [CheckedContinuation<Void, Never>] = [] |
| 273 | #if DEBUG && targetEnvironment(simulator) |
| 274 | // Explicit test injection only; no synthetic speech is compiled into releases. |
| 275 | var simulatedSpeechStart: (@MainActor (@escaping @Sendable (LocalTranscript) async -> Void) async throws -> any MobileSpeechSession)? |
| 276 | var simulatedCaptureStart: (@MainActor () async -> Void)? |
| 277 | // Measured PCM peaks for screenshot playback; never part of a release build. |
| 278 | var simulatedAudioLevels: [Float] = [] |
| 279 | private var simulatedSegmentStart: TimeInterval? |
| 280 | var simulatedSummaryGeneration: (@MainActor (@escaping @Sendable (String) async -> Void) async throws -> String)? |
| 281 | var simulatedTitleGeneration: (@MainActor (String) async throws -> String)? |
| 282 | var simulatedOrganization: (@MainActor (String, [LocalTagCandidate]) async throws -> LocalNoteOrganization)? |
| 283 | #endif |
| 284 | private var sessionID: UUID? |
| 285 | private var endingSession = false |
| 286 | private var speechHasFailed = false |
| 287 | private var pendingTranscript: LocalTranscript? |
| 288 | private var transcriptFlushTask: Task<Void, Never>? |
| 289 | private var timer: Timer? |
| 290 | private var observers: [NSObjectProtocol] = [] |
| 291 | private let notificationCenter: NotificationCenter |
| 292 | private var previousDuration: TimeInterval = 0 |
| 293 | private var segmentRate: Double = 0 |
| 294 | private var captureProgress: MicrophoneCaptureProgress? |
| 295 | private var engineObserver: NSObjectProtocol? |
| 296 | private var baseTranscript = "" |
| 297 | private var baseUtterances: [TranscriptUtterance] = [] |
| 298 | private(set) var transcriptOffset: TimeInterval = 0 |
| 299 | private var captureLease: UUID? |
| 300 | private var summaryTask: Task<Void, Never>? |
| 301 | private var summaryRuntime: SummaryBackgroundRuntime? |
| 302 | private var pendingSummaryJob: MobileSummaryJob? |
| 303 | private var summaryPausedBySystem = false |
| 304 | var summaryRecoveryURL: URL? { store?.root.appendingPathComponent("SummaryGeneration.json") } |
| 305 | private let liveActivity = LocalTranscriptionLiveActivity() |
| 306 | var locale: Locale { Locale(identifier: UserDefaults.standard.string(forKey: "transcriptionLanguage") ?? "en-US") } |
| 307 | var isTranscribing: Bool { transcriptionState != .idle } |
| 308 | var canStart: Bool { !busy && stopRequests == 0 && !isTranscribing && summaryNoteID == nil } |
| 309 | |
| 310 | init(store: SharedPersistenceController?, notificationCenter: NotificationCenter = .default, summaryNotifications: JotleySummaryNotifications? = nil) { |
| 311 | self.summaryNotifications = summaryNotifications ?? .shared |
| 312 | self.store = store; self.notificationCenter = notificationCenter |
| 313 | guard let store, store.ready else { return } |
| 314 | do { try LegacyAudioCleanup.remove(in: store.root) } catch { errorMessage = "Could not remove previous audio: \(error.localizedDescription). Your transcript text is preserved." } |
| 315 | if let url = summaryRecoveryURL, FileManager.default.fileExists(atPath: url.path) { |
| 316 | do { pendingSummaryJob = try JSONDecoder().decode(MobileSummaryJob.self, from: Data(contentsOf: url)) } |
| 317 | catch { errorMessage = "Summary recovery could not be read. Your saved transcript and summary are unchanged: \(error.localizedDescription)" } |
| 318 | } |
| 319 | let center = notificationCenter |
| 320 | observers.append(center.addObserver(forName: AVAudioApplication.inputMuteStateChangeNotification, object: nil, queue: .main) { [weak self] notice in |
| 321 | guard notice.userInfo?[AVAudioApplication.muteStateKey] as? Bool == true else { return } |
| 322 | Task { @MainActor [weak self] in self?.handleInterruption("The microphone is muted. Transcription is paused. Unmute the microphone, then tap Resume. Words already transcribed are saved.") } |
| 323 | }) |
| 324 | observers.append(center.addObserver(forName: AVAudioSession.didBecomeInactiveNotification, object: nil, queue: .main) { [weak self] notice in |
| 325 | if let context = notice.userInfo?[AVAudioSession.deactivationContextKey] as? AVAudioSession.DeactivationContext, context.source == .app { return } |
| 326 | Task { @MainActor [weak self] in |
| 327 | self?.handleInterruption("Transcription paused by an audio interruption. Resume when the microphone is available.") |
| 328 | } |
| 329 | }) |
| 330 | observers.append(center.addObserver(forName: AVAudioSession.routeChangeNotification, object: nil, queue: .main) { [weak self] notice in |
| 331 | guard let raw = notice.userInfo?[AVAudioSessionRouteChangeReasonKey] as? UInt, |
| 332 | AVAudioSession.RouteChangeReason(rawValue: raw) == .oldDeviceUnavailable else { return } |
| 333 | Task { @MainActor [weak self] in self?.handleInterruption("The audio input changed. Transcription is paused; reconnect the microphone or resume with the new input.") } |
| 334 | }) |
| 335 | observers.append(center.addObserver(forName: AVAudioSession.mediaServicesWereResetNotification, object: nil, queue: .main) { [weak self] _ in |
| 336 | Task { @MainActor [weak self] in |
| 337 | guard let self, self.activeNoteID != nil else { return } |
| 338 | let message = "Audio services restarted. Live transcription stopped; words already transcribed are saved." |
| 339 | if self.busy { self.pendingStop = message } |
| 340 | else { self.errorMessage = message; await self.stopTranscription() } |
| 341 | } |
| 342 | }) |
| 343 | } |
| 344 | private func handleInterruption(_ message: String) { |
| 345 | guard activeNoteID != nil else { return } |
| 346 | if busy { pendingInterruption = message } |
| 347 | else if transcriptionState == .listening { pauseTranscription(); errorMessage = message } |
| 348 | } |
| 349 | private func finishTransition() { |
| 350 | busy = false |
| 351 | let waiters = transitionWaiters |
| 352 | transitionWaiters.removeAll() |
| 353 | waiters.forEach { $0.resume() } |
| 354 | if let message = pendingStop { |
| 355 | pendingStop = nil; pendingInterruption = nil |
| 356 | Task { @MainActor [weak self] in self?.errorMessage = message; await self?.stopTranscription() } |
| 357 | } else if let message = pendingInterruption { |
| 358 | pendingInterruption = nil |
| 359 | if transcriptionState == .listening { pauseTranscription(); errorMessage = message } |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | deinit { |
| 364 | observers.forEach(notificationCenter.removeObserver) |
| 365 | if let engineObserver { notificationCenter.removeObserver(engineObserver) } |
| 366 | timer?.invalidate(); transcriptFlushTask?.cancel() |
| 367 | } |
| 368 | |
| 369 | func createNote(text: String = "", title: String = "Untitled") throws -> Note { |
| 370 | guard let store, store.ready, canStart else { throw LocalError.message("Finish the current transcription or summary first.") } |
| 371 | guard let note = try store.create(title: title, text: text, noteType: "voice") as? Note else { throw LocalError.message("Unable to create a local note.") } |
| 372 | return note |
| 373 | } |
| 374 | func startTranscription(note existing: Note? = nil) async { |
| 375 | guard canStart, let store else { return } |
| 376 | busy = true; defer { finishTransition() } |
| 377 | errorMessage = nil |
| 378 | do { |
| 379 | if let reason = MobileDeviceEligibility.unsupportedReason { throw LocalError.message(reason) } |
| 380 | #if DEBUG && targetEnvironment(simulator) |
| 381 | let permitted = simulatedSpeechStart != nil ? true : await AVAudioApplication.requestRecordPermission() |
| 382 | #else |
| 383 | let permitted = await AVAudioApplication.requestRecordPermission() |
| 384 | #endif |
| 385 | guard permitted else { throw LocalError.message("Microphone access is required. Enable Microphone in Settings → Apps → Jotley.") } |
| 386 | guard stopRequests == 0 else { return } |
| 387 | let note: Note |
| 388 | if let existing { note = existing } else { |
| 389 | guard let created = try store.create(title: "Untitled") as? Note else { throw LocalError.message("Unable to create note.") } |
| 390 | note = created |
| 391 | } |
| 392 | guard note.managedObjectContext === store.context, !note.isDeleted, let id = note.id else { throw LocalError.message("This note is unavailable.") } |
| 393 | captureLease = try store.beginRecording(note) |
| 394 | activeNoteID = id; note.noteType = "voice"; try store.save() |
| 395 | baseTranscript = note.transcription ?? ""; baseUtterances = note.transcriptUtterances |
| 396 | if baseUtterances.isEmpty { baseUtterances = TranscriptUtterance.fallbackUtterances(from: baseTranscript) } |
| 397 | transcriptOffset = baseUtterances.compactMap(\.end).max() ?? 0 |
| 398 | transcriptionDuration = 0; previousDuration = 0; liveTranscript = baseTranscript |
| 399 | liveUtterances = baseUtterances.isEmpty ? TranscriptUtterance.fallbackUtterances(from: baseTranscript) : baseUtterances |
| 400 | // Prepare the local speech engine before opening the microphone. |
| 401 | // No saved audio exists to retry if the model is unavailable. |
| 402 | let token = UUID(); sessionID = token; endingSession = false; speechHasFailed = false |
| 403 | let snapshot: @Sendable (LocalTranscript) async -> Void = { [weak self] value in |
| 404 | await MainActor.run { [weak self] in |
| 405 | guard self?.sessionID == token else { return } |
| 406 | self?.stageTranscript(value, token: token) |
| 407 | } |
| 408 | } |
| 409 | #if DEBUG && targetEnvironment(simulator) |
| 410 | if let simulatedSpeechStart { speech = try await simulatedSpeechStart(snapshot) } |
| 411 | else { speech = try await prepareSpeech(snapshot: snapshot, token: token) } |
| 412 | #else |
| 413 | speech = try await prepareSpeech(snapshot: snapshot, token: token) |
| 414 | #endif |
| 415 | guard stopRequests == 0 else { return } |
| 416 | guard !speechHasFailed else { throw LocalError.message("The speech engine could not start. Try again after checking on-device speech in Settings.") } |
| 417 | notificationCenter.post(name: Self.willBeginTranscription, object: nil) |
| 418 | try await startSegment() |
| 419 | guard stopRequests == 0 else { return } |
| 420 | transcriptionState = .listening |
| 421 | liveActivity.start(noteID: id) |
| 422 | timer = Timer.scheduledTimer(withTimeInterval: 0.25, repeats: true) { [weak self] _ in |
| 423 | Task { @MainActor [weak self] in self?.updateCaptureProgress() } |
| 424 | } |
| 425 | } catch { |
| 426 | endingSession = true; sessionID = nil; pendingStop = nil; pendingInterruption = nil |
| 427 | flushTranscript() |
| 428 | closeSegment(); await speech?.cancel(); speech = nil; activeNoteID = nil; transcriptionState = .idle |
| 429 | if let captureLease { store.endRecording(lease: captureLease); self.captureLease = nil } |
| 430 | errorMessage = Self.microphoneErrorMessage(error) |
| 431 | await LocalAudioSession.shared.deactivate(owner: audioSessionOwner) |
| 432 | } |
| 433 | } |
| 434 | private func prepareSpeech(snapshot: @escaping @Sendable (LocalTranscript) async -> Void, token: UUID) async throws -> LiveSpeechSession { |
| 435 | try await LiveSpeechSession.start(locale: locale, failure: { [weak self] error in |
| 436 | Task { @MainActor [weak self] in self?.speechFailed(error, sessionID: token) } |
| 437 | }, snapshot: snapshot) |
| 438 | } |
| 439 | private func startSegment() async throws { |
| 440 | #if DEBUG && targetEnvironment(simulator) |
| 441 | if simulatedSpeechStart != nil { |
| 442 | await simulatedCaptureStart?() |
| 443 | guard stopRequests == 0 else { return } |
| 444 | segmentRate = 1000 |
| 445 | simulatedSegmentStart = ProcessInfo.processInfo.systemUptime |
| 446 | captureProgress = MicrophoneCaptureProgress() |
| 447 | captureProgress?.received(frames: 1) |
| 448 | return |
| 449 | } |
| 450 | #endif |
| 451 | guard let speech, let token = sessionID else { throw LocalError.message("Prepare on-device speech before starting the microphone.") } |
| 452 | try await LocalAudioSession.shared.activate(owner: audioSessionOwner) |
| 453 | guard stopRequests == 0 else { return } |
| 454 | guard AVAudioSession.sharedInstance().isInputAvailable else { |
| 455 | throw LocalError.message("No microphone is available. Disconnect iPhone Mirroring or another app using the microphone, then try again.") |
| 456 | } |
| 457 | guard !AVAudioApplication.shared.isInputMuted else { |
| 458 | throw LocalError.message("The microphone is muted. Unmute it before starting live transcription.") |
| 459 | } |
| 460 | let engine = AVAudioEngine(); let input = engine.inputNode |
| 461 | let format = input.outputFormat(forBus: 0) |
| 462 | guard format.sampleRate.isFinite, format.sampleRate > 0, format.channelCount > 0, format.commonFormat == .pcmFormatFloat32 else { throw LocalError.message("The microphone's audio format is unavailable.") } |
| 463 | self.engine = engine; self.segmentRate = format.sampleRate |
| 464 | let progress = MicrophoneCaptureProgress() |
| 465 | captureProgress = progress |
| 466 | engineObserver = notificationCenter.addObserver(forName: .AVAudioEngineConfigurationChange, object: engine, queue: .main) { [weak self, weak engine] _ in |
| 467 | Task { @MainActor [weak self, weak engine] in |
| 468 | guard let self, let engine, self.engine === engine else { return } |
| 469 | self.handleInterruption("The microphone connection changed. Transcription is paused. Tap Resume to reconnect the input, words already transcribed are saved.") |
| 470 | } |
| 471 | } |
| 472 | // Use the shortest supported tap (100 ms) and meter shorter slices |
| 473 | // within each buffer to retain changes between syllables. |
| 474 | let tapFrames = AVAudioFrameCount(ceil(format.sampleRate * 0.1)) |
| 475 | try input.installAudioTap(onBus: 0, bufferSize: tapFrames, format: format) { [weak self, weak engine] buffer, _ in |
| 476 | do { |
| 477 | let data = try Self.monoPCM(buffer) |
| 478 | let peaks = Self.waveformPeaks(in: data, sampleRate: format.sampleRate) |
| 479 | progress.received(frames: Int(buffer.frameLength)) |
| 480 | speech.append(data, sampleRate: format.sampleRate) |
| 481 | Task { @MainActor [weak self, weak engine] in |
| 482 | guard let self, let engine, self.sessionID == token, self.engine === engine, !self.endingSession else { return } |
| 483 | self.waveformPeaks = peaks[...] |
| 484 | } |
| 485 | } catch { |
| 486 | Task { @MainActor [weak self] in |
| 487 | self?.speechFailed(error, sessionID: token) |
| 488 | } |
| 489 | } |
| 490 | } |
| 491 | tapInstalled = true |
| 492 | engine.prepare(); try engine.start() |
| 493 | } |
| 494 | |
| 495 | nonisolated static func waveformPeaks(in data: Data, sampleRate: Double) -> [Float] { |
| 496 | data.withUnsafeBytes { bytes in |
| 497 | let samples = bytes.bindMemory(to: Float.self) |
| 498 | guard !samples.isEmpty else { return [] } |
| 499 | let windows = max(1, Int((Double(samples.count) * waveformSamplesPerSecond / sampleRate).rounded())) |
| 500 | return (0..<windows).map { window in |
| 501 | let start = window * samples.count / windows |
| 502 | let end = (window + 1) * samples.count / windows |
| 503 | return samples[start..<end].reduce(Float(0)) { max($0, abs($1)) } |
| 504 | } |
| 505 | } |
| 506 | } |
| 507 | |
| 508 | func nextWaveformPeak() -> Float { |
| 509 | #if DEBUG && targetEnvironment(simulator) |
| 510 | if let start = simulatedSegmentStart, !simulatedAudioLevels.isEmpty { |
| 511 | let elapsed = max(0, ProcessInfo.processInfo.systemUptime - start) |
| 512 | let index = Int(elapsed * Self.waveformSamplesPerSecond) % simulatedAudioLevels.count |
| 513 | return simulatedAudioLevels[index] |
| 514 | } |
| 515 | #endif |
| 516 | if let peak = waveformPeaks.popFirst() { |
| 517 | lastWaveformPeak = peak |
| 518 | return peak |
| 519 | } |
| 520 | // Fill a brief scheduling gap between buffers, then settle to silence. |
| 521 | let peak = lastWaveformPeak |
| 522 | lastWaveformPeak = 0 |
| 523 | return peak |
| 524 | } |
| 525 | |
| 526 | private func updateCaptureProgress() { |
| 527 | guard transcriptionState == .listening, let progress = captureProgress, segmentRate > 0 else { return } |
| 528 | #if DEBUG && targetEnvironment(simulator) |
| 529 | if simulatedSpeechStart != nil, let start = simulatedSegmentStart { |
| 530 | let expectedFrames = Int(max(0, ProcessInfo.processInfo.systemUptime - start) * segmentRate) |
| 531 | let pendingFrames = expectedFrames - Int(progress.snapshot().frames) |
| 532 | if pendingFrames > 0 { progress.received(frames: pendingFrames) } |
| 533 | } |
| 534 | #endif |
| 535 | let captured = progress.snapshot() |
| 536 | transcriptionDuration = previousDuration + Double(captured.frames) / segmentRate |
| 537 | liveActivity.update(seconds: transcriptionDuration, recording: true) |
| 538 | if captured.stalled { |
| 539 | handleInterruption("The microphone stopped delivering audio. Transcription is paused; the timer counts microphone input only. Close iPhone Mirroring or another app using the microphone, then tap Resume. Words already transcribed are saved.") |
| 540 | } |
| 541 | } |
| 542 | nonisolated static func microphoneErrorMessage(_ error: Error) -> String { |
| 543 | if error is LocalError { return error.localizedDescription } |
| 544 | return "Jotley couldn’t start the microphone. Close iPhone Mirroring or another app using audio, check Microphone in Settings → Apps → Jotley, then try again. Existing notes are preserved." |
| 545 | } |
| 546 | nonisolated static func monoPCM(_ buffer: AVReadOnlyAudioPCMBuffer) throws -> Data { |
| 547 | try monoPCM(AVAudioPCMBuffer(copying: buffer)) |
| 548 | } |
| 549 | nonisolated static func monoPCM(_ buffer: AVAudioPCMBuffer) throws -> Data { |
| 550 | guard let channels = buffer.floatChannelData else { throw LocalError.message("Microphone returned no PCM samples.") } |
| 551 | let count = Int(buffer.frameLength); let channelCount = Int(buffer.format.channelCount) |
| 552 | var samples = [Float](repeating: 0, count: count) |
| 553 | for frame in 0..<count { |
| 554 | for channel in 0..<channelCount { samples[frame] += channels[channel][frame] / Float(channelCount) } |
| 555 | } |
| 556 | return samples.withUnsafeBytes { Data($0) } |
| 557 | } |
| 558 | private func closeSegment() { |
| 559 | #if DEBUG && targetEnvironment(simulator) |
| 560 | simulatedSegmentStart = nil |
| 561 | #endif |
| 562 | if let engineObserver { notificationCenter.removeObserver(engineObserver); self.engineObserver = nil } |
| 563 | engine?.stop() |
| 564 | if tapInstalled { engine?.inputNode.removeTap(onBus: 0); tapInstalled = false } |
| 565 | engine = nil |
| 566 | if let progress = captureProgress, segmentRate > 0 { |
| 567 | previousDuration += Double(progress.snapshot().frames) / segmentRate |
| 568 | } |
| 569 | captureProgress = nil; transcriptionDuration = previousDuration |
| 570 | waveformPeaks = []; lastWaveformPeak = 0 |
| 571 | } |
| 572 | private func speechFailed(_ error: Error, sessionID token: UUID) { |
| 573 | guard sessionID == token, !endingSession, !speechHasFailed else { return } |
| 574 | speechHasFailed = true |
| 575 | let message = "Live transcription stopped: \(error.localizedDescription) Words received so far remain in the note. Only transcript text is saved." |
| 576 | if busy { pendingStop = message } |
| 577 | else { |
| 578 | errorMessage = message |
| 579 | Task { @MainActor [weak self] in await self?.stopTranscription() } |
| 580 | } |
| 581 | } |
| 582 | func pauseTranscription() { |
| 583 | guard transcriptionState == .listening, !busy, stopRequests == 0 else { return } |
| 584 | closeSegment(); transcriptionState = .paused |
| 585 | liveActivity.update(seconds: transcriptionDuration, recording: false, force: true) |
| 586 | } |
| 587 | func resumeTranscription() async { |
| 588 | guard transcriptionState == .paused, !busy, stopRequests == 0, activeNoteID != nil else { return } |
| 589 | busy = true; defer { finishTransition() } |
| 590 | do { |
| 591 | try await startSegment() |
| 592 | guard stopRequests == 0 else { return } |
| 593 | transcriptionState = .listening |
| 594 | liveActivity.update(seconds: transcriptionDuration, recording: true, force: true) |
| 595 | } catch { closeSegment(); errorMessage = Self.microphoneErrorMessage(error) } |
| 596 | } |
| 597 | func stopTranscription() async { |
| 598 | // A Stop/Close during setup, Resume or another Stop must wait for the |
| 599 | // transition, rather than dismissing the sheet with an active engine. |
| 600 | stopRequests += 1 |
| 601 | defer { stopRequests -= 1 } |
| 602 | while busy { |
| 603 | await withCheckedContinuation { transitionWaiters.append($0) } |
| 604 | } |
| 605 | guard isTranscribing || speech != nil || activeNoteID != nil else { return } |
| 606 | busy = true; defer { finishTransition() } |
| 607 | // Finalization returns an authoritative snapshot. Fence queued streaming |
| 608 | // callbacks now so they cannot overwrite it, even after Close returns. |
| 609 | flushTranscript() |
| 610 | endingSession = true; sessionID = nil |
| 611 | closeSegment(); timer?.invalidate(); timer = nil |
| 612 | // An interrupted session with no buffers has nothing to finalize. Waiting |
| 613 | // for speech results in this state can leave Stop stuck indefinitely. |
| 614 | if transcriptionDuration == 0 || speechHasFailed { await speech?.cancel() } |
| 615 | else { |
| 616 | do { if let speech { accept(try await speech.finish()) } } catch { errorMessage = "Live transcription could not finish: \(error.localizedDescription). Words received so far remain in the note. Only transcript text is saved." } |
| 617 | } |
| 618 | speech = nil; sessionID = nil; transcriptionState = .idle |
| 619 | liveActivity.end(seconds: transcriptionDuration) |
| 620 | if let id = activeNoteID, let note = fetch(id) { store?.organizeCompletedRecording(note, locale: locale) } |
| 621 | activeNoteID = nil |
| 622 | await LocalAudioSession.shared.deactivate(owner: audioSessionOwner) |
| 623 | if let captureLease { store?.endRecording(lease: captureLease); self.captureLease = nil } |
| 624 | } |
| 625 | private func stageTranscript(_ value: LocalTranscript, token: UUID) { |
| 626 | pendingTranscript = value |
| 627 | guard transcriptFlushTask == nil else { return } |
| 628 | transcriptFlushTask = Task { [weak self] in |
| 629 | do { try await Task.sleep(for: .milliseconds(250)) } catch { return } |
| 630 | guard let self, self.sessionID == token, !self.endingSession else { return } |
| 631 | self.flushTranscript() |
| 632 | } |
| 633 | } |
| 634 | private func flushTranscript() { |
| 635 | transcriptFlushTask?.cancel(); transcriptFlushTask = nil |
| 636 | if let value = pendingTranscript { |
| 637 | pendingTranscript = nil |
| 638 | accept(value) |
| 639 | } |
| 640 | } |
| 641 | |
| 642 | private func accept(_ value: LocalTranscript) { |
| 643 | guard let store, let id = activeNoteID, let note = fetch(id), !note.isDeleted else { return } |
| 644 | liveTranscript = [baseTranscript, value.displayText].filter { !$0.isEmpty }.joined(separator: " ") |
| 645 | let checkpoint = MobileTranscriptCheckpoint(baseText: baseTranscript, |
| 646 | baseUtterances: baseUtterances, offset: transcriptOffset) |
| 647 | liveUtterances = checkpoint.displayUtterances(for: value) |
| 648 | do { |
| 649 | _ = try checkpoint.save(value, to: note, in: store) |
| 650 | } catch { |
| 651 | // A failed checkpoint is fatal for a session without an audio backup. |
| 652 | if endingSession { errorMessage = "Could not save the latest transcript: \(error.localizedDescription)" } |
| 653 | else if let sessionID { speechFailed(error, sessionID: sessionID) } |
| 654 | } |
| 655 | } |
| 656 | |
| 657 | private func fetch(_ id: UUID) -> Note? { |
| 658 | guard let store else { return nil } |
| 659 | let request = NSFetchRequest<Note>(entityName: "Note"); request.predicate = NSPredicate(format: "id == %@ AND trashedAt == nil", id as CVarArg); request.fetchLimit = 1 |
| 660 | return try? store.context.fetch(request).first |
| 661 | } |
| 662 | |
| 663 | |
| 664 | func delete(_ note: Note) throws { |
| 665 | guard !busy, !isTranscribing, summaryNoteID == nil, let store else { throw LocalError.message("Finish transcribing or processing before deleting a note.") } |
| 666 | try store.deleteNote(note) |
| 667 | } |
| 668 | |
| 669 | func summarize(_ note: Note, template: LocalSummaryTemplate) { |
| 670 | summarize(note, template: SummaryTemplateDefinition(template)) |
| 671 | } |
| 672 | func summarize(_ note: Note, template: SummaryTemplateDefinition) { |
| 673 | guard canStart, store != nil, let id = note.id else { return } |
| 674 | let job = MobileSummaryJob(noteID: id, templateKey: template.key, localeIdentifier: locale.identifier, |
| 675 | checkpoint: LocalSummaryCheckpoint(input: note.transcription ?? "", template: template), templateDefinition: template) |
| 676 | do { try persistSummaryJob(job) } |
| 677 | catch { errorMessage = "Could not save summary recovery: \(error.localizedDescription)"; return } |
| 678 | summaryNotifications.prepareForSummary() |
| 679 | startSummary(note, job: job) |
| 680 | } |
| 681 | |
| 682 | private func persistSummaryJob(_ job: MobileSummaryJob) throws { |
| 683 | guard let url = summaryRecoveryURL else { throw LocalError.message("Local notes are unavailable.") } |
| 684 | try JSONEncoder().encode(job).write(to: url, options: [.atomic, .completeFileProtectionUntilFirstUserAuthentication]) |
| 685 | pendingSummaryJob = job |
| 686 | } |
| 687 | private func removeSummaryJob() { |
| 688 | pendingSummaryJob = nil |
| 689 | guard let url = summaryRecoveryURL, FileManager.default.fileExists(atPath: url.path) else { return } |
| 690 | do { try FileManager.default.removeItem(at: url) } |
| 691 | catch { errorMessage = "Could not remove summary recovery: \(error.localizedDescription)" } |
| 692 | } |
| 693 | func resumePendingSummary(applicationState: UIApplication.State = UIApplication.shared.applicationState) { |
| 694 | guard applicationState == .active, summaryTask == nil, |
| 695 | !busy, !isTranscribing, let job = pendingSummaryJob else { return } |
| 696 | guard let note = fetch(job.noteID), note.transcription == job.checkpoint.input else { |
| 697 | removeSummaryJob(); summaryNoteID = nil; summaryPausedBySystem = false; return |
| 698 | } |
| 699 | startSummary(note, job: job) |
| 700 | } |
| 701 | /// Navigation/backgrounding never calls this. Only Apple's expiration |
| 702 | /// handler pauses inference; completed sections remain in the local record. |
| 703 | func pauseSummaryForSystem() { |
| 704 | guard summaryTask != nil else { return } |
| 705 | summaryPausedBySystem = true |
| 706 | summaryProgress = .waitingForForeground |
| 707 | summaryTask?.cancel() |
| 708 | } |
| 709 | private func startSummary(_ note: Note, job: MobileSummaryJob) { |
| 710 | guard let store else { return } |
| 711 | let id = job.noteID |
| 712 | guard let template = job.templateDefinition ?? (try? SummaryTemplateStore.shared.resolve(job.templateKey)) else { |
| 713 | errorMessage = "The summary template is unavailable. Choose a template and generate again. Your saved note is unchanged." |
| 714 | return |
| 715 | } |
| 716 | let locale = Locale(identifier: job.localeIdentifier) |
| 717 | summaryPausedBySystem = false |
| 718 | summaryNoteID = id; summaryPreview = job.checkpoint.result ?? ""; summaryProgress = .preparing; errorMessage = nil |
| 719 | let runtime = SummaryBackgroundRuntime { [weak self] in self?.pauseSummaryForSystem() } |
| 720 | summaryRuntime = runtime; runtime.begin() |
| 721 | let canFileNote = note.folder == nil |
| 722 | summaryTask = Task { [weak self] in |
| 723 | guard let self else { return } |
| 724 | var completed = false |
| 725 | defer { |
| 726 | runtime.finish(success: completed); self.summaryRuntime = nil; self.summaryTask = nil |
| 727 | if self.summaryPausedBySystem { |
| 728 | self.summaryProgress = .waitingForForeground |
| 729 | // Expiration can race returning to the foreground. Restart |
| 730 | // only after the old inference has fully unwound. |
| 731 | Task { @MainActor [weak self] in self?.resumePendingSummary() } |
| 732 | } else { |
| 733 | self.summaryNoteID = nil; self.summaryPreview = ""; self.summaryProgress = .preparing |
| 734 | } |
| 735 | } |
| 736 | do { |
| 737 | let update: @Sendable (String) async -> Void = { [weak self] value in |
| 738 | guard !Task.isCancelled else { return } |
| 739 | await MainActor.run { [weak self] in |
| 740 | guard let self, self.summaryNoteID == id else { return } |
| 741 | if self.summaryPreview != value { self.summaryPreview = value } |
| 742 | if !value.isEmpty { |
| 743 | if self.summaryProgress != .writing { |
| 744 | self.summaryProgress = .writing |
| 745 | self.summaryRuntime?.update(.writing) |
| 746 | } |
| 747 | self.summaryRuntime?.streamed() |
| 748 | } |
| 749 | } |
| 750 | } |
| 751 | let progress: @Sendable (LocalSummaryProgress) async -> Void = { [weak self] value in |
| 752 | guard !Task.isCancelled else { return } |
| 753 | await MainActor.run { [weak self] in |
| 754 | guard self?.summaryNoteID == id else { return } |
| 755 | self?.summaryProgress = value; self?.summaryRuntime?.update(value) |
| 756 | } |
| 757 | } |
| 758 | let checkpoint: @Sendable (LocalSummaryCheckpoint) async throws -> Void = { [weak self] state in |
| 759 | try Task.checkCancellation() |
| 760 | try await MainActor.run { [weak self] in |
| 761 | guard let self, self.summaryNoteID == id, self.pendingSummaryJob != nil else { throw CancellationError() } |
| 762 | var next = job; next.checkpoint = state |
| 763 | try self.persistSummaryJob(next) |
| 764 | } |
| 765 | } |
| 766 | let modelResult: String |
| 767 | if let savedResult = job.checkpoint.result { modelResult = savedResult } |
| 768 | else { |
| 769 | #if DEBUG && targetEnvironment(simulator) |
| 770 | if let simulatedSummaryGeneration { modelResult = try await simulatedSummaryGeneration(update) } |
| 771 | else { modelResult = try await LocalSummary.generate(job.checkpoint.input, template: template, locale: locale, |
| 772 | resuming: job.checkpoint, checkpoint: checkpoint, progress: progress, snapshot: update) } |
| 773 | #else |
| 774 | modelResult = try await LocalSummary.generate(job.checkpoint.input, template: template, locale: locale, |
| 775 | resuming: job.checkpoint, checkpoint: checkpoint, progress: progress, snapshot: update) |
| 776 | #endif |
| 777 | } |
| 778 | let result: String |
| 779 | if LocalSummary.firstContentLine(in: modelResult) != nil { result = modelResult } |
| 780 | else if let transcriptLine = LocalSummary.firstContentLine(in: job.checkpoint.input) { |
| 781 | // A short recording can produce a heading with no summary body. |
| 782 | result = transcriptLine |
| 783 | } else { |
| 784 | throw LocalError.message("The model returned no summary. Your current note was preserved.") |
| 785 | } |
| 786 | // Keep the completed model result before the separate title call. |
| 787 | var finishedJob = self.pendingSummaryJob ?? job; finishedJob.checkpoint.result = result |
| 788 | try self.persistSummaryJob(finishedJob) |
| 789 | var generatedTitle: String? |
| 790 | if note.shouldReplaceTitleFromGeneratedSummary() { |
| 791 | self.summaryProgress = .finishing; runtime.update(.finishing) |
| 792 | do { |
| 793 | #if DEBUG && targetEnvironment(simulator) |
| 794 | if let simulatedTitleGeneration { |
| 795 | generatedTitle = LocalSummary.descriptiveTitle(try await simulatedTitleGeneration(result)) |
| 796 | } else { generatedTitle = try await LocalSummary.generateTitle(from: result, locale: locale) } |
| 797 | #else |
| 798 | generatedTitle = try await LocalSummary.generateTitle(from: result, locale: locale) |
| 799 | #endif |
| 800 | } catch { |
| 801 | try Task.checkCancellation() |
| 802 | if error is CancellationError { throw error } |
| 803 | } |
| 804 | if generatedTitle == nil { |
| 805 | generatedTitle = LocalSummary.fallbackTitle(transcript: job.checkpoint.input, summary: result) |
| 806 | } |
| 807 | } |
| 808 | let autoTags = note.shouldGenerateSummaryTags |
| 809 | let autoFolder = canFileNote && note.folder == nil && LocalNoteOrganizationSettings.autoFolders() |
| 810 | let library = autoTags ? try store.tagLibrary() : [] |
| 811 | var organization: LocalNoteOrganization? |
| 812 | if autoTags || autoFolder { |
| 813 | self.summaryProgress = .organizingTags; runtime.update(.organizingTags) |
| 814 | do { |
| 815 | #if DEBUG && targetEnvironment(simulator) |
| 816 | if let simulatedOrganization { organization = try await simulatedOrganization(result, library) } |
| 817 | else { |
| 818 | organization = try await LocalNoteTags.generateOrganization(from: result, transcript: job.checkpoint.input, |
| 819 | library: library, locale: locale, autoTags: autoTags, autoFolder: autoFolder) |
| 820 | } |
| 821 | #else |
| 822 | organization = try await LocalNoteTags.generateOrganization(from: result, transcript: job.checkpoint.input, |
| 823 | library: library, locale: locale, autoTags: autoTags, autoFolder: autoFolder) |
| 824 | #endif |
| 825 | } catch is CancellationError { throw CancellationError() } |
| 826 | catch { organization = nil } |
| 827 | } |
| 828 | try Task.checkCancellation() |
| 829 | guard !note.isDeleted, note.transcription == job.checkpoint.input else { |
| 830 | throw LocalError.message("This transcript changed during generation. Your current note was preserved; generate a summary again.") |
| 831 | } |
| 832 | let tags = autoTags && note.shouldGenerateSummaryTags |
| 833 | ? LocalNoteTags.completedNames(organization?.tags, transcript: job.checkpoint.input, |
| 834 | summary: result, library: library, excluding: note.tagNames) |
| 835 | : nil |
| 836 | let filingSource = result + "\n" + job.checkpoint.input |
| 837 | let category = organization?.folder.name == nil ? LocalNoteFolder.inferred(from: filingSource) : organization?.folder |
| 838 | let folder = autoFolder && LocalNoteOrganizationSettings.autoFolders() ? category : nil |
| 839 | try store.saveNoteChanges(note, values: note.generatedSummaryValues(result, template: template.key, generatedTitle: generatedTitle), |
| 840 | addingGeneratedTags: tags, autoFolder: folder, |
| 841 | projectName: organization?.projectName, filingSource: filingSource) |
| 842 | self.removeSummaryJob(); completed = true |
| 843 | await self.summaryNotifications.summarySaved(noteID: id) |
| 844 | } catch is CancellationError { |
| 845 | if !self.summaryPausedBySystem { self.removeSummaryJob() } |
| 846 | } catch { |
| 847 | if Task.isCancelled { |
| 848 | if !self.summaryPausedBySystem { self.removeSummaryJob() } |
| 849 | } else if UIApplication.shared.applicationState != .active { |
| 850 | self.summaryPausedBySystem = true |
| 851 | } else { self.removeSummaryJob(); self.errorMessage = error.localizedDescription } |
| 852 | } |
| 853 | } |
| 854 | } |
| 855 | func cancelProcessing() { |
| 856 | summaryPausedBySystem = false; removeSummaryJob() |
| 857 | summaryTask?.cancel() |
| 858 | if summaryTask == nil { summaryNoteID = nil; summaryPreview = ""; summaryProgress = .preparing } |
| 859 | } |
| 860 | func saveEdits() { flushTranscript(); do { try store?.save() } catch { errorMessage = error.localizedDescription } } |
| 861 | } |
| 862 | |
| 863 | // Keep the existing Codable names for installed Live Activity compatibility. |
| 864 | // This schema is also used by the widget extension. No note text, |
| 865 | // microphone samples, remote token or shared-container access is needed. |
| 866 | struct RecordingActivityAttributes: ActivityAttributes { |
| 867 | struct ContentState: Codable, Hashable { |
| 868 | var elapsedSeconds: Int |
| 869 | var isRecording: Bool |
| 870 | var lastUpdatedAt: Date? |
| 871 | var themeColor: ThemeColor? = nil |
| 872 | var formattedDuration: String { String(format: "%d:%02d", elapsedSeconds / 60, elapsedSeconds % 60) } |
| 873 | var timerStartDate: Date { (lastUpdatedAt ?? Date()).addingTimeInterval(-Double(elapsedSeconds)) } |
| 874 | } |
| 875 | var recordingId: String |
| 876 | var startTime: Date |
| 877 | } |
| 878 | |
| 879 | @MainActor private final class LocalTranscriptionLiveActivity { |
| 880 | private var activity: Activity<RecordingActivityAttributes>? |
| 881 | private var lastUpdate = Date.distantPast |
| 882 | private var transition: Task<Void, Never>? |
| 883 | private var transitionID: UUID? |
| 884 | init() { |
| 885 | let orphans = Activity<RecordingActivityAttributes>.activities |
| 886 | enqueue { for item in orphans { await item.end(nil, dismissalPolicy: .immediate) } } |
| 887 | } |
| 888 | func start(noteID: UUID) { |
| 889 | guard ActivityAuthorizationInfo().areActivitiesEnabled else { return } |
| 890 | let state = makeState(seconds: 0, recording: true) |
| 891 | do { |
| 892 | activity = try Activity.request(attributes: RecordingActivityAttributes(recordingId: noteID.uuidString, startTime: Date()), |
| 893 | content: ActivityContent(state: state, staleDate: nil), pushType: nil) |
| 894 | lastUpdate = Date() |
| 895 | } catch { |
| 896 | // Live Activities are optional; denied/disabled activities must never |
| 897 | // block microphone capture or the user's transcript. |
| 898 | activity = nil |
| 899 | } |
| 900 | } |
| 901 | func update(seconds: TimeInterval, recording: Bool, force: Bool = false) { |
| 902 | guard let activity, force || Date().timeIntervalSince(lastUpdate) >= 15 else { return } |
| 903 | lastUpdate = Date() |
| 904 | let state = makeState(seconds: seconds, recording: recording) |
| 905 | enqueue { await activity.update(ActivityContent(state: state, staleDate: nil)) } |
| 906 | } |
| 907 | func end(seconds: TimeInterval) { |
| 908 | guard let activity else { return } |
| 909 | self.activity = nil |
| 910 | let state = makeState(seconds: seconds, recording: false) |
| 911 | enqueue { await activity.end(ActivityContent(state: state, staleDate: nil), dismissalPolicy: .immediate) } |
| 912 | } |
| 913 | private func makeState(seconds: TimeInterval, recording: Bool) -> RecordingActivityAttributes.ContentState { |
| 914 | .init(elapsedSeconds: max(0, Int(seconds)), isRecording: recording, lastUpdatedAt: Date(), |
| 915 | themeColor: ThemeManager.shared.currentThemeColor) |
| 916 | } |
| 917 | private func enqueue(_ operation: @escaping @MainActor () async -> Void) { |
| 918 | let previous = transition, id = UUID() |
| 919 | transitionID = id |
| 920 | transition = Task { @MainActor in |
| 921 | await previous?.value |
| 922 | await operation() |
| 923 | if transitionID == id { transition = nil; transitionID = nil } |
| 924 | } |
| 925 | } |
| 926 | } |