Jotley / app / macOS / ViewModels / NotesListViewModel.swift
| 1 | import SwiftUI |
| 2 | import CoreData |
| 3 | import Combine |
| 4 | import AppKit |
| 5 | |
| 6 | // Retains the existing view-facing model while all capture and inference run locally. |
| 7 | @MainActor final class NotesListViewModel: ObservableObject { |
| 8 | let viewContext: NSManagedObjectContext |
| 9 | let recorder: ProcessTapRecorder |
| 10 | let summaryNotifications: JotleySummaryNotifications |
| 11 | let persistenceController: SharedPersistenceController |
| 12 | @Published var newNoteBeingRecorded: Note? |
| 13 | @Published var isTranscriptionPaused = false |
| 14 | @Published var accumulatedTranscription = "" |
| 15 | @Published var selectedNoteIDs: Set<NSManagedObjectID> = [] |
| 16 | @Published var selectedDetailTab = DetailTab.transcript.rawValue |
| 17 | @Published var showSyncError = false |
| 18 | @Published var syncErrorMessage = "" |
| 19 | @Published var isGeneratingSummary = false |
| 20 | @Published var generatingSummaryNoteID: NSManagedObjectID? |
| 21 | @Published var generatingSummaryStartedAt: Date? |
| 22 | @Published var operationInProgress = false |
| 23 | var pendingFolderSelection: FolderSelection = .all |
| 24 | var activeRecordingNote: Note? { recorder.isRecording ? newNoteBeingRecorded : nil } |
| 25 | let streamingSummaryViewModel = StreamingSummaryViewModel() |
| 26 | var summaryProgress: LocalSummaryProgress { streamingSummaryViewModel.progress } |
| 27 | private var subscriptions: Set<AnyCancellable> = [] |
| 28 | private var inference: Task<Void, Never>? |
| 29 | #if DEBUG |
| 30 | var simulatedSummaryGeneration: (@MainActor (@escaping @Sendable (String) async -> Void) async throws -> String)? |
| 31 | var simulatedOrganization: (@MainActor (String, [LocalTagCandidate]) async throws -> LocalNoteOrganization)? |
| 32 | #endif |
| 33 | private var recordingLease: UUID? |
| 34 | private var summaryLease: UUID? |
| 35 | private var stopTask: Task<Void, Never>? |
| 36 | private var isConfirmingCapture = false |
| 37 | private var baseText = "" |
| 38 | private var baseUtterances: [TranscriptUtterance] = [] |
| 39 | init(viewContext: NSManagedObjectContext, recorder: ProcessTapRecorder, persistenceController: SharedPersistenceController, summaryNotifications: JotleySummaryNotifications? = nil) { |
| 40 | self.summaryNotifications = summaryNotifications ?? .shared |
| 41 | self.viewContext = viewContext; self.recorder = recorder; self.persistenceController = persistenceController |
| 42 | streamingSummaryViewModel.objectWillChange.sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &subscriptions) |
| 43 | // The waveform polls its meter directly. Audio-level changes must not |
| 44 | // invalidate the entire sidebar, note detail and transcript bubble tree. |
| 45 | let captureChanges: [AnyPublisher<Void, Never>] = [ |
| 46 | recorder.$recording.map { _ in () }.eraseToAnyPublisher(), |
| 47 | recorder.$paused.map { _ in () }.eraseToAnyPublisher(), |
| 48 | recorder.$starting.map { _ in () }.eraseToAnyPublisher(), |
| 49 | recorder.$finishing.map { _ in () }.eraseToAnyPublisher(), |
| 50 | recorder.$elapsed.map { _ in () }.eraseToAnyPublisher(), |
| 51 | recorder.$transcription.map { _ in () }.eraseToAnyPublisher(), |
| 52 | recorder.$errorMessage.map { _ in () }.eraseToAnyPublisher() |
| 53 | ] |
| 54 | Publishers.MergeMany(captureChanges).sink { [weak self] _ in self?.objectWillChange.send() }.store(in: &subscriptions) |
| 55 | } |
| 56 | func saveContext() { |
| 57 | do { try persistenceController.save() } catch { report(error) } |
| 58 | } |
| 59 | func report(_ error: Error) { syncErrorMessage = error.localizedDescription; showSyncError = true } |
| 60 | @discardableResult |
| 61 | func createBlankNote(text: String = "", title: String = "Untitled Note") -> Note? { |
| 62 | guard !recorder.isRecording, !recorder.isBusy, !operationInProgress, !LocalAppModel.shared.busy else { return nil } |
| 63 | do { |
| 64 | guard let note = try persistenceController.create(title: title, text: text) as? Note else { |
| 65 | throw LocalError.message("Unable to create a local note.") |
| 66 | } |
| 67 | if case .folder(let id) = pendingFolderSelection { |
| 68 | let request = Folder.fetchRequest(); request.predicate = NSPredicate(format: "id == %@", id as CVarArg) |
| 69 | note.folder = try viewContext.fetch(request).first |
| 70 | } |
| 71 | try persistenceController.save(); LocalAppModel.shared.selected = note.id; try LocalAppModel.shared.reload(); selectedNoteIDs = [note.objectID]; selectedDetailTab = DetailTab.transcript.rawValue |
| 72 | return note |
| 73 | } catch { report(error); return nil } |
| 74 | } |
| 75 | func startNewNote() async { |
| 76 | guard canStartCapture, let systemAudio = await confirmCapture(), canStartCapture else { return } |
| 77 | guard let note = createBlankNote() else { return } |
| 78 | await startCapture(on: note, systemAudio: systemAudio) |
| 79 | } |
| 80 | func resumeTranscriptionOnNote(note: Note) async { |
| 81 | guard canStartCapture, let systemAudio = await confirmCapture(), canStartCapture else { return } |
| 82 | await startCapture(on: note, systemAudio: systemAudio) |
| 83 | } |
| 84 | |
| 85 | private var canStartCapture: Bool { |
| 86 | !recorder.isRecording && !recorder.isBusy && !operationInProgress && !LocalAppModel.shared.busy && !isConfirmingCapture |
| 87 | } |
| 88 | |
| 89 | private func confirmCapture() async -> Bool? { |
| 90 | guard UserDefaults.standard.object(forKey: "recordSystemAudio") as? Bool ?? true else { return false } |
| 91 | #if DEBUG |
| 92 | if recorder.simulatedStart != nil { return true } |
| 93 | #endif |
| 94 | isConfirmingCapture = true |
| 95 | defer { isConfirmingCapture = false } |
| 96 | let alert = NSAlert() |
| 97 | alert.messageText = "Before you transcribe a call" |
| 98 | alert.informativeText = "Jotley doesn’t join the call or notify anyone. Tell the other participants and get their permission before transcribing. Microphone-only mode can still pick up people you hear through speakers." |
| 99 | alert.addButton(withTitle: "Start with System Audio") |
| 100 | alert.addButton(withTitle: "Use Microphone Only") |
| 101 | let cancel = alert.addButton(withTitle: "Cancel") |
| 102 | alert.buttons.first?.keyEquivalent = "" |
| 103 | cancel.keyEquivalent = "\u{1b}" |
| 104 | let response: NSApplication.ModalResponse |
| 105 | if let window = NSApp.keyWindow ?? NSApp.mainWindow, window.isVisible, window.attachedSheet == nil { |
| 106 | response = await alert.beginSheetModal(for: window) |
| 107 | } else { |
| 108 | NSApp.activate() |
| 109 | response = alert.runModal() |
| 110 | } |
| 111 | switch response { |
| 112 | case .alertFirstButtonReturn: return true |
| 113 | case .alertSecondButtonReturn: return false |
| 114 | default: return nil |
| 115 | } |
| 116 | } |
| 117 | |
| 118 | private func startCapture(on note: Note, systemAudio: Bool) async { |
| 119 | operationInProgress = true; defer { operationInProgress = false } |
| 120 | do { |
| 121 | guard note.managedObjectContext === viewContext, !note.isDeleted else { |
| 122 | throw LocalError.message("This note is unavailable.") |
| 123 | } |
| 124 | recordingLease = try persistenceController.beginRecording(note) |
| 125 | let id = note.id ?? UUID(); note.id = id |
| 126 | note.noteType = "transcription" |
| 127 | try persistenceController.save() |
| 128 | baseText = note.transcription ?? ""; baseUtterances = note.transcriptUtterances |
| 129 | recorder.onTranscript = { [weak self] value in self?.persistLiveTranscript(value) } |
| 130 | recorder.existingTranscript = baseText |
| 131 | recorder.existingUtterances = baseUtterances |
| 132 | JotleyAppDelegate.shared?.recordingNotesViewModel = self |
| 133 | LocalAppModel.shared.selected = note.id |
| 134 | newNoteBeingRecorded = note; selectedNoteIDs = [note.objectID]; selectedDetailTab = DetailTab.transcript.rawValue |
| 135 | recorder.speechLocale = Locale(identifier: UserDefaults.standard.string(forKey: "transcriptionLanguage") ?? "en-US") |
| 136 | try await recorder.start(root: persistenceController.root, noteID: id, systemAudio: systemAudio) |
| 137 | LocalAppModel.shared.message = "" |
| 138 | isTranscriptionPaused = false |
| 139 | if let message = recorder.errorMessage { syncErrorMessage = message; showSyncError = true } |
| 140 | } catch { |
| 141 | newNoteBeingRecorded = nil |
| 142 | if let recordingLease { persistenceController.endRecording(lease: recordingLease); self.recordingLease = nil } |
| 143 | if JotleyAppDelegate.shared?.recordingNotesViewModel === self { JotleyAppDelegate.shared?.recordingNotesViewModel = nil } |
| 144 | report(error) |
| 145 | } |
| 146 | } |
| 147 | private func persistLiveTranscript(_ value: LocalTranscript) { |
| 148 | guard let note = newNoteBeingRecorded, |
| 149 | note.managedObjectContext === viewContext, !note.isDeleted else { return } |
| 150 | // Save only finalized words; tentative snapshots remain transient in the UI. |
| 151 | let text = [baseText, value.text].filter { !$0.isEmpty }.joined(separator: " ") |
| 152 | accumulatedTranscription = [baseText, value.displayText].filter { !$0.isEmpty }.joined(separator: " ") |
| 153 | if !value.text.isEmpty { |
| 154 | note.transcription = text |
| 155 | let offset = recorder.transcriptTimeOffset |
| 156 | note.setTranscriptUtterances(baseUtterances + value.utterances.map { |
| 157 | TranscriptUtterance(text: $0.text, start: offset + $0.start, end: offset + $0.end) |
| 158 | }) |
| 159 | saveContext() |
| 160 | } |
| 161 | } |
| 162 | func updateNewNoteTranscription() { objectWillChange.send() } |
| 163 | func resumeTranscription() async { |
| 164 | guard recorder.isRecording else { return } |
| 165 | defer { isTranscriptionPaused = recorder.paused } |
| 166 | do { try recorder.togglePause() } catch { report(error) } |
| 167 | } |
| 168 | func stopRecording() async { |
| 169 | if let stopTask { await stopTask.value; return } |
| 170 | if let owner = JotleyAppDelegate.shared?.recordingNotesViewModel, owner !== self { |
| 171 | await owner.stopRecording(); return |
| 172 | } |
| 173 | guard recorder.isRecording || newNoteBeingRecorded != nil else { return } |
| 174 | let task = Task { @MainActor in |
| 175 | operationInProgress = true |
| 176 | defer { |
| 177 | if let recordingLease { persistenceController.endRecording(lease: recordingLease); self.recordingLease = nil } |
| 178 | if let note = newNoteBeingRecorded, selectedNoteIDs.contains(note.objectID) { |
| 179 | selectedDetailTab = DetailTab.transcript.rawValue |
| 180 | } |
| 181 | newNoteBeingRecorded = nil; isTranscriptionPaused = false; operationInProgress = false; stopTask = nil |
| 182 | if JotleyAppDelegate.shared?.recordingNotesViewModel === self { JotleyAppDelegate.shared?.recordingNotesViewModel = nil } |
| 183 | } |
| 184 | _ = await recorder.stop() |
| 185 | do { |
| 186 | try persistenceController.save() |
| 187 | if let note = newNoteBeingRecorded { |
| 188 | persistenceController.organizeCompletedRecording(note, locale: recorder.speechLocale) |
| 189 | } |
| 190 | } catch { report(error) } |
| 191 | if let error = recorder.errorMessage { syncErrorMessage = error; showSyncError = true } |
| 192 | } |
| 193 | stopTask = task; await task.value |
| 194 | } |
| 195 | func isTranscriptLoading(for _: Note) -> Bool { false } |
| 196 | func summaryLoadingStartedAt(for noteID: NSManagedObjectID) -> Date? { generatingSummaryNoteID == noteID ? generatingSummaryStartedAt : nil } |
| 197 | func beginSummaryGeneration(for id: NSManagedObjectID) { |
| 198 | if let summaryLease { persistenceController.endNoteOperation(lease: summaryLease) } |
| 199 | summaryLease = persistenceController.beginNoteOperation(for: id) |
| 200 | isGeneratingSummary = true; generatingSummaryNoteID = id; generatingSummaryStartedAt = Date() |
| 201 | } |
| 202 | func endSummaryGeneration(for id: NSManagedObjectID) { |
| 203 | guard generatingSummaryNoteID == id else { return } |
| 204 | if let summaryLease { persistenceController.endNoteOperation(lease: summaryLease); self.summaryLease = nil } |
| 205 | isGeneratingSummary = false; generatingSummaryNoteID = nil; generatingSummaryStartedAt = nil |
| 206 | } |
| 207 | |
| 208 | func toggleSelection(for note: Note, isCommandKeyPressed: Bool = false) { |
| 209 | LocalAppModel.shared.selected = note.id |
| 210 | try? LocalAppModel.shared.reload() |
| 211 | NotificationCenter.default.post(name: Notification.Name("JotVibeSaveCurrentNote"), object: nil) |
| 212 | if isCommandKeyPressed { |
| 213 | if selectedNoteIDs.contains(note.objectID) { |
| 214 | if selectedNoteIDs.count > 1 { selectedNoteIDs.remove(note.objectID) } |
| 215 | } |
| 216 | else { selectedNoteIDs.insert(note.objectID) } |
| 217 | } else { selectedNoteIDs = [note.objectID] } |
| 218 | selectedDetailTab = note.hasMeaningfulSummaryText ? DetailTab.summary.rawValue : DetailTab.transcript.rawValue |
| 219 | } |
| 220 | func ensureSelection(in notes: [Note]) { |
| 221 | let available = notes.filter { !$0.isDeleted } |
| 222 | let retained = selectedNoteIDs.intersection(Set(available.map(\.objectID))) |
| 223 | if !retained.isEmpty { |
| 224 | if retained != selectedNoteIDs { selectedNoteIDs = retained } |
| 225 | } else if let first = available.first { |
| 226 | toggleSelection(for: first) |
| 227 | } else if !selectedNoteIDs.isEmpty { selectedNoteIDs = [] } |
| 228 | } |
| 229 | func jumpToActiveRecordingNote() { if let note = activeRecordingNote { selectedNoteIDs = [note.objectID]; selectedDetailTab = DetailTab.transcript.rawValue } } |
| 230 | func performContextualDelete(for note: Note) { Task { await delete(note) } } |
| 231 | private func delete(_ note: Note) async { |
| 232 | guard !LocalAppModel.shared.busy, !recorder.isBusy else { |
| 233 | report(LocalError.message("Cancel or finish the current operation before deleting notes.")); return |
| 234 | } |
| 235 | if let owner = JotleyAppDelegate.shared?.recordingNotesViewModel, owner.newNoteBeingRecorded?.objectID == note.objectID { |
| 236 | await owner.stopRecording() |
| 237 | } else if note == newNoteBeingRecorded { await stopRecording() } |
| 238 | if generatingSummaryNoteID == note.objectID { inference?.cancel() } |
| 239 | let objectID = note.objectID |
| 240 | do { |
| 241 | try persistenceController.deleteNote(note) |
| 242 | selectedNoteIDs.remove(objectID) |
| 243 | try LocalAppModel.shared.reload() |
| 244 | } catch { report(error) } |
| 245 | } |
| 246 | func deleteSelectedNotes(fetchedNotes: FetchedResults<Note>) async { |
| 247 | for note in fetchedNotes.filter({ selectedNoteIDs.contains($0.objectID) }) { await delete(note) } |
| 248 | } |
| 249 | func deleteNotes(inGroup group: [Note], atOffsets offsets: IndexSet) async { |
| 250 | for i in offsets { await delete(group[i]) } |
| 251 | } |
| 252 | func generateSummary(note: Note, templateKey: String) async { |
| 253 | guard !operationInProgress, !isGeneratingSummary, !recorder.isRecording, !recorder.isBusy, !LocalAppModel.shared.busy else { return } |
| 254 | do { try persistenceController.requireExternalWriteAccess(to: note) } |
| 255 | catch { report(error); return } |
| 256 | let template: SummaryTemplateDefinition |
| 257 | do { template = try SummaryTemplateStore.shared.resolve(templateKey) } |
| 258 | catch { report(error); return } |
| 259 | summaryNotifications.prepareForSummary() |
| 260 | beginSummaryGeneration(for: note.objectID) |
| 261 | streamingSummaryViewModel.summary = ""; streamingSummaryViewModel.progress = .preparing |
| 262 | let source = note.transcription ?? "" |
| 263 | let canFileNote = note.folder == nil |
| 264 | let locale = Locale(identifier: UserDefaults.standard.string(forKey: "transcriptionLanguage") ?? "en-US") |
| 265 | let activity = ProcessInfo.processInfo.beginActivity(options: .userInitiatedAllowingIdleSystemSleep, |
| 266 | reason: "Finish on-device note summary") |
| 267 | let task = Task { @MainActor in |
| 268 | JotleyProcessing.shared.begin() |
| 269 | defer { |
| 270 | ProcessInfo.processInfo.endActivity(activity) |
| 271 | JotleyProcessing.shared.end() |
| 272 | } |
| 273 | defer { endSummaryGeneration(for: note.objectID); streamingSummaryViewModel.summary = ""; streamingSummaryViewModel.progress = .preparing } |
| 274 | do { |
| 275 | let update: @Sendable (String) async -> Void = { [weak self] text in |
| 276 | guard !Task.isCancelled else { return } |
| 277 | await MainActor.run { self?.streamingSummaryViewModel.summary = text; if !text.isEmpty { self?.streamingSummaryViewModel.progress = .writing } } |
| 278 | } |
| 279 | let progress: @Sendable (LocalSummaryProgress) async -> Void = { [weak self] value in |
| 280 | guard !Task.isCancelled else { return } |
| 281 | await MainActor.run { self?.streamingSummaryViewModel.progress = value } |
| 282 | } |
| 283 | let result: String |
| 284 | #if DEBUG |
| 285 | if let simulatedSummaryGeneration { result = try await simulatedSummaryGeneration(update) } |
| 286 | else { result = try await LocalSummary.generate(source, template: template, |
| 287 | locale: locale, progress: progress, snapshot: update) } |
| 288 | #else |
| 289 | result = try await LocalSummary.generate(source, template: template, |
| 290 | locale: locale, progress: progress, snapshot: update) |
| 291 | #endif |
| 292 | var generatedTitle: String? |
| 293 | if note.shouldReplaceTitleFromGeneratedSummary() { |
| 294 | streamingSummaryViewModel.progress = .finishing |
| 295 | do { |
| 296 | generatedTitle = try await LocalSummary.generateTitle(from: result, locale: locale) |
| 297 | } catch is CancellationError { throw CancellationError() } |
| 298 | catch {} |
| 299 | if generatedTitle == nil { |
| 300 | generatedTitle = LocalSummary.fallbackTitle(transcript: source, summary: result) |
| 301 | } |
| 302 | } |
| 303 | let autoTags = note.shouldGenerateSummaryTags |
| 304 | let autoFolder = canFileNote && note.folder == nil && LocalNoteOrganizationSettings.autoFolders() |
| 305 | let library = autoTags ? try persistenceController.tagLibrary() : [] |
| 306 | var organization: LocalNoteOrganization? |
| 307 | if autoTags || autoFolder { |
| 308 | streamingSummaryViewModel.progress = .organizingTags |
| 309 | do { |
| 310 | #if DEBUG |
| 311 | if let simulatedOrganization { organization = try await simulatedOrganization(result, library) } |
| 312 | else { |
| 313 | organization = try await LocalNoteTags.generateOrganization(from: result, transcript: source, |
| 314 | library: library, locale: locale, autoTags: autoTags, autoFolder: autoFolder) |
| 315 | } |
| 316 | #else |
| 317 | organization = try await LocalNoteTags.generateOrganization(from: result, transcript: source, |
| 318 | library: library, locale: locale, autoTags: autoTags, autoFolder: autoFolder) |
| 319 | #endif |
| 320 | } catch is CancellationError { throw CancellationError() } |
| 321 | catch { organization = nil } |
| 322 | } |
| 323 | try Task.checkCancellation() |
| 324 | guard !note.isDeleted else { return } |
| 325 | guard (note.transcription ?? "") == source else { |
| 326 | throw LocalError.message("This transcript changed during generation. Your current note was preserved; generate a summary again.") |
| 327 | } |
| 328 | let tags = autoTags && note.shouldGenerateSummaryTags |
| 329 | ? LocalNoteTags.completedNames(organization?.tags, transcript: source, summary: result, |
| 330 | library: library, excluding: note.tagNames) |
| 331 | : nil |
| 332 | let filingSource = result + "\n" + source |
| 333 | let category = organization?.folder.name == nil ? LocalNoteFolder.inferred(from: filingSource) : organization?.folder |
| 334 | let folder = autoFolder && LocalNoteOrganizationSettings.autoFolders() ? category : nil |
| 335 | try persistenceController.saveNoteChanges(note, values: note.generatedSummaryValues(result, template: template.key, generatedTitle: generatedTitle), |
| 336 | addingGeneratedTags: tags, autoFolder: folder, |
| 337 | projectName: organization?.projectName, filingSource: filingSource) |
| 338 | await summaryNotifications.summarySaved(noteID: note.id) |
| 339 | NotificationCenter.default.post(name: Notification.Name("SummaryGenerationComplete"), object: nil, |
| 340 | userInfo: ["noteID": note.objectID, "summary": result]) |
| 341 | } catch is CancellationError { } catch { report(error) } |
| 342 | } |
| 343 | inference = task; await task.value; inference = nil |
| 344 | } |
| 345 | func cancelInference() { inference?.cancel() } |
| 346 | } |
| 347 | @MainActor final class StreamingSummaryViewModel: ObservableObject { |
| 348 | @Published var summary = "" |
| 349 | @Published var progress: LocalSummaryProgress = .preparing |
| 350 | var displayedText: String { summary } |
| 351 | } |