From c085b7d49a87f6e06ee09778d91e520b55a7c595 Mon Sep 17 00:00:00 2001 From: ichen27 Date: Sun, 25 Oct 2026 09:56:06 -0400 Subject: [PATCH] Preserve dictations across interruptions and restarts --- README.md | 8 +- Sources/ClearFlow/AudioCapture.swift | 39 ++++-- Sources/ClearFlow/ClearFlowApp.swift | 17 ++- Sources/ClearFlow/DictationModel.swift | 160 ++++++++++++++++++++----- Sources/ClearFlow/MediaPreview.swift | 5 + Sources/ClearFlow/SettingsStore.swift | 12 +- Sources/ClearFlow/Views.swift | 53 +++++++- Tests/AudioCaptureChecks.swift | 6 +- Tests/RecoveryChecks.swift | 131 ++++++++++++++++++++ docs/media/README.md | 4 + docs/media/recovery-warning.png | Bin 0 -> 15734 bytes scripts/build-app.sh | 2 +- scripts/test-audio.sh | 7 ++ 13 files changed, 386 insertions(+), 58 deletions(-) create mode 100644 Tests/RecoveryChecks.swift create mode 100644 docs/media/recovery-warning.png diff --git a/README.md b/README.md index 8d6284a..1cd35c0 100644 --- a/README.md +++ b/README.md @@ -66,7 +66,9 @@ In **Settings → General**, click the shortcut, then press your new key combina 3. Speak, then press the shortcut again. Keep the selected field and cursor unchanged while transcription runs. 4. If insertion cannot be verified or the destination changed, ClearFlow keeps the transcript on the clipboard for manual paste. Check the app’s status for details. -There is no elapsed-time cutoff: recording continues until you finish or cancel. After you finish, longer recordings are transcribed sequentially in parts of at most four minutes and combined into one result. Nothing is uploaded or inserted while you are recording. A word spanning a part boundary may be less accurate. Device interruptions or disk errors can still stop capture and are reported as errors; saved audio can be retried when available. Cancel with the overlay’s ×; pressing the shortcut while processing cancels delivery. Retry returns text for review and never pastes at an old cursor. +There is no elapsed-time cutoff: recording continues until you finish or cancel. After you finish, longer recordings are transcribed sequentially in parts of at most four minutes and combined into one result. Nothing is uploaded or inserted while you are recording. A word spanning a part boundary may be less accurate. Device interruptions or disk errors can still stop capture. A persistent warning appears and ClearFlow attempts to transcribe the available audio into Recent Dictations without pasting at a stale cursor. Low disk space triggers an advance warning; a sudden hardware failure cannot always be predicted. Quitting during capture or transcription asks for confirmation and retains audio. + +Transcripts are saved locally **before insertion**, with history enabled by default. Under **Saved Recordings**, choose **Recover** for unfinished audio from an interruption, failed request or previous launch, or **Discard** to delete it. Recovery never automatically pastes. Cancel with the overlay’s × while recording to discard that recording; cancelling while transcribing pauses delivery and keeps the audio. Damaged or unfinalized audio after a crash may not be transcribable, but is retained for inspection or explicit discard. [Full local setup, custom storage, startup at login, remote Mac and troubleshooting](local-stt/README.md). @@ -78,9 +80,9 @@ Deploy the supplied Worker in **your own account**, generate your own secret, an - The only bundled endpoint is loopback. Audio and vocabulary go only to the address you explicitly configure. No automatic provider fallback. - Local Whisper holds request audio in memory and does not log audio or transcripts. Setup downloads dependencies/model weights; runtime uses the local model with Hugging Face offline mode. -- Recording uses temporary WAV files, deleted after successful transcription or cancellation. A crash can leave a temporary file. Failed requests retain the temporary recording file for retry until you cancel, start a new recording or quit. +- Audio is stored in ~/Library/Application Support/ClearFlow/Recordings with private file permissions. It is deleted after successful transcription (and history persistence when enabled) or explicit discard. Failed, interrupted or paused requests retain audio across new recordings and app restarts. Review or delete these files under Saved Recordings; no automatic expiry. Existing temporary files from older versions are not imported. - Field content is read locally to guard insertion and is not uploaded. Known secure fields are rejected. -- History is memory-only by default. Opt-in saved history stores up to 50 transcripts on your Mac. Clipboard fallback leaves the transcript available until replaced. +- Transcript history is saved on this Mac by default, without automatic pruning, in ~/Library/Application Support/ClearFlow/history.json. Existing explicit history-off preferences are respected. Disable it in Settings → Data & privacy and save to remove stored history; ordinary completed dictations then stay in memory only. Interrupted audio remains recoverable until discarded. Clear recent history removes transcripts, not unfinished audio. Clipboard fallback leaves text available until replaced. - Your endpoint is stored in macOS preferences; the token is stored in Keychain. Keep credentials, recordings, personal endpoints and runtime data out of Git. ## Development diff --git a/Sources/ClearFlow/AudioCapture.swift b/Sources/ClearFlow/AudioCapture.swift index b833af6..8ba8fbf 100644 --- a/Sources/ClearFlow/AudioCapture.swift +++ b/Sources/ClearFlow/AudioCapture.swift @@ -16,8 +16,10 @@ extension AVAudioRecorder: AudioRecording {} @MainActor final class AudioCapture: NSObject, AVAudioRecorderDelegate { private var recorder: AudioRecording? + private let directory: URL private let makeRecorder: (URL, [String: Any]) throws -> AudioRecording - init(makeRecorder: @escaping (URL, [String: Any]) throws -> AudioRecording = { try AVAudioRecorder(url: $0, settings: $1) }) { + init(directory: URL = RecordingStore.directory, makeRecorder: @escaping (URL, [String: Any]) throws -> AudioRecording = { try AVAudioRecorder(url: $0, settings: $1) }) { + self.directory = directory self.makeRecorder = makeRecorder super.init() } @@ -30,10 +32,9 @@ extension AVAudioRecorder: AudioRecording {} return max(0, min(1, (Double(recorder.averagePower(forChannel: 0)) + 55) / 55)) } func start() throws { - let directory = FileManager.default.temporaryDirectory.appendingPathComponent("ClearFlow", isDirectory: true) try FileManager.default.createDirectory(at: directory, withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) - let url = directory.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav") + let url = directory.appendingPathComponent(UUID().uuidString).appendingPathExtension("wav").standardizedFileURL let settings: [String: Any] = [ AVFormatIDKey: kAudioFormatLinearPCM, AVSampleRateKey: 16000, AVNumberOfChannelsKey: 1, AVLinearPCMBitDepthKey: 16, @@ -41,7 +42,13 @@ extension AVAudioRecorder: AudioRecording {} ] let r = try makeRecorder(url, settings) r.delegate = self; r.isMeteringEnabled = true - guard r.prepareToRecord(), r.record() else { + guard r.prepareToRecord() else { + try? FileManager.default.removeItem(at: url) + throw AppError.message("The microphone could not prepare. Check your input device.") + } + do { try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) } + catch { try? FileManager.default.removeItem(at: url); throw error } + guard r.record() else { try? FileManager.default.removeItem(at: url) throw AppError.message("The microphone could not start. Check the selected input in System Settings.") } @@ -76,9 +83,27 @@ extension AVAudioRecorder: AudioRecording {} } } -/// Owns the temporary recording through transcription and retry; removes it on release. +/// Durable until explicitly discarded or a transcript has been saved successfully. final class RecordedAudio { let url: URL - init(url: URL) { self.url = url } - deinit { try? FileManager.default.removeItem(at: url) } + init(url: URL) { self.url = url.standardizedFileURL } + func discard() throws { + if FileManager.default.fileExists(atPath: url.path) { try FileManager.default.removeItem(at: url) } + } +} + +enum RecordingStore { + static var directory: URL { + FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] + .appendingPathComponent("ClearFlow/Recordings", isDirectory: true) + } + static func recordings(in directory: URL = directory) throws -> [URL] { + guard FileManager.default.fileExists(atPath: directory.path) else { return [] } + return try FileManager.default.contentsOfDirectory(at: directory, + includingPropertiesForKeys: [.creationDateKey, .isRegularFileKey]) + .filter { $0.pathExtension == "wav" && (try? $0.resourceValues(forKeys: [.isRegularFileKey]).isRegularFile) == true } + .map { $0.standardizedFileURL } + .sorted { ((try? $0.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast) + > ((try? $1.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast) } + } } diff --git a/Sources/ClearFlow/ClearFlowApp.swift b/Sources/ClearFlow/ClearFlowApp.swift index a23c0f2..1de3054 100644 --- a/Sources/ClearFlow/ClearFlowApp.swift +++ b/Sources/ClearFlow/ClearFlowApp.swift @@ -83,7 +83,7 @@ import ClearFlowCore guard let self else { return false } return self.shortcut.register(value) } - subscription = model.$mode.combineLatest(model.$status, model.$shortcut).sink { [weak self] _, _, _ in + subscription = model.$mode.combineLatest(model.$status, model.$shortcut, model.$recordingNotice).sink { [weak self] _, _, _, _ in DispatchQueue.main.async { self?.refresh() } } refresh() @@ -96,7 +96,9 @@ import ClearFlowCore startItem.title = action + " " + model.shortcut.display statusItem.button?.image = NSImage(systemSymbolName: model.mode == .recording ? "mic.fill" : model.mode == .transcribing ? "hourglass" : "waveform", accessibilityDescription: "ClearFlow") - if model.busy { + if model.busy || !model.recordingNotice.isEmpty { + let fitting = overlay.contentView?.fittingSize ?? NSSize(width: 118, height: 46) + overlay.setContentSize(fitting) let screen = NSScreen.screens.first { NSMouseInRect(NSEvent.mouseLocation, $0.frame, false) } ?? NSScreen.main if let screen { overlay.setFrameOrigin(NSPoint(x: screen.visibleFrame.midX - overlay.frame.width / 2, y: screen.visibleFrame.minY + 34)) @@ -147,7 +149,16 @@ import ClearFlowCore window?.makeKeyAndOrderFront(nil) } @objc func quit() { NSApp.terminate(nil) } + func applicationShouldTerminate(_ sender: NSApplication) -> NSApplication.TerminateReply { + guard model.busy else { return .terminateNow } + let alert = NSAlert() + alert.messageText = model.mode == .recording ? "Recording will end if you quit." : "Transcription is still running." + alert.informativeText = "Your audio will stay saved on this Mac. Reopen ClearFlow and choose Recover to finish the transcript." + alert.addButton(withTitle: "Keep ClearFlow open") + alert.addButton(withTitle: "Quit and keep audio") + return alert.runModal() == .alertSecondButtonReturn ? .terminateNow : .terminateCancel + } func applicationWillTerminate(_ notification: Notification) { - model.cancel(); shortcut.unregister() + model.prepareForQuit(); shortcut.unregister() } } diff --git a/Sources/ClearFlow/DictationModel.swift b/Sources/ClearFlow/DictationModel.swift index 118efbf..c4b5218 100644 --- a/Sources/ClearFlow/DictationModel.swift +++ b/Sources/ClearFlow/DictationModel.swift @@ -11,6 +11,8 @@ import ClearFlowCore @Published var level = 0.0 @Published var meter = MeterHistory() @Published var transcript = "" + @Published var recordingNotice = "" + @Published private(set) var recoverableRecordings: [URL] = [] @Published var history: [Transcript] = [] @Published var endpoint = AppSettings.endpoint @Published var token = "" @@ -55,7 +57,14 @@ import ClearFlowCore var showWindow: (() -> Void)? var lastExternalApp: NSRunningApplication? private var demoMode = false - private let capture = AudioCapture() + private let capture: AudioCapture + private let recoveryDirectory: URL + // Injection seams exercise the actual stop/save/insertion ordering without microphone access. + var transcribeRecording: ((URL, UUID) async throws -> TranscriptionReply)? + var insertTranscript: ((String) async -> String)? + var persistHistory: ([Transcript]) throws -> Void = { try HistoryStore.save($0) } + private var interrupted = false + private var diskCheckAt = 0.0 private var gate = SessionGate() private var currentID: UUID? private var target: InsertionTarget? @@ -66,7 +75,11 @@ import ClearFlowCore private var workspaceObserver: NSObjectProtocol? var busy: Bool { mode == .recording || mode == .transcribing || mode == .requestingPermission || mode == .testingInsertion } var canRetry: Bool { pendingAudio != nil && !busy } - init(demo: Bool = false) { + init(demo: Bool = false, capture: AudioCapture? = nil, recoveryDirectory: URL = RecordingStore.directory) { + let capture = capture ?? AudioCapture() + self.capture = capture + self.recoveryDirectory = recoveryDirectory + capture.onUnexpectedStop = { [weak self] message in self?.recordingInterrupted(message) } if demo { demoMode = true shortcut = .default @@ -85,14 +98,47 @@ import ClearFlowCore app.processIdentifier != ProcessInfo.processInfo.processIdentifier else { return } Task { @MainActor [weak self] in self?.lastExternalApp = app } } - capture.onUnexpectedStop = { [weak self] message in - guard let self, self.mode == .recording else { return } - self.ticker?.invalidate(); self.ticker = nil - self.pendingAudio = try? self.capture.stop() - self.gate.cancel(); self.mode = .error; self.level = 0 - self.status = message + (self.pendingAudio == nil ? " Please start again." : " Retry to transcribe the saved audio.") + refreshRecoveries() + if let file = recoverableRecordings.first { + pendingAudio = RecordedAudio(url: file) + mode = .error + recordingNotice = "An unfinished recording is saved on this Mac. Open ClearFlow and choose Recover." + status = recordingNotice } } + func refreshRecoveries() { + do { recoverableRecordings = try RecordingStore.recordings(in: recoveryDirectory) } + catch { recordingNotice = "Could not read saved recordings: " + error.localizedDescription } + } + func recover(_ url: URL) { + guard !busy, recoverableRecordings.contains(url) else { return } + pendingAudio = RecordedAudio(url: url) + retry() + } + func discardRecovery(_ url: URL) { + guard !busy, recoverableRecordings.contains(url) else { return } + do { + try RecordedAudio(url: url).discard() + if pendingAudio?.url == url { pendingAudio = nil } + refreshRecoveries() + status = "Recording discarded" + } catch { recordingNotice = "Could not delete the recording: " + error.localizedDescription } + } + func recordingInterrupted(_ message: String) { + guard mode == .recording else { return } + interrupted = true + // Show a nonactivating warning throughout transcription and until explicitly dismissed. + recordingNotice = message + " Saving the available speech…" + target = nil; captureIssue = nil + stop() + } + func prepareForQuit() { + requestTask?.cancel(); requestTask = nil + ticker?.invalidate(); ticker = nil + if mode == .recording { pendingAudio = try? capture.stop() } + gate.cancel(); currentID = nil + // Keep durable audio for the next launch. Quitting is not a discard action. + } func refreshPermissions() { guard !demoMode else { return } hasAccessibility = AXIsProcessTrusted() @@ -132,6 +178,7 @@ import ClearFlowCore let destination = TextInsertion.capture(previousApp: lastExternalApp) target = destination.target; captureIssue = destination.issue pendingAudio = nil + interrupted = false mode = .requestingPermission; status = "Waiting for microphone access…" Task { let granted: Bool @@ -142,20 +189,36 @@ import ClearFlowCore guard granted else { gate.cancel(); mode = .error; status = "Microphone access is needed. Enable it in System Settings."; return } - do { - try capture.start() - seconds = 0; level = 0; meter.reset(); transcript = "" - mode = .recording; status = "Listening" - ticker = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in - Task { @MainActor [weak self] in - guard let self, self.mode == .recording else { return } - self.seconds = self.capture.seconds; self.level = self.capture.level - self.meter.append(self.level) + beginCapture() + } + } + func beginCapture() { + guard mode != .recording, mode != .transcribing else { return } + interrupted = false + do { + gate.cancel() + let id = UUID() + guard gate.begin(id) else { return } + currentID = id + try capture.start() + seconds = 0; level = 0; meter.reset(); diskCheckAt = 0 + mode = .recording; status = "Listening" + ticker = Timer.scheduledTimer(withTimeInterval: 0.05, repeats: true) { [weak self] _ in + Task { @MainActor [weak self] in + guard let self, self.mode == .recording else { return } + self.seconds = self.capture.seconds; self.level = self.capture.level + self.meter.append(self.level) + if self.seconds >= self.diskCheckAt { + self.diskCheckAt = self.seconds + 5 + if let free = try? FileManager.default.attributesOfFileSystem(forPath: self.recoveryDirectory.path)[.systemFreeSize] as? NSNumber, + free.int64Value < 100 * 1024 * 1024 { + self.recordingNotice = "Storage is almost full. Finish dictation now to save your words before recording fails." + } } } - } catch { - gate.cancel(); mode = .error; status = error.localizedDescription } + } catch { + gate.cancel(); mode = .error; status = error.localizedDescription } } func stop() { @@ -168,37 +231,63 @@ import ClearFlowCore transcribe(audio, id: id) } catch { gate.cancel(); mode = .error; status = error.localizedDescription + refreshRecoveries() + recordingNotice = "Recording ended: " + status + " Check saved recordings in ClearFlow." } } private func transcribe(_ audio: RecordedAudio, id: UUID) { mode = .transcribing; status = "Turning speech into text…"; level = 0 - let endpoint = AppSettings.endpoint, token = TokenStore.read() + let endpoint = AppSettings.endpoint, token = transcribeRecording == nil ? TokenStore.read() : "" let language = AppSettings.language, vocabulary = AppSettings.vocabulary requestTask = Task { do { - let reply = try await TranscriptionClient.transcribe(file: audio.url, id: id, endpoint: endpoint, + let reply: TranscriptionReply + if let transcribeRecording { reply = try await transcribeRecording(audio.url, id) } + else { reply = try await TranscriptionClient.transcribe(file: audio.url, id: id, endpoint: endpoint, token: token, language: language, vocabulary: vocabulary, progress: { [weak self] part, count in await self?.transcriptionProgress(part: part, count: count, id: id) - }) + }) } guard !Task.isCancelled, gate.acceptResult(id) else { return } let text = reply.text.trimmingCharacters(in: .whitespacesAndNewlines) guard !text.isEmpty else { - mode = .error; status = "No speech was detected. Try again closer to the microphone."; return + mode = .error; status = "No speech was detected. Audio saved for recovery." + recordingNotice = status; refreshRecoveries(); return } transcript = text - let outcome = await TextInsertion.insert(text, target: target, captureIssue: captureIssue) - guard !Task.isCancelled, currentID == id else { return } - status = outcome; mode = .ready; pendingAudio = nil - let item = Transcript(id: id, date: Date(), text: text, target: target?.name ?? "Clipboard") - history.insert(item, at: 0); history = Array(history.prefix(50)) + let transcriptID = UUID(uuidString: audio.url.deletingPathExtension().lastPathComponent) ?? id + let item = Transcript(id: transcriptID, date: Date(), text: text, target: interrupted ? "Interrupted recording" : target?.name ?? "Clipboard") + history.removeAll { $0.id == transcriptID } + history.insert(item, at: 0) + // Commit words to disk BEFORE any asynchronous insertion or clipboard operation. if saveHistory { - do { try HistoryStore.save(history) } - catch { settingsMessage = "Could not save local history: \(error.localizedDescription)" } + do { try persistHistory(history) } + catch { + mode = .error + status = "Transcript could not be saved. Audio is retained for recovery. " + error.localizedDescription + recordingNotice = status + refreshRecoveries() + return + } } + let outcome: String + if interrupted { outcome = saveHistory ? "Recovered transcript saved in Recent Dictations." : "Recovered transcript is available for this session; audio retained." } + else if let insertTranscript { outcome = await insertTranscript(text) } + else { outcome = await TextInsertion.insert(text, target: target, captureIssue: captureIssue) } + guard !Task.isCancelled, currentID == id else { return } + status = outcome; mode = .ready + // History-off is an explicit privacy choice; retain interrupted audio until discarded. + if saveHistory || !interrupted { + do { try audio.discard(); pendingAudio = nil } + catch { recordingNotice = "Transcript is ready, but the saved audio could not be removed." } + } + if interrupted { recordingNotice = outcome } + refreshRecoveries() } catch { guard !Task.isCancelled, currentID == id else { return } gate.cancel(); mode = .error; status = error.localizedDescription + recordingNotice = "Transcription failed. Your recording is saved on this Mac. Open ClearFlow to retry. " + status + refreshRecoveries() } } } @@ -212,6 +301,7 @@ import ClearFlowCore guard gate.begin(id), gate.finishRecording(id) else { return } currentID = id // A delayed retry always returns text for review; never pastes at an old cursor. + interrupted = true target = nil; captureIssue = "retries return text for review. Use Copy to paste it." transcribe(audio, id: id) } @@ -222,10 +312,20 @@ import ClearFlowCore mode = .ready; status = "Insertion test cancelled"; settingsMessage = status return } + if mode == .transcribing { + requestTask?.cancel(); requestTask = nil + gate.cancel(); currentID = nil + mode = .error; level = 0 + status = "Transcription paused. Audio saved for recovery." + recordingNotice = status + refreshRecoveries() + return + } requestTask?.cancel(); requestTask = nil capture.cancel(); ticker?.invalidate(); ticker = nil gate.cancel(); currentID = nil; pendingAudio = nil; target = nil mode = .idle; status = "Cancelled"; level = 0; meter.reset() + refreshRecoveries() } func testInsertion() { guard !busy else { return } diff --git a/Sources/ClearFlow/MediaPreview.swift b/Sources/ClearFlow/MediaPreview.swift index c018b29..a46f879 100644 --- a/Sources/ClearFlow/MediaPreview.swift +++ b/Sources/ClearFlow/MediaPreview.swift @@ -9,6 +9,11 @@ import SwiftUI let model = DictationModel(demo: true) try save(MainView(renderForDocumentation: true, model: model).frame(width: 1120, height: 780), to: directory.appendingPathComponent("screenshot.png")) + let recovery = DictationModel(demo: true) + recovery.mode = .ready + recovery.recordingNotice = "Recording stopped unexpectedly. Your recovered transcript is saved in Recent Dictations." + try save(OverlayView(model: recovery).frame(width: 360, height: 200), + to: directory.appendingPathComponent("recovery-warning.png")) for frame in 0..<48 { try save(Walkthrough(frame: frame).frame(width: 960, height: 560), to: directory.appendingPathComponent(String(format: "frame-%03d.png", frame))) diff --git a/Sources/ClearFlow/SettingsStore.swift b/Sources/ClearFlow/SettingsStore.swift index bae3331..242a5bc 100644 --- a/Sources/ClearFlow/SettingsStore.swift +++ b/Sources/ClearFlow/SettingsStore.swift @@ -21,7 +21,7 @@ struct AppSettings { set { defaults.set(newValue, forKey: "language") } } static var saveHistory: Bool { - get { defaults.bool(forKey: "saveHistory") } + get { defaults.object(forKey: "saveHistory") as? Bool ?? true } set { defaults.set(newValue, forKey: "saveHistory") } } } @@ -70,15 +70,15 @@ enum HistoryStore { FileManager.default.urls(for: .applicationSupportDirectory, in: .userDomainMask)[0] .appendingPathComponent("ClearFlow/history.json") } - static func load() -> [Transcript] { - guard AppSettings.saveHistory, let data = try? Data(contentsOf: url), + static func load(from url: URL = url, enabled: Bool = AppSettings.saveHistory) -> [Transcript] { + guard enabled, let data = try? Data(contentsOf: url), let items = try? JSONDecoder().decode([Transcript].self, from: data) else { return [] } - return Array(items.prefix(50)) + return items } - static func save(_ items: [Transcript]) throws { + static func save(_ items: [Transcript], to url: URL = url) throws { try FileManager.default.createDirectory(at: url.deletingLastPathComponent(), withIntermediateDirectories: true, attributes: [.posixPermissions: 0o700]) - let data = try JSONEncoder().encode(Array(items.prefix(50))) + let data = try JSONEncoder().encode(items) try data.write(to: url, options: .atomic) try FileManager.default.setAttributes([.posixPermissions: 0o600], ofItemAtPath: url.path) } diff --git a/Sources/ClearFlow/Views.swift b/Sources/ClearFlow/Views.swift index b114579..8011a02 100644 --- a/Sources/ClearFlow/Views.swift +++ b/Sources/ClearFlow/Views.swift @@ -27,6 +27,7 @@ struct MainView: View { @State private var showSettings = false @State private var query = "" @State private var searching = false + @State private var discardURL: URL? private var words: Int { model.history.reduce(0) { $0 + $1.text.split(whereSeparator: { $0.isWhitespace }).count } } private var filtered: [Transcript] { model.history.filter { query.isEmpty || $0.text.localizedCaseInsensitiveContains(query) } @@ -55,6 +56,13 @@ struct MainView: View { .preferredColorScheme(.light) .sheet(isPresented: $showSettings) { FlowSettings(model: model) } .onAppear { model.refreshPermissions() } + .alert("Discard saved recording?", isPresented: Binding(get: { discardURL != nil }, set: { if !$0 { discardURL = nil } })) { + Button("Keep", role: .cancel) { discardURL = nil } + Button("Discard", role: .destructive) { + if let url = discardURL { model.discardRecovery(url) } + discardURL = nil + } + } message: { Text("This permanently deletes the audio. Recover it first if you need its transcript.") } } private var sidebar: some View { VStack(alignment: .leading, spacing: 6) { @@ -131,6 +139,23 @@ struct MainView: View { Spacer(minLength: 0) }.padding(14).background(FlowTheme.shell, in: RoundedRectangle(cornerRadius: 10)) } + if !model.recoverableRecordings.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Text("SAVED RECORDINGS").font(.caption).fontWeight(.semibold) + Text("Unfinished audio stays on this Mac until recovered or discarded.").font(.caption) + ScrollView { + ForEach(model.recoverableRecordings, id: \.self) { url in + HStack { + Text((try? url.resourceValues(forKeys: [.creationDateKey]).creationDate) ?? .distantPast, + format: .dateTime.month().day().hour().minute()).font(.caption) + Spacer() + Button("Recover") { model.recover(url) }.disabled(model.busy) + Button("Discard") { discardURL = url }.disabled(model.busy) + } + } + }.frame(maxHeight: 90) + }.padding(12).background(FlowTheme.selected, in: RoundedRectangle(cornerRadius: 10)) + } history }.frame(maxWidth: .infinity, maxHeight: .infinity, alignment: .top) stats.frame(width: 174) @@ -371,11 +396,11 @@ private struct FlowSettings: View { private var privacy: some View { Group { Toggle("Save recent transcripts on this Mac", isOn: $model.saveHistory).font(.system(size: 13, weight: .medium)) - Text("When off, recent dictations stay in memory. Turning this off and saving removes the saved history file.") + Text("On by default. Transcripts are saved before insertion and survive restarting. Turning this off and saving removes saved history; new successful dictations then stay in memory only.") .font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(4).padding(.top, 10) rule() Text("Your audio").font(.system(size: 14, weight: .medium)) - Text("Audio is sent only to the service address you configure when you finish. Local Whisper runs on your own hardware; a cloud endpoint sends audio to that provider. There is no automatic cloud fallback. Temporary recordings are deleted on normal finish or cancel. Failed requests can keep audio in memory so you can retry.") + Text("After recording ends, audio is sent only to the service address you configure, including recovery after an unexpected stop. Local Whisper runs on your own hardware; a cloud endpoint sends audio to that provider. There is no automatic cloud fallback. Recordings are stored privately on this Mac until transcription succeeds or you explicitly discard them. Interrupted or failed recordings survive restarting; recover or discard them under Saved Recordings. Cancel while recording discards that recording; cancel while transcribing preserves it for recovery.") .font(.system(size: 12)).foregroundStyle(FlowTheme.muted).lineSpacing(4).padding(.top, 9) Text("No screen content is uploaded.").font(.system(size: 12)).padding(.top, 12) rule() @@ -459,10 +484,26 @@ struct RecordingBar: View { struct OverlayView: View { @ObservedObject var model: DictationModel var body: some View { - RecordingBar(samples: model.meter.samples, recording: model.mode == .recording, - processingLabel: model.mode == .testingInsertion ? "Testing" : model.mode == .transcribing ? "Transcribing" : "Microphone", - onCancel: { model.cancel() }, onFinish: { model.stop() }) - .shadow(color: .black.opacity(0.2), radius: 5, y: 2).padding(8) + VStack(spacing: 8) { + if !model.recordingNotice.isEmpty { + VStack(alignment: .leading, spacing: 8) { + Label(model.mode == .recording ? "Recording needs attention" : "Recording update", + systemImage: "exclamationmark.triangle.fill").font(.system(size: 12, weight: .semibold)) + Text(model.recordingNotice).font(.system(size: 12)).lineLimit(5).fixedSize(horizontal: false, vertical: true) + HStack { + Button("Open ClearFlow") { model.showWindow?() } + Spacer() + Button("Dismiss") { model.recordingNotice = "" } + }.font(.system(size: 11)) + }.padding(12).frame(width: 310).foregroundStyle(.white) + .background(Color(white: 0.12), in: RoundedRectangle(cornerRadius: 12)) + } + if model.busy { + RecordingBar(samples: model.meter.samples, recording: model.mode == .recording, + processingLabel: model.status, + onCancel: { model.cancel() }, onFinish: { model.stop() }) + } + }.shadow(color: .black.opacity(0.2), radius: 5, y: 2).padding(8) } } diff --git a/Tests/AudioCaptureChecks.swift b/Tests/AudioCaptureChecks.swift index c3a9df8..517e7bd 100644 --- a/Tests/AudioCaptureChecks.swift +++ b/Tests/AudioCaptureChecks.swift @@ -38,7 +38,9 @@ final class ClockRecorder: AudioRecording { guard !recorder.active, FileManager.default.fileExists(atPath: audio!.url.path) else { fatalError("Explicit stop must retain audio for transcription") } let saved = audio!.url audio = nil - guard !FileManager.default.fileExists(atPath: saved.path) else { fatalError("Releasing a completed/cancelled request must delete temporary audio") } - print("PASS: capture remains active at 60 minutes (simulated clock); explicit stop/cancel and temporary file lifetime") + guard FileManager.default.fileExists(atPath: saved.path) else { fatalError("Unfinished audio must survive release") } + try RecordedAudio(url: saved).discard() + guard !FileManager.default.fileExists(atPath: saved.path) else { fatalError("Explicit discard must delete audio") } + print("PASS: capture remains active at 60 minutes (simulated clock); explicit stop/cancel and durable file lifetime") } } diff --git a/Tests/RecoveryChecks.swift b/Tests/RecoveryChecks.swift new file mode 100644 index 0000000..96748aa --- /dev/null +++ b/Tests/RecoveryChecks.swift @@ -0,0 +1,131 @@ +import Foundation +import AVFoundation + +final class RecoveryRecorder: AudioRecording { + var delegate: AVAudioRecorderDelegate? + var isMeteringEnabled = false + var currentTime: TimeInterval = 30 + func prepareToRecord() -> Bool { true } + func record() -> Bool { true } + func record(forDuration duration: TimeInterval) -> Bool { true } + func updateMeters() {} + func averagePower(forChannel channel: Int) -> Float { -30 } + func stop() {} +} + +@main enum RecoveryChecks { + @MainActor static func settle(_ model: DictationModel) async { + for _ in 0..<200 { + if !model.busy { return } + try? await Task.sleep(nanoseconds: 5_000_000) + } + fatalError("Model did not settle") + } + @MainActor static func main() async throws { + let directory = FileManager.default.temporaryDirectory.appendingPathComponent(UUID().uuidString) + defer { try? FileManager.default.removeItem(at: directory) } + let historyURL = directory.appendingPathComponent("history.json") + let recordings = directory.appendingPathComponent("Recordings") + var file: URL? + let capture = AudioCapture(directory: recordings) { url, _ in + file = url + try Data(repeating: 0, count: 32044).write(to: url) + return RecoveryRecorder() + } + try capture.start() + var audio: RecordedAudio? = try capture.stop() + guard audio != nil else { fatalError("Recording missing") } + audio = nil + guard FileManager.default.fileExists(atPath: file!.path) else { + fatalError("Unfinished recording was deleted on owner release") + } + guard try RecordingStore.recordings(in: recordings).map({ $0.standardizedFileURL.path }) == [file!.standardizedFileURL.path] else { fatalError("Restart discovery lost recording") } + try RecordedAudio(url: file!).discard() + + let model = DictationModel(demo: true, capture: capture, recoveryDirectory: recordings) + model.history = []; model.saveHistory = true + model.persistHistory = { try HistoryStore.save($0, to: historyURL) } + model.transcribeRecording = { _, id in + TranscriptionReply(text: "Synthetic recovered words.", requestId: id.uuidString, model: "test", durationMs: 30) + } + var inserted = 0 + model.insertTranscript = { text in + guard HistoryStore.load(from: historyURL, enabled: true).first?.text == text else { + fatalError("Insertion happened before durable transcript save") + } + inserted += 1 + return "Inserted" + } + model.beginCapture() + model.stop() + await settle(model) + guard model.mode == .ready, inserted == 1, + !FileManager.default.fileExists(atPath: file!.path) else { fatalError("Normal completion lifecycle") } + // Re-read from disk to simulate a fresh process, not the in-memory history. + guard HistoryStore.load(from: historyURL, enabled: true).count == 1 else { fatalError("Transcript lost on restart") } + + model.beginCapture() + capture.onUnexpectedStop?("Synthetic device interruption.") + guard !model.recordingNotice.isEmpty else { fatalError("Unexpected stop was silent") } + await settle(model) + guard model.mode == .ready, inserted == 1, + HistoryStore.load(from: historyURL, enabled: true).count == 2, + model.recordingNotice.contains("saved") else { fatalError("Interruption must save, warn and never paste") } + + model.persistHistory = { _ in throw AppError.message("Synthetic full disk") } + model.beginCapture(); model.stop() + await settle(model) + guard model.mode == .error, model.canRetry, inserted == 1, + FileManager.default.fileExists(atPath: file!.path) else { fatalError("Save failure must retain audio and block insertion") } + let failedFile = file! + // Starting a new recording must not delete a previously failed recording. + model.beginCapture() + let quittingFile = file! + model.prepareForQuit() + guard try RecordingStore.recordings(in: recordings).contains(failedFile), + FileManager.default.fileExists(atPath: quittingFile.path) else { fatalError("Quit/start lost unfinished audio") } + model.mode = .idle + model.persistHistory = { try HistoryStore.save($0, to: historyURL) } + model.refreshRecoveries() + model.recover(quittingFile) + await settle(model) + guard model.mode == .ready, inserted == 1, + !FileManager.default.fileExists(atPath: quittingFile.path) else { fatalError("Recovery must save without paste") } + + model.transcribeRecording = { _, _ in throw AppError.message("Synthetic network failure") } + model.beginCapture(); model.stop() + await settle(model) + guard model.mode == .error, model.canRetry, !model.recordingNotice.isEmpty, + FileManager.default.fileExists(atPath: file!.path) else { fatalError("Network failure lost audio") } + // Explicit history-off must not silently persist text, but interrupted audio stays recoverable. + model.saveHistory = false + model.persistHistory = { _ in fatalError("History-off must not persist text") } + model.transcribeRecording = { _, id in + TranscriptionReply(text: "Private session.", requestId: id.uuidString, model: "test", durationMs: 1) + } + model.beginCapture() + capture.onUnexpectedStop?("Synthetic interruption with history off") + await settle(model) + guard model.mode == .ready, FileManager.default.fileExists(atPath: file!.path) else { fatalError("History-off interruption lost audio") } + model.saveHistory = true + model.persistHistory = { try HistoryStore.save($0, to: historyURL) } + model.transcribeRecording = { _, id in + try await Task.sleep(nanoseconds: 500_000_000) + return TranscriptionReply(text: "Do not deliver.", requestId: id.uuidString, model: "test", durationMs: 1) + } + model.beginCapture(); model.stop(); model.cancel() + let cancelled = file! + guard model.canRetry, FileManager.default.fileExists(atPath: cancelled.path) else { fatalError("Cancelled transcription must be recoverable") } + let before = model.history.count + try await Task.sleep(nanoseconds: 550_000_000) + guard model.history.count == before else { fatalError("Cancelled result was delivered") } + model.refreshRecoveries(); model.discardRecovery(cancelled) + guard !FileManager.default.fileExists(atPath: cancelled.path) else { fatalError("Explicit discard failed") } + + model.beginCapture() + let discarded = file! + model.cancel() + guard !FileManager.default.fileExists(atPath: discarded.path) else { fatalError("Explicit recording cancel must discard") } + print("PASS: durable audio discovery; transcript saved before paste; interrupted auto-save and warning; disk/network failure; quit/new recording preservation; recovery; cancellation and explicit discard") + } +} diff --git a/docs/media/README.md b/docs/media/README.md index 6565c6d..912b1cc 100644 --- a/docs/media/README.md +++ b/docs/media/README.md @@ -10,3 +10,7 @@ python3 scripts/assemble-demo.py work/media docs/media ``` The renderer bypasses normal app startup and does not read Keychain or saved transcript history. Never replace these with screenshots containing personal dictations, tokens, endpoints or account details. + +## Recording recovery warning + +[recovery-warning.png](recovery-warning.png) renders the actual nonactivating warning component with synthetic copy. It illustrates the message retained after unexpected recording termination; it is not evidence of a physical device interruption. The existing --render-media command produces this image alongside the walkthrough frames. diff --git a/docs/media/recovery-warning.png b/docs/media/recovery-warning.png new file mode 100644 index 0000000000000000000000000000000000000000..6112e0997e90074e19d9bd47ca6534bb5f7f1585 GIT binary patch literal 15734 zcmeHuRa9I}urBUSaQEO6g1fuBOK`W~5Zo=ehv3fO5ZooWTW|(<9qdl>ud~*Dy$|>8 zJk0E#y?eTMRd-dFd=;glB#nwhhy(!vfhsE_p#}i~X$@|VAi#mY2jhJcz!yk2HEA)3 znn~g#@DB+K9a&37MF<9P8vz0`!Uh87Zx`@~5d49Ffc^mq0S&%F{=N4D>VKX>TK|Cl zpEktE-;P_fu9grG0$Z{Yq8eV1XSwjLXA%qH;+T+(loLLxd@|S)su)MJMe^DbBCt3b zB9d8h(!Fxh(X+5g@wW^zIEf6w-w>h^aGAPu0{^r zG9%?{3Z7*P0Uw5G#TI<;Ycadz=U@D|FlBu98Ru)}O)4%H!_g1Ze>X*t5vI)O0;yfT z3ekS)b2Jq(PNs{7oPV225|e3rEf3N6xf0*DqV!#doD2TH6HlW*9_|D$!96DrMs8PhKRvbb)={GR5tUzbY> zC`BBPD_Y1#S+Ds~Op9mZ#OR@&*XSl|sfusIeXjaLv!qyFOX!)VX*NAEqalyG%iopz z;Q|vLEYkCixF+0pFTwMsxLotLw)yt;>1Im!y%d8E3Re|dkKprn+@#epsrFh9$u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zUBfNE0@%`IU!(ULCDyl zWd3ZUB6j14DoUFqCR9~EF+zp18zga!lv|yv|H=iY8KLNtjx(km(;}N{r%MV0QfDez zijSm|Z#B3~S7`${hy(yu7B(CN)FMhHv>RrMqKm1KGJz^t{S=@4!+fhK%MjVts0`QIsL!hfzoWh zVR#h}v2=J3;KERN#YWRR#F(M>qgwiTL#&=*!un``{~t5S>tPYkJdqt%RmGi|5ZS8b zhmmZGHna=fT=;+m|K_C<6_KzXuX9<|E^|Ku>=2<2hrGCYl(-zZ6vo~6{j2U8Ay547 z=%bKkU{F$K`Ew{6q4KzvZ%N^#^TU7GS1J|B4o#pGPB&MQNwzzI=5(hs_<^+`)UMQ6 xwe%3qKdJiP%GrO+`p3}!ryAm*Ua75jNS;#Z8hN!(Xn$*-WhIp)YQ#)}{|}HVCl~+# literal 0 HcmV?d00001 diff --git a/scripts/build-app.sh b/scripts/build-app.sh index 16e8ae4..673bd0f 100755 --- a/scripts/build-app.sh +++ b/scripts/build-app.sh @@ -11,7 +11,7 @@ cp assets/AppIcon.icns "$APP/Contents/Resources/AppIcon.icns" python3 - "$APP" "http://127.0.0.1:8768" <<'PY' import pathlib,plistlib,sys app=pathlib.Path(sys.argv[1]) -info={"CFBundleName":"ClearFlow","CFBundleDisplayName":"ClearFlow","CFBundleIdentifier":"org.clearflow.app","CFBundleExecutable":"ClearFlow","CFBundlePackageType":"APPL","CFBundleShortVersionString":"0.4.6","CFBundleVersion":"14","LSMinimumSystemVersion":"14.0","LSUIElement":False,"CFBundleIconFile":"AppIcon","NSHighResolutionCapable":True,"NSMicrophoneUsageDescription":"ClearFlow records your voice only when you start dictation, then sends it to the transcription service you configure.","ClearFlowEndpoint":sys.argv[2]} +info={"CFBundleName":"ClearFlow","CFBundleDisplayName":"ClearFlow","CFBundleIdentifier":"org.clearflow.app","CFBundleExecutable":"ClearFlow","CFBundlePackageType":"APPL","CFBundleShortVersionString":"0.4.7","CFBundleVersion":"15","LSMinimumSystemVersion":"14.0","LSUIElement":False,"CFBundleIconFile":"AppIcon","NSHighResolutionCapable":True,"NSMicrophoneUsageDescription":"ClearFlow records your voice only when you start dictation, then sends it to the transcription service you configure.","ClearFlowEndpoint":sys.argv[2]} (app/"Contents/Info.plist").write_bytes(plistlib.dumps(info)) PY # Remove linker debug records containing the build machine absolute source paths. diff --git a/scripts/test-audio.sh b/scripts/test-audio.sh index cc05427..d19f3e0 100755 --- a/scripts/test-audio.sh +++ b/scripts/test-audio.sh @@ -11,3 +11,10 @@ swiftc -parse-as-library -I "$BUILD_DIR/Modules" "$BUILD_DIR"/ClearFlowCore.buil Sources/ClearFlow/SettingsStore.swift Sources/ClearFlow/TranscriptionClient.swift Tests/LongTranscriptionChecks.swift \ -o "$BUILD_DIR/LongTranscriptionChecks" "$BUILD_DIR/LongTranscriptionChecks" + +swiftc -parse-as-library -I "$BUILD_DIR/Modules" "$BUILD_DIR"/ClearFlowCore.build/*.o \ + Sources/ClearFlow/SettingsStore.swift Sources/ClearFlow/AudioCapture.swift \ + Sources/ClearFlow/TranscriptionClient.swift Sources/ClearFlow/TextInsertion.swift \ + Sources/ClearFlow/DictationModel.swift Tests/RecoveryChecks.swift \ + -o "$BUILD_DIR/RecoveryChecks" +"$BUILD_DIR/RecoveryChecks"