Fastest and only macOS Dictation app with on-device STT and custom trained AI enhancement model. Windows, iOS testflight! Android, Linux waitlist open! A local Wispr Flow alternative. Follow https://x.com/fluidvoiceapp for more
preserve canceled dictation in history without delivery
altic-dev7395fa13138b
diff --git a/.github/screenshots/hotkey-escape-history.jpg b/.github/screenshots/hotkey-escape-history.jpgnew file mode 100644index 00000000..7c03d77cBinary files /dev/null and b/.github/screenshots/hotkey-escape-history.jpg differdiff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex fc283dcf..daa5edf5 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -241,9 +241,14 @@ struct ContentView: View {case command}- private enum DictationOutputRoute: String {+ enum DictationOutputRoute: String {case normalcase onboardingSandbox+ case historyOnly++ var savesHistory: Bool { self != .onboardingSandbox }+ var deliversText: Bool { self == .normal }+ var publishesEditorResult: Bool { self != .historyOnly }}@EnvironmentObject private var appServices: AppServices@@ -269,6 +274,9 @@ struct ContentView: View {@Environment(\.accessibilityReduceMotion) private var accessibilityReduceMotion@State private var hotkeyManager: GlobalHotkeyManager? = nil@State private var hotkeyManagerInitialized: Bool = false+ @State private var processingDictationLifecycleID: UInt64?+ @State private var cancelledOutputLifecycleID: UInt64?+ @State private var isSavingCancelledRecording = false@State private var appear = false@State private var accessibilityEnabled = false@@ -2324,7 +2332,8 @@ struct ContentView: View {textReadyAt: TimeInterval,toggleStopRequestedAt: TimeInterval?,preserveTranscriptOnClipboard: Bool,- stopSnapshot: DictationStopSnapshot? = nil+ stopSnapshot: DictationStopSnapshot? = nil,+ isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> TypingService.DeliveryOutcome {let sendsExistingDraft = outputPlan.plainText.isEmptylet outcome = await self.asr.typeOutputPlanToActiveFieldAndWait(@@ -2334,8 +2343,10 @@ struct ContentView: View {toggleStopRequestedAt: toggleStopRequestedAt,postInsertionKey: self.settings.spokenSendKey,requiredFocusTarget: stopSnapshot == nil ? self.recordingFocusTarget : stopSnapshot?.focusTarget,- preserveTranscriptOnClipboard: preserveTranscriptOnClipboard+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid)+ guard isOutputValid() else { return outcome }if outcome.didDispatchAction {NotchContentState.shared.setSpokenSendIndicatorState(.sent)try? await Task.sleep(nanoseconds: 350_000_000)@@ -2464,9 +2475,9 @@ struct ContentView: View {stopSnapshot = snapshot}- private func prepareStoppedDictationDelivery(_ text: String, keepBackup: Bool, snapshot: DictationStopSnapshot?, needsRestoration: Bool) async -> Bool {- if let snapshot { return await snapshot.prepareDelivery(text, keepBackup: keepBackup) }- return await self.prepareRecordingTargetForDelivery(text, keepBackup: keepBackup, needsRestoration: needsRestoration)+ private func prepareStoppedDictationDelivery(_ text: String, keepBackup: Bool, snapshot: DictationStopSnapshot?, needsRestoration: Bool, isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> Bool {+ if let snapshot { return await snapshot.prepareDelivery(text, keepBackup: keepBackup, isOutputValid: isOutputValid) }+ return await self.prepareRecordingTargetForDelivery(text, keepBackup: keepBackup, needsRestoration: needsRestoration, isOutputValid: isOutputValid)}private func showStoppedDictationDeliveryFailure(_ failure: TextDeliveryFailure, transcript: String, snapshot: DictationStopSnapshot?) {@@ -2914,6 +2925,12 @@ struct ContentView: View {// MARK: - Stop and Process Transcriptionprivate func stopAndProcessTranscription(route: DictationOutputRoute = .normal, toggleStopRequestedAt: TimeInterval? = nil) async {+ guard self.processingDictationLifecycleID == nil else { return }+ let outputLifecycleID = self.overlayLifecycleID+ self.processingDictationLifecycleID = outputLifecycleID+ defer {+ if self.processingDictationLifecycleID == outputLifecycleID { self.processingDictationLifecycleID = nil }+ }var closeTrace = OverlayCloseTrace("content.stopCallback")defer { closeTrace.finish() }let lifecycle = self.overlayLifecycleID@@ -2954,20 +2971,20 @@ struct ContentView: View {let promptOverride = self.promptModeOverrideTextlet promptTest = DictationPromptTestCoordinator.sharedlet promptTestSessionID = promptTest.isActive ? promptTest.sessionID : nil- var stopSnapshot = route == .normal && !wasRewriteMode && !wasCommandMode && !promptTest.isActive+ var stopSnapshot = route.savesHistory && !wasRewriteMode && !wasCommandMode && !promptTest.isActive? self.captureDictationStopSnapshot(slot: activeDictationSlot ?? .primary) : nillet shouldUseAIOnStop = stopSnapshot?.usesAI ?? activeDictationSlot.map {DictationAIPostProcessingGate.isConfigured(for: $0, appBundleID: self.recordingAppInfo?.bundleId)} ?? DictationAIPostProcessingGate.isConfigured(for: .primary, appBundleID: self.recordingAppInfo?.bundleId)- let shouldHideOverlayOnStop = route == .normal && !wasRewriteMode && !wasCommandMode- && !promptTest.isActive && !shouldUseAIOnStop && !self.settings.spokenSendEnabled+ let shouldHideOverlayOnStop = route == .historyOnly || self.cancelledOutputLifecycleID == expectedOverlayLifecycleID || (route == .normal && !wasRewriteMode && !wasCommandMode+ && !promptTest.isActive && !shouldUseAIOnStop && !self.settings.spokenSendEnabled)DebugLogger.shared.info("Routing decision snapshot | activeMode=\(modeAtStop.rawValue) | rewrite=\(wasRewriteMode) | command=\(wasCommandMode) | overlay=\(NotchContentState.shared.mode.rawValue)",source: "ContentView")self.clearActiveRecordingMode()- let stopOverlay = self.prepareOverlayForASRStop(shouldHideOverlayOnStop: shouldHideOverlayOnStop)+ let stopOverlay = self.prepareOverlayForASRStop(shouldHideOverlayOnStop: shouldHideOverlayOnStop, lifecycleID: expectedOverlayLifecycleID)let stopUIInvalidationHold = self.holdStopUIInvalidation(whileProcessing: !stopOverlay.didRequestHide)defer { self.releaseStopUIInvalidation(stopUIInvalidationHold) }@@ -3020,8 +3037,11 @@ struct ContentView: View {return}+ var cancelledAtASRStop = route == .historyOnly || self.cancelledOutputLifecycleID == expectedOverlayLifecycleID+ if cancelledAtASRStop, promptTestSessionID != nil || route == .onboardingSandbox { return }+// Prompt Test Mode: reroute dictation hotkey output into the prompt editor (no typing/clipboard/history).- if await self.routePromptTestResult(transcribedText, sessionID: promptTestSessionID, lifecycleID: expectedOverlayLifecycleID) {+ if !cancelledAtASRStop, await self.routePromptTestResult(transcribedText, sessionID: promptTestSessionID, lifecycleID: expectedOverlayLifecycleID) {return}@@ -3030,7 +3050,7 @@ struct ContentView: View {}// If this was a rewrite recording, process the rewrite instead of typing- if wasRewriteMode {+ if !cancelledAtASRStop, wasRewriteMode {DebugLogger.shared.info("Processing rewrite with instruction: \(transcribedText)", source: "ContentView")AnalyticsService.shared.recordModelUsage(role: .transcription,@@ -3038,12 +3058,13 @@ struct ContentView: View {descriptor: self.settings.selectedSpeechModel.analyticsDescriptor)let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()- await self.processRewriteWithVoiceInstruction(transcribedText, appInfo: appInfo)- return+ await self.processRewriteWithVoiceInstruction(transcribedText, appInfo: appInfo, lifecycleID: expectedOverlayLifecycleID)+ cancelledAtASRStop = self.cancelledOutputLifecycleID == expectedOverlayLifecycleID+ if !cancelledAtASRStop { return }}// If this was a command recording, process the command- if wasCommandMode {+ if !cancelledAtASRStop, wasCommandMode {DebugLogger.shared.info("Processing command: \(transcribedText)", source: "ContentView")AnalyticsService.shared.recordModelUsage(role: .transcription,@@ -3051,7 +3072,8 @@ struct ContentView: View {descriptor: self.settings.selectedSpeechModel.analyticsDescriptor)await self.processCommandWithVoice(transcribedText)- return+ cancelledAtASRStop = self.cancelledOutputLifecycleID == expectedOverlayLifecycleID+ if !cancelledAtASRStop { return }}var finalText: String@@ -3070,17 +3092,17 @@ struct ContentView: View {let spokenSendParse = SpokenSendParser.parseArmed(punctuationFormattedText,phrase: self.settings.spokenSendPhrase,- enabled: route == .normal && self.settings.spokenSendEnabled,+ enabled: !cancelledAtASRStop && route.deliversText && self.settings.spokenSendEnabled,wasArmed: self.spokenSendArming.wasArmed)self.updateSpokenSendIndicatorForFinalParse(shouldSend: spokenSendParse.shouldSend)let normalizedTranscribedText = spokenSendParse.text- let sendsExistingDraft = spokenSendParse.shouldSend &&+ var sendsExistingDraft = spokenSendParse.shouldSend &&normalizedTranscribedText.trimmingCharacters(in: .whitespacesAndNewlines).isEmptylet practiceModelID = route == .onboardingSandbox && self.settings.onboardingCurrentStep == 5? PrivateAIProviderPromptFormat.verifiedModelID(settings: self.settings) : nil- let shouldUseAI = !sendsExistingDraft && (practiceModelID != nil || (stopSnapshot?.usesAI ?? DictationAIPostProcessingGate.isConfigured(+ let shouldUseAI = !(cancelledAtASRStop && (wasRewriteMode || wasCommandMode)) && !sendsExistingDraft && (practiceModelID != nil || (stopSnapshot?.usesAI ?? DictationAIPostProcessingGate.isConfigured(for: activeDictationSlot ?? .primary,appBundleID: appInfo.bundleId)))@@ -3173,8 +3195,15 @@ struct ContentView: View {windowTitle: appInfo.windowTitle)self.recordingPrecedingText = ""- self.asr.finalText = finalText+ let outputRoute: DictationOutputRoute = route == .normal && self.cancelledOutputLifecycleID == expectedOverlayLifecycleID ? .historyOnly : route+ if outputRoute == .historyOnly, sendsExistingDraft {+ // Keep the spoken words recoverable when Escape cancels a send-only draft.+ sendsExistingDraft = false+ finalText = ASRService.applyGAAVFormatting(punctuationFormattedText)+ }+ if outputRoute.publishesEditorResult, self.cancelledOutputLifecycleID != expectedOverlayLifecycleID { self.asr.finalText = finalText }if route == .onboardingSandbox,+ self.cancelledOutputLifecycleID != expectedOverlayLifecycleID,self.isOnboardingVoicePlaygroundStepActive,!finalText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty{@@ -3209,7 +3238,8 @@ struct ContentView: View {self.appBench("text_ready chars=\(finalText.count)")self.appBench("pipeline_text_ready id=\(pipelineID) stopToReadyMs=\((finalTextReadyAt - pipelineStartedAt) * 1000)")- let shouldPersistOutputs = route == .normal+ let shouldPersistOutputs = outputRoute.savesHistory+ let shouldDeliverOutputs = outputRoute.deliversTextif !shouldPersistOutputs {DebugLogger.shared.info("Sandbox route active: suppressing clipboard/history/external typing side effects",@@ -3218,7 +3248,7 @@ struct ContentView: View {}let shouldShowAIProcessingFailure = DictationAIFailurePresentationPolicy.shouldPresent(- shouldPersistOutputs: shouldPersistOutputs,+ shouldPersistOutputs: shouldDeliverOutputs,fallbackReason: aiFallbackReason)if !shouldShowAIProcessingFailure {@@ -3235,7 +3265,7 @@ struct ContentView: View {TranscriptionHistoryStore.shared.addEntry(id: historyEntryID,timestamp: historyTimestamp,- rawText: spokenSendParse.shouldSend ? normalizedTranscribedText : transcribedText,+ rawText: outputRoute.deliversText && spokenSendParse.shouldSend ? normalizedTranscribedText : transcribedText,processedText: finalText,appName: appInfo.name,windowTitle: appInfo.windowTitle,@@ -3255,10 +3285,30 @@ struct ContentView: View {)}// When FluidVoice itself is frontmost, the bound editor already receives `finalText`.- let shouldCopyToClipboard = shouldPersistOutputs &&+ let shouldCopyToClipboard = shouldDeliverOutputs &&!sendsExistingDraft &&SettingsStore.shared.copyTranscriptionToClipboard- let shouldTypeExternally = shouldPersistOutputs && !isFluidFrontmost+ let shouldTypeExternally = shouldDeliverOutputs && !isFluidFrontmost++ // Send-only stops normally have no History row. Recover their words if+ // Escape arrives after the output decision but before delivery completes.+ func saveCancelledSendOnlyHistory() {+ guard sendsExistingDraft, self.settings.saveTranscriptionHistory else { return }+ let id = UUID()+ let timestamp = Date()+ TranscriptionHistoryStore.shared.addEntry(+ id: id,+ timestamp: timestamp,+ rawText: transcribedText,+ processedText: ASRService.applyGAAVFormatting(punctuationFormattedText),+ appName: appInfo.name,+ windowTitle: appInfo.windowTitle,+ wasAIProcessed: false,+ processingModel: nil,+ transcriptionDurationMilliseconds: transcriptionDurationMilliseconds+ )+ self.persistDictationAudioIfNeeded(audioSnapshot, entryID: id, timestamp: timestamp, model: transcriptionModelInfo.model)+ }var didTypeExternally = falsevar didFailTextDelivery = false@@ -3267,7 +3317,7 @@ struct ContentView: View {// A sidebar search field that was already focused when recording began gets// the text through its field editor, which also fires change notifications.- if isFluidFrontmost, shouldPersistOutputs, !sendsExistingDraft,+ if isFluidFrontmost, shouldDeliverOutputs, !sendsExistingDraft,let focusTarget = self.recordingFocusTarget,focusTarget.pid == ProcessInfo.processInfo.processIdentifier,TypingService.isExactFocusTargetActive(focusTarget),@@ -3293,7 +3343,18 @@ struct ContentView: View {&& !self.isSpokenSendBlockedApp(appInfo)// Dispatch insertion as soon as the destination app is ready; the// overlay hides asynchronously after output so it cannot delay paste.- let focusReady = await self.prepareStoppedDictationDelivery(finalText, keepBackup: shouldCopyToClipboard, snapshot: stopSnapshot, needsRestoration: typingTarget.shouldRestoreOriginalFocus)+ let focusReady = await self.prepareStoppedDictationDelivery(+ finalText,+ keepBackup: shouldCopyToClipboard,+ snapshot: stopSnapshot,+ needsRestoration: typingTarget.shouldRestoreOriginalFocus,+ isOutputValid: { self.cancelledOutputLifecycleID != expectedOverlayLifecycleID }+ )+ // Escape can arrive while focus restoration is suspended; History is already saved.+ guard self.cancelledOutputLifecycleID != expectedOverlayLifecycleID else {+ saveCancelledSendOnlyHistory()+ return+ }if spokenSendAllowed {NotchContentState.shared.setSpokenSendIndicatorState(.sending)@@ -3313,7 +3374,8 @@ struct ContentView: View {textReadyAt: finalTextReadyAt,toggleStopRequestedAt: toggleStopRequestedAt,preserveTranscriptOnClipboard: shouldCopyToClipboard,- stopSnapshot: stopSnapshot+ stopSnapshot: stopSnapshot,+ isOutputValid: { self.cancelledOutputLifecycleID != expectedOverlayLifecycleID })self.logPipelineCompletion(outcome: String(describing: deliveryOutcome),@@ -3335,7 +3397,8 @@ struct ContentView: View {textReadyAt: finalTextReadyAt,toggleStopRequestedAt: toggleStopRequestedAt,tracksDictionaryCorrections: true,- preserveTranscriptOnClipboard: shouldCopyToClipboard+ preserveTranscriptOnClipboard: shouldCopyToClipboard,+ isOutputValid: { self.cancelledOutputLifecycleID != expectedOverlayLifecycleID })didTypeExternally = deliveryResult.wasDispatchedself.handleTypingDelivery(@@ -3348,7 +3411,8 @@ struct ContentView: View {)}- guard self.overlayLifecycleID == expectedOverlayLifecycleID else {+ guard self.overlayLifecycleID == expectedOverlayLifecycleID, self.cancelledOutputLifecycleID != expectedOverlayLifecycleID else {+ if self.cancelledOutputLifecycleID == expectedOverlayLifecycleID { saveCancelledSendOnlyHistory() }self.appBench("delivery_ui_skipped reason=stale_recording")return}@@ -3384,9 +3448,11 @@ struct ContentView: View {}if !shouldTypeExternally {- await PasteDeliveryCoordinator.shared.copyBackup(finalText, enabled: shouldCopyToClipboard)+ await PasteDeliveryCoordinator.shared.copyBackup(finalText, enabled: shouldCopyToClipboard, isOutputValid: { self.cancelledOutputLifecycleID != expectedOverlayLifecycleID })}+ guard self.cancelledOutputLifecycleID != expectedOverlayLifecycleID || outputRoute == .historyOnly else { return }+// Submit raw fallback delivery before failure UI or notification work can// compete with it on the main actor. Sandbox runs never present either.if shouldShowAIProcessingFailure {@@ -3403,7 +3469,7 @@ struct ContentView: View {}if !shouldTypeExternally {self.logPipelineCompletion(- outcome: shouldPersistOutputs ? "internal_editor" : "sandbox",+ outcome: outputRoute == .historyOnly ? "history_only" : (shouldPersistOutputs ? "internal_editor" : "sandbox"),pipelineID: pipelineID,pipelineStartedAt: pipelineStartedAt,textReadyAt: finalTextReadyAt@@ -3451,10 +3517,10 @@ struct ContentView: View {bundleID: appInfo.bundleId,windowTitle: appInfo.windowTitle)- guard promptTest.acceptsResult(for: sessionID) else { return }+ guard promptTest.acceptsResult(for: sessionID), self.cancelledOutputLifecycleID != lifecycleID else { return }promptTest.lastOutputText = ASRService.applyGAAVFormatting(literalFormattedResult)} catch {- guard promptTest.acceptsResult(for: sessionID) else { return }+ guard promptTest.acceptsResult(for: sessionID), self.cancelledOutputLifecycleID != lifecycleID else { return }DebugLogger.shared.error("Prompt test AI call failed: \(error.localizedDescription)", source: "ContentView")promptTest.lastError = error.localizedDescription}@@ -3479,7 +3545,7 @@ struct ContentView: View {let statusTask = scheduleDeferredMainActorOperation(afterNanoseconds: Self.aiProcessingStatusDelayNanoseconds) {- guard self.overlayLifecycleID == lifecycleID else {+ guard self.overlayLifecycleID == lifecycleID, self.cancelledOutputLifecycleID != lifecycleID else {self.appBench("processing_ui_skipped status=Refining reason=stale_lifecycle")return}@@ -3490,14 +3556,14 @@ struct ContentView: View {self.appBench("processing_ui_requested status=Refining trigger=delayed_status")}let streamPreview = DictationAIStreamPreviewBuffer { text in- guard self.overlayLifecycleID == lifecycleID else { return }+ guard self.overlayLifecycleID == lifecycleID, self.cancelledOutputLifecycleID != lifecycleID else { return }NotchOverlayManager.shared.updateTranscriptionText(text)}return (statusTask, streamPreview)}private func prepareOverlayForASRStop(- shouldHideOverlayOnStop: Bool+ shouldHideOverlayOnStop: Bool, lifecycleID: UInt64) -> (didRequestHide: Bool, onFinalTranscriptionStarted: (@MainActor () -> Void)?) {if shouldHideOverlayOnStop {DebugLogger.shared.debug("Hiding dictation overlay at stop path", source: "ContentView")@@ -3519,6 +3585,7 @@ struct ContentView: View {self.menuBarManager.reserveProcessingOverlay()self.appBench("processing_ui_reserved trigger=warm_final_asr")let onFinalTranscriptionStarted: @MainActor () -> Void = {+ guard self.overlayLifecycleID == lifecycleID, self.cancelledOutputLifecycleID != lifecycleID else { return }self.menuBarManager.flushDeferredStoppedRecordingState()self.appBench("processing_ui_request status=Transcribing trigger=final_executor")self.menuBarManager.setProcessing(true)@@ -3700,6 +3767,7 @@ struct ContentView: View {guard self.settings.spokenSendEnabled else { return }let isDictationMode = self.activeRecordingMode == .dictate || self.activeRecordingMode == .promptModelet isEligible = isDictationMode &&+ self.cancelledOutputLifecycleID != self.overlayLifecycleID &&self.currentDictationOutputRouteForHotkeyStop() == .normal &&self.asr.isRunning &&!self.spokenSendAutoStopTriggered@@ -4315,7 +4383,8 @@ struct ContentView: View {private func processRewriteWithVoiceInstruction(_ instruction: String,- appInfo: (name: String, bundleId: String, windowTitle: String)+ appInfo: (name: String, bundleId: String, windowTitle: String),+ lifecycleID: UInt64) async {self.rewriteModeService.setPromptAppBundleID(appInfo.bundleId)let hasOriginalText = !self.rewriteModeService.originalText.isEmpty@@ -4331,6 +4400,7 @@ struct ContentView: View {// - With originalText: rewrites existing text based on instruction// - Without originalText: improves/refines the spoken textawait self.rewriteModeService.processRewriteRequest(instruction)+ guard self.cancelledOutputLifecycleID != lifecycleID else { return }// If rewrite was successful, type the resultif !self.rewriteModeService.rewrittenText.isEmpty {@@ -4339,7 +4409,8 @@ struct ContentView: View {// Type the rewritten textlet typingTarget = self.resolveTypingTargetPID()if typingTarget.shouldRestoreOriginalFocus {- guard await self.prepareRecordingTargetForDelivery(self.rewriteModeService.rewrittenText, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard) else {+ guard await self.prepareRecordingTargetForDelivery(self.rewriteModeService.rewrittenText, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard, isOutputValid: { self.cancelledOutputLifecycleID != lifecycleID }) else {+ guard self.cancelledOutputLifecycleID != lifecycleID else { return }self.showTextDeliveryFailure(.targetRestoreFailed,transcript: self.rewriteModeService.rewrittenText@@ -4350,8 +4421,10 @@ struct ContentView: View {let deliveryResult = await self.asr.typeTextToActiveField(self.rewriteModeService.rewrittenText,preferredTargetPID: typingTarget.pid,- preserveTranscriptOnClipboard: SettingsStore.shared.copyTranscriptionToClipboard+ preserveTranscriptOnClipboard: SettingsStore.shared.copyTranscriptionToClipboard,+ isOutputValid: { self.cancelledOutputLifecycleID != lifecycleID })+ guard self.cancelledOutputLifecycleID != lifecycleID else { return }if case let .recoverableFailure(failure) = deliveryResult {self.showTextDeliveryFailure(failure, transcript: self.rewriteModeService.rewrittenText)return@@ -4468,6 +4541,7 @@ struct ContentView: View {/// Capture app context at start to avoid mismatches if the user switches apps mid-sessionprivate func startRecording() -> Task<Void, Never>? {+ guard !self.isSavingCancelledRecording, self.processingDictationLifecycleID == nil else { return nil }// Browsing the demo must not send dictation to a previously focused app.guard !self.showsFluidIntelligenceDemo || (DictationPromptTestCoordinator.shared.isActive && !DictationPromptTestCoordinator.shared.isProcessing) else { return nil }guard !self.presentExclusiveActivityBlockIfNeeded() else { return nil }@@ -4609,19 +4683,20 @@ struct ContentView: View {}/// Restores only the window and element captured when recording started.- private func prepareRecordingTargetForDelivery(_ transcript: String, keepBackup: Bool, needsRestoration: Bool = true) async -> Bool {+ private func prepareRecordingTargetForDelivery(_ transcript: String, keepBackup: Bool, needsRestoration: Bool = true, isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> Bool {+ guard isOutputValid() else { return false }guard needsRestoration else { return true }- return await PasteDeliveryCoordinator.shared.prepareForDelivery(transcript, preserveTranscriptOnClipboard: keepBackup) {- await self.restoreFocusToRecordingTarget()+ return await PasteDeliveryCoordinator.shared.prepareForDelivery(transcript, preserveTranscriptOnClipboard: keepBackup, isOutputValid: isOutputValid) {+ await self.restoreFocusToRecordingTarget(isOutputValid: isOutputValid)}}- private func restoreFocusToRecordingTarget() async -> Bool {+ private func restoreFocusToRecordingTarget(isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> Bool {guard let context = NotchContentState.shared.recordingTargetContext else { return false }let pid = context.pidlet startedAt = ProcessInfo.processInfo.systemUptimeself.appBench("focus_restore_start targetPID=\(pid)")- let result = await TypingService.prepareTargetForDelivery(context)+ let result = await TypingService.prepareTargetForDelivery(context, isOutputValid: isOutputValid)self.appBench("focus_restore_result result=\(result.rawValue) elapsedMs=\(Int(((ProcessInfo.processInfo.systemUptime - startedAt) * 1000).rounded()))")@@ -4916,40 +4991,7 @@ struct ContentView: View {// Set cancel callback for Escape key handling (closes transient UI, resets recording state)// Returns true if it handled something (so GlobalHotkeyManager knows to consume the event)self.hotkeyManager?.setCancelCallback {- var handled = false-- // The suggestion panel is non-activating, so its Escape key arrives- // through the global event tap while the target app stays focused.- if DictionaryCorrectionOverlayController.shared.isPresented {- DebugLogger.shared.debug("Cancel callback: closing dictionary suggestion", source: "ContentView")- DictionaryCorrectionOverlayController.shared.dismiss()- return true- }-- // Close expanded command notch if visible (highest priority)- if NotchOverlayManager.shared.isCommandOutputExpanded {- DebugLogger.shared.debug("Cancel callback: closing expanded command notch", source: "ContentView")- NotchOverlayManager.shared.hideExpandedCommandOutput()- handled = true- }-- // Reset recording mode flags- if self.activeRecordingMode != .none {- self.cancelPrewarmDictationIfNeeded()- self.clearActiveRecordingMode()- handled = true- }-- // Close rewrite mode if open. Command Mode stays open so Escape can cancel voice capture without leaving the tool.- if self.selectedSidebarItem == .rewriteMode {- DebugLogger.shared.debug("Cancel callback: closing mode view", source: "ContentView")- DispatchQueue.main.async {- self.navigateToApp(.welcome)- }- handled = true- }-- return handled+ self.handleCancelShortcut()}// Re-insert the most recent transcription on demand (no clipboard involved).@@ -4983,46 +5025,72 @@ struct ContentView: View {@discardableResultprivate func handleCancelShortcut() -> Bool {+ if self.isSavingCancelledRecording { return true }var handled = falseif DictionaryCorrectionOverlayController.shared.isPresented {- DebugLogger.shared.debug("Cancel shortcut: closing dictionary suggestion", source: "ContentView")DictionaryCorrectionOverlayController.shared.dismiss()- return true+ handled = true}-if NotchOverlayManager.shared.isCommandOutputExpanded {- DebugLogger.shared.debug("Cancel shortcut: closing expanded command notch", source: "ContentView")NotchOverlayManager.shared.hideExpandedCommandOutput()NotchOverlayManager.shared.onCommandOutputDismiss?()handled = true}- if self.asr.isRunningOrStarting {- DebugLogger.shared.debug("Cancel shortcut: cancelling ASR recording", source: "ContentView")- let isOnboardingTryout = self.isOnboardingVoicePlaygroundStepActive- Task {- await self.asr.stopWithoutTranscription()- if isOnboardingTryout {- AnalyticsService.shared.recordOnboardingTryoutAttemptResult(outcome: .cancelled)+ if let lifecycleID = self.processingDictationLifecycleID {+ // A stop already owns the audio; suppress its pending output without stopping again.+ self.cancelledOutputLifecycleID = lifecycleID+ handled = true+ } else if self.asr.isRunningOrStarting {+ let preservesHistory = self.settings.saveTranscriptionHistory && self.asr.isRunning && !self.asr.isDictionaryTrainingCaptureActive+ && self.currentDictationOutputRouteForHotkeyStop() != .onboardingSandbox+ && !DictationPromptTestCoordinator.shared.isActive && !self.showsFluidIntelligenceDemo+ if preservesHistory {+ self.isSavingCancelledRecording = true+ self.cancelledOutputLifecycleID = self.overlayLifecycleID+ let manager = self.hotkeyManager+ let stopLockStartedAt = manager?.traceStopLocked()+ Task {+ defer {+ self.isSavingCancelledRecording = false+ if let stopLockStartedAt { manager?.traceStopUnlocked(since: stopLockStartedAt) }+ }+ await self.stopAndProcessTranscription(route: .historyOnly)+ }+ } else {+ let isOnboardingTryout = self.isOnboardingVoicePlaygroundStepActive+ Task {+ await self.asr.stopWithoutTranscription()+ if isOnboardingTryout {+ AnalyticsService.shared.recordOnboardingTryoutAttemptResult(outcome: .cancelled)+ }}+ self.clearActiveRecordingMode()}self.cancelPrewarmDictationIfNeeded()handled = true+ } else if self.activeRecordingMode != .none {+ self.cancelPrewarmDictationIfNeeded()+ self.clearActiveRecordingMode()+ handled = true}- if NotchOverlayManager.shared.isBottomOverlayVisible || NotchOverlayManager.shared.isOverlayVisible {- DebugLogger.shared.debug("Cancel shortcut: hiding recording overlay", source: "ContentView")- NotchOverlayManager.shared.hide()+ if handled || NotchOverlayManager.shared.isBottomOverlayVisible || NotchOverlayManager.shared.isOverlayVisible {+ self.menuBarManager.beginProcessingCompletionAndHideOverlay()handled = true}-if self.selectedSidebarItem == .rewriteMode {- DebugLogger.shared.debug("Cancel shortcut: closing mode view", source: "ContentView")self.navigateToApp(.welcome)handled = true}-+ if handled {+ self.spokenSendAutoStopTask?.cancel()+ self.spokenSendAutoStopTask = nil+ self.stopSpokenSendVoiceActivityMonitoring()+ self.spokenSendCountdownStartedAt = nil+ self.hotkeyManager?.resetModifierOnlyShortcutTracking(reason: .cancel)+ }return handled}@@ -5206,6 +5274,7 @@ extension ContentView {mode: ActiveRecordingMode,startMethod: AnalyticsOnboardingTryoutStartMethod = .hotkey) -> Task<Void, Never>? {+ guard !self.isSavingCancelledRecording, self.processingDictationLifecycleID == nil else { return nil }guard !self.presentExclusiveActivityBlockIfNeeded() else { return nil }DebugLogger.shared.debug("Begin dictation recording for slot \(slot.rawValue)", source: "ContentView")DebugLogger.shared.debug("CLOSE_DETAIL nextStartRequested uptime=\(ProcessInfo.processInfo.systemUptime)", source: "StopTiming")diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex 50f59f06..6c1c6457 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -7158,13 +7158,15 @@ final class ASRService: ObservableObject {_ text: String,preferredTargetPID: pid_t?,textReadyAt: TimeInterval? = nil,- preserveTranscriptOnClipboard: Bool = false+ preserveTranscriptOnClipboard: Bool = false,+ isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> TextDeliveryResult {await self.typeOutputPlanToActiveField(.plain(text),preferredTargetPID: preferredTargetPID,textReadyAt: textReadyAt,- preserveTranscriptOnClipboard: preserveTranscriptOnClipboard+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid)}@@ -7175,7 +7177,8 @@ final class ASRService: ObservableObject {textReadyAt: TimeInterval? = nil,toggleStopRequestedAt: TimeInterval? = nil,tracksDictionaryCorrections: Bool = false,- preserveTranscriptOnClipboard: Bool = false+ preserveTranscriptOnClipboard: Bool = false,+ isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> TextDeliveryResult {let requestedAt = ProcessInfo.processInfo.systemUptimelet textReadyAge = textReadyAt.map { Int(((requestedAt - $0) * 1000).rounded()) }@@ -7191,7 +7194,8 @@ final class ASRService: ObservableObject {textReadyAt: textReadyAt,toggleStopRequestedAt: toggleStopRequestedAt,tracksDictionaryCorrections: tracksDictionaryCorrections,- preserveTranscriptOnClipboard: preserveTranscriptOnClipboard+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid)let dispatchedAt = ProcessInfo.processInfo.systemUptimelet textReadyToDispatchMs = textReadyAt.map {@@ -7227,7 +7231,8 @@ final class ASRService: ObservableObject {tracksDictionaryCorrections: Bool = false,postInsertionKey: SettingsStore.SpokenSendKey? = nil,requiredFocusTarget: TypingService.CapturedFocusTarget? = nil,- preserveTranscriptOnClipboard: Bool = false+ preserveTranscriptOnClipboard: Bool = false,+ isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> TypingService.DeliveryOutcome {let requestedAt = ProcessInfo.processInfo.systemUptimelet textReadyAge = textReadyAt.map { Int(((requestedAt - $0) * 1000).rounded()) }@@ -7246,7 +7251,8 @@ final class ASRService: ObservableObject {tracksDictionaryCorrections: tracksDictionaryCorrections,postInsertionKey: postInsertionKey,requiredFocusTarget: requiredFocusTarget,- preserveTranscriptOnClipboard: preserveTranscriptOnClipboard+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid) { outcome incontinuation.resume(returning: outcome)}diff --git a/Sources/Fluid/Services/DictationStopSnapshot.swift b/Sources/Fluid/Services/DictationStopSnapshot.swiftindex 7b5700ee..d3b41da2 100644--- a/Sources/Fluid/Services/DictationStopSnapshot.swift+++ b/Sources/Fluid/Services/DictationStopSnapshot.swift@@ -71,10 +71,10 @@ struct DictationStopSnapshot {}@MainActor- func prepareDelivery(_ text: String, keepBackup: Bool) async -> Bool {+ func prepareDelivery(_ text: String, keepBackup: Bool, isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> Bool {guard let target else { return false }- return await PasteDeliveryCoordinator.shared.prepareForDelivery(text, preserveTranscriptOnClipboard: keepBackup) {- await TypingService.prepareTargetForDelivery(target).isReady+ return await PasteDeliveryCoordinator.shared.prepareForDelivery(text, preserveTranscriptOnClipboard: keepBackup, isOutputValid: isOutputValid) {+ await TypingService.prepareTargetForDelivery(target, isOutputValid: isOutputValid).isReady}}}diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swiftindex 6b626831..a91b2f74 100644--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift@@ -327,6 +327,7 @@ final class GlobalHotkeyManager: NSObject {case shortcutCapturecase tapDisabledcase reinitialize+ case cancel}private nonisolated var isKeyPressed: Bool {@@ -1271,28 +1272,16 @@ final class GlobalHotkeyManager: NSObject {{ self.activePrimaryShortcutPress = nil }self.markOtherInputDuringModifierOnly()- // Check the configured cancel shortcut first.+ // The application owns cancellation output; fallback managers only discard capture.if SettingsStore.shared.cancelRecordingHotkeyShortcut?.matches(keyCode: keyCode, modifiers: eventModifiers) == true {- var handled = self.pendingRecordingActionCounts.values.contains { $0 > 0 }-- if self.asrService.isRunning || self.asrService.isStarting {- DebugLogger.shared.info("Cancel shortcut pressed - cancelling recording", source: "GlobalHotkeyManager")- Task { @MainActor in- await self.asrService.stopWithoutTranscription()- }- handled = true- }-- // Trigger cancel callback to close mode views / reset state- if let callback = cancelCallback, callback() {- DebugLogger.shared.info("Cancel shortcut pressed - cancel callback handled", source: "GlobalHotkeyManager")+ var handled = self.cancelCallback?() ?? false+ if !handled, self.asrService.isRunningOrStarting {+ Task { @MainActor in await self.asrService.stopWithoutTranscription() }handled = true}-- if handled {- self.invalidateAllRecordingActions()- if self.hotkeyMode == .toggle { self.activePrimaryShortcutPress = nil }- return nil // Consume event only if we did something+ if handled || self.pendingRecordingActionCounts.values.contains(where: { $0 > 0 }) {+ self.resetModifierOnlyShortcutTracking(reason: .cancel)+ return nil}}@@ -1965,7 +1954,7 @@ final class GlobalHotkeyManager: NSObject {self.invalidateAllRecordingActions()self.modifierPressReceivedAt = nilself.currentStopPressReceivedAt = nil- let shouldStopActiveHold = self.hotkeyMode != .toggle+ let shouldStopActiveHold = reason != .cancel && self.hotkeyMode != .toggle&& self.asrService.isRunningOrStarting&& (self.isKeyPressed || self.isPromptModeKeyPressed || self.isCommandModeKeyPressed || self.isRewriteKeyPressed || self.isPromptAssignmentKeyPressed)@@ -1990,6 +1979,8 @@ final class GlobalHotkeyManager: NSObject {DebugLogger.shared.debug("Shortcut capture active - stopping active hold recording before reset", source: "GlobalHotkeyManager")case .tapDisabled:DebugLogger.shared.warning("Event tap disabled during active hold - stopping recording before reset", source: "GlobalHotkeyManager")+ case .cancel:+ breakcase .reinitialize:DebugLogger.shared.info("Hotkey manager reinitializing - stopping active hold recording before reset", source: "GlobalHotkeyManager")}@@ -2679,7 +2670,9 @@ private extension GlobalHotkeyManager {return press.shortcut}}+}+extension GlobalHotkeyManager {func traceStopLocked() -> TimeInterval {OverlayCloseRunLoopProbe.begin()self.isProcessingStop = true@@ -2693,9 +2686,7 @@ private extension GlobalHotkeyManager {source: "StopTiming")}-}-extension GlobalHotkeyManager {nonisolated static func isSynthesizedTypingEvent(_ event: CGEvent) -> Bool {event.getIntegerValueField(.eventSourceUserData) == TypingService.synthesizedEventUserData}diff --git a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift b/Sources/Fluid/Services/PasteDeliveryCoordinator.swiftindex 54d93466..37ff6d2c 100644--- a/Sources/Fluid/Services/PasteDeliveryCoordinator.swift+++ b/Sources/Fluid/Services/PasteDeliveryCoordinator.swift@@ -40,6 +40,7 @@ enum TextDeliveryFailure: String, Equatable {}enum TextDeliveryResult: Equatable {+ case cancelledcase commandPostedcase recoverableFailure(TextDeliveryFailure)@@ -617,6 +618,7 @@ final class PasteDeliveryCoordinator {let text: Stringlet generation: UInt64let shouldKeepTranscript: Bool+ let isOutputValid: @MainActor () -> Boolvar settlementTask: Task<Void, Never>?}@@ -642,8 +644,10 @@ final class PasteDeliveryCoordinator {func deliver(_ text: String,preserveTranscriptOnClipboard: Bool,+ isOutputValid: @escaping @MainActor () -> Bool = { true },onCommandPosted: ((TimeInterval) -> Void)? = nil) async -> TextDeliveryResult {+ guard isOutputValid() else { return .cancelled }self.log("delivery_policy keepTranscript=\(preserveTranscriptOnClipboard) auditSchema=1")let slotRequestedAt = ProcessInfo.processInfo.systemUptimeawait self.acquireDeliverySlot()@@ -653,6 +657,7 @@ final class PasteDeliveryCoordinator {if !settlementOwnsSlot { self.releaseDeliverySlot() }}+ guard isOutputValid() else { return .cancelled }let startedAt = ProcessInfo.processInfo.systemUptimeself.generation &+= 1let generation = self.generation@@ -681,11 +686,16 @@ final class PasteDeliveryCoordinator {)self.pasteboard.recordAudit("command_before", detail: "session=\(sessionID)")+ guard isOutputValid() else {+ self.finishFailedDelivery(originalSnapshot, sessionID: sessionID, text: text, originalChangeCount: originalChangeCount, keepBackup: false)+ return .cancelled+ }let commandPosted = await self.commandPoster.postGlobalPasteCommand()let commandPostedAt = ProcessInfo.processInfo.systemUptimeself.pasteboard.recordAudit("command_after", detail: "session=\(sessionID) success=\(commandPosted)")guard commandPosted else {- self.finishFailedDelivery(originalSnapshot, sessionID: sessionID, text: text, originalChangeCount: originalChangeCount, keepBackup: preserveTranscriptOnClipboard)+ self.finishFailedDelivery(originalSnapshot, sessionID: sessionID, text: text, originalChangeCount: originalChangeCount, keepBackup: preserveTranscriptOnClipboard && isOutputValid())+ if !isOutputValid() { return .cancelled }self.log("delivery_failed generation=\(generation) reason=paste_command_failed")return .recoverableFailure(.pasteCommandFailed)}@@ -701,6 +711,7 @@ final class PasteDeliveryCoordinator {text: text,generation: generation,shouldKeepTranscript: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid,settlementTask: nil)// Return immediately to finish delivery UI, but retain exclusive clipboard use@@ -714,24 +725,28 @@ final class PasteDeliveryCoordinator {func prepareForDelivery(_ text: String,preserveTranscriptOnClipboard: Bool,+ isOutputValid: @escaping @MainActor () -> Bool = { true },prepare: () async -> Bool) async -> Bool {+ guard isOutputValid() else { return false }let changeCount = self.pasteboard.changeCountlet generation = self.generationlet ready = await prepare()+ guard isOutputValid() else { return false }if !ready, self.generation == generation {- await self.copyBackup(text, enabled: preserveTranscriptOnClipboard, expectedChangeCount: changeCount)+ await self.copyBackup(text, enabled: preserveTranscriptOnClipboard, expectedChangeCount: changeCount, isOutputValid: isOutputValid)}return ready}/// Serialize standalone copies with active paste leases so cleanup cannot undo the backup.@discardableResult- func copyBackup(_ text: String, enabled: Bool, expectedChangeCount: Int? = nil) async -> Bool {- guard enabled, !text.isEmpty else { return false }+ func copyBackup(_ text: String, enabled: Bool, expectedChangeCount: Int? = nil, isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> Bool {+ guard enabled, isOutputValid(), !text.isEmpty else { return false }let requestedChangeCount = expectedChangeCount ?? self.pasteboard.changeCountawait self.acquireDeliverySlot()defer { self.releaseDeliverySlot() }+ guard isOutputValid() else { return false }guard self.pasteboard.changeCount == requestedChangeCount ||self.pasteboard.changeCount == self.lastWrittenChangeCountelse {@@ -807,7 +822,7 @@ final class PasteDeliveryCoordinator {}let restoreStartedAt = ProcessInfo.processInfo.systemUptime- if lease.shouldKeepTranscript {+ if lease.shouldKeepTranscript, lease.isOutputValid() {let didWrite = self.writeBackup(lease.text)self.log("intentional_copy_settled generation=\(generation) success=\(didWrite) elapsedMs=\((ProcessInfo.processInfo.systemUptime - restoreStartedAt) * 1000)")} else {diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swiftindex abe9477c..7f1898c7 100644--- a/Sources/Fluid/Services/TypingService.swift+++ b/Sources/Fluid/Services/TypingService.swift@@ -308,29 +308,30 @@ final class TypingService {TypingService().captureTextBeforeCursorInFocusedField()}- static func prepareTargetForDelivery(_ context: RecordingTargetContext) async -> FocusPreparationResult {+ static func prepareTargetForDelivery(_ context: RecordingTargetContext, isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> FocusPreparationResult {+ guard isOutputValid() else { return .failed }if context.pid == self.currentFocusedPID(),context.element == nil || self.isCapturedFocusStillActive(context){return .alreadyFocused}- if await self.restoreExactTarget(context) {+ if await self.restoreExactTarget(context, isOutputValid: isOutputValid) {return .restoredExactTarget}- guard context.window != nil, context.element != nil,+ guard isOutputValid(), context.window != nil, context.element != nil,self.activateAppForRecovery(pid: context.pid)else {return .failed}try? await Task.sleep(nanoseconds: 25_000_000)- return await self.restoreExactTarget(context) ? .activatedForRecovery : .failed+ return await self.restoreExactTarget(context, isOutputValid: isOutputValid) ? .activatedForRecovery : .failed}- private static func restoreExactTarget(_ context: RecordingTargetContext) async -> Bool {- guard AXIsProcessTrusted(), context.window != nil, context.element != nil else { return false }+ private static func restoreExactTarget(_ context: RecordingTargetContext, isOutputValid: @escaping @MainActor () -> Bool) async -> Bool {+ guard isOutputValid(), AXIsProcessTrusted(), context.window != nil, context.element != nil else { return false }self.logFocusState("[TypingService] Before restoreExactTarget")let appElement = AXUIElementCreateApplication(context.pid)@@ -342,9 +343,10 @@ final class TypingService {try? await Task.sleep(nanoseconds: 25_000_000)}- guard let element = context.element else { return false }+ guard isOutputValid(), let element = context.element else { return false }for attempt in 0..<3 {+ guard isOutputValid() else { return false }let result = AXUIElementSetAttributeValue(element,kAXFocusedAttribute as CFString,@@ -443,14 +445,16 @@ final class TypingService {preferredTargetPID: pid_t?,textReadyAt: TimeInterval?,toggleStopRequestedAt: TimeInterval? = nil,- preserveTranscriptOnClipboard: Bool = false+ preserveTranscriptOnClipboard: Bool = false,+ isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> TextDeliveryResult {await self.typeOutputPlanInstantly(.plain(text),preferredTargetPID: preferredTargetPID,textReadyAt: textReadyAt,toggleStopRequestedAt: toggleStopRequestedAt,- preserveTranscriptOnClipboard: preserveTranscriptOnClipboard+ preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid)}@@ -462,8 +466,10 @@ final class TypingService {toggleStopRequestedAt: TimeInterval? = nil,tracksDictionaryCorrections: Bool = false,preserveTranscriptOnClipboard: Bool = false,- verifiesLanding: Bool = true+ verifiesLanding: Bool = true,+ isOutputValid: @escaping @MainActor () -> Bool = { true }) async -> TextDeliveryResult {+ guard isOutputValid() else { return .cancelled }let requestedAt = ProcessInfo.processInfo.systemUptimevar closeTrace = OverlayCloseTrace("typing.delivery")defer { closeTrace.finish() }@@ -493,7 +499,8 @@ final class TypingService {// Check accessibility permissions firstguard AXIsProcessTrusted() else {- await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard)+ await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard, isOutputValid: isOutputValid)+ guard isOutputValid() else { return .cancelled }self.bench("request_return reason=accessibility_not_trusted")self.log("[TypingService] ERROR: Accessibility permissions required for text injection")self.log("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")@@ -512,7 +519,8 @@ final class TypingService {let targetAssessment = DeliveryTargetAssessment.assessFocusedElement()DebugLogger.shared.info("FOCUS_ASSESS \(targetAssessment.logDescription)", source: "TypingService")if targetAssessment.isCertainlyNotEditable {- await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard)+ await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard, isOutputValid: isOutputValid)+ guard isOutputValid() else { return .cancelled }self.bench("request_return reason=no_editable_target")let result = TextDeliveryResult.recoverableFailure(.noEditableTarget)self.recordInsertionLatency(@@ -538,11 +546,12 @@ final class TypingService {result = await PasteDeliveryCoordinator.shared.deliver(text,preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid,onCommandPosted: { dispatchedAt = $0 })- } else if await self.insertTextDirectlyOffMain(text, preferredTargetPID: preferredTargetPID) {+ } else if await self.insertTextDirectlyOffMain(text, preferredTargetPID: preferredTargetPID, isOutputValid: isOutputValid) {deliveryPath = .direct- await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard)+ await PasteDeliveryCoordinator.shared.copyBackup(text, enabled: preserveTranscriptOnClipboard, isOutputValid: isOutputValid)result = .commandPosted} else {deliveryPath = .clipboardFallback@@ -551,10 +560,12 @@ final class TypingService {result = await PasteDeliveryCoordinator.shared.deliver(text,preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,+ isOutputValid: isOutputValid,onCommandPosted: { dispatchedAt = $0 })}+ guard result != .cancelled, isOutputValid() else { return .cancelled }let completedAt = dispatchedAt ?? ProcessInfo.processInfo.systemUptimeself.bench("complete result=\(String(describing: result)) totalMs=\(Self.elapsedMs(from: requestedAt, to: completedAt)) textReadyToCompleteMs=\(textReadyAt.map { String(Self.elapsedMs(from: $0, to: completedAt)) } ?? "nil")"@@ -585,9 +596,11 @@ final class TypingService {postInsertionKey: SettingsStore.SpokenSendKey? = nil,requiredFocusTarget: CapturedFocusTarget? = nil,preserveTranscriptOnClipboard: Bool = false,+ isOutputValid: @escaping @MainActor () -> Bool = { true },completion: (@MainActor (DeliveryOutcome) -> Void)? = nil) {Task { @MainActor in+ guard isOutputValid() else { completion?(.rejected); return }let hasTextToInsert = !plan.plainText.isEmptyguard hasTextToInsert || postInsertionKey != nil else {completion?(.rejected)@@ -603,7 +616,7 @@ final class TypingService {exactFocusIsActive: Self.isExactFocusTargetActive(requiredFocusTarget))else {- await PasteDeliveryCoordinator.shared.copyBackup(plan.plainText, enabled: preserveTranscriptOnClipboard)+ await PasteDeliveryCoordinator.shared.copyBackup(plan.plainText, enabled: preserveTranscriptOnClipboard, isOutputValid: isOutputValid)completion?(.actionSuppressed)return}@@ -619,15 +632,17 @@ final class TypingService {tracksDictionaryCorrections: tracksDictionaryCorrections,preserveTranscriptOnClipboard: preserveTranscriptOnClipboard,// A send key empties the field right after the paste, so the read-back would report a false miss.- verifiesLanding: postInsertionKey == nil+ verifiesLanding: postInsertionKey == nil,+ isOutputValid: isOutputValid)guard result.wasDispatched else {- completion?(.insertionFailed)+ completion?(result == .cancelled ? .rejected : .insertionFailed)return}outcome = .inserted}+ guard isOutputValid() else { completion?(hasTextToInsert ? .insertedActionSuppressed : .actionSuppressed); return }guard let postInsertionKey else {completion?(outcome)if tracksDictionaryCorrections, outcome.didInsert {@@ -645,7 +660,7 @@ final class TypingService {}let modifiersReleased = await self.waitForPhysicalModifiersToRelease(timeout: 2)- guard Self.canDispatchPostInsertionAction(+ guard isOutputValid(), Self.canDispatchPostInsertionAction(preferredTargetPID: preferredTargetPID,requiredTargetPID: requiredFocusTarget.pid,isSecureTextField: requiredFocusTarget.isSecureTextField,@@ -657,7 +672,7 @@ final class TypingService {}try? await Task.sleep(nanoseconds: 50_000_000)- guard Self.isExactFocusTargetActive(requiredFocusTarget),+ guard isOutputValid(), Self.isExactFocusTargetActive(requiredFocusTarget),await self.postReturnKey(postInsertionKey, targetPID: preferredTargetPID)else {completion?(hasTextToInsert ? .insertedActionSuppressed : .actionSuppressed)@@ -679,7 +694,7 @@ final class TypingService {toggleStopRequestedAt: TimeInterval?,completedAt: TimeInterval = ProcessInfo.processInfo.systemUptime) {- let outcome = Self.analyticsOutcome(for: result)+ guard let outcome = Self.analyticsOutcome(for: result) else { return }let isClipboardDispatch = outcome == .dispatched &&(path == .clipboard || path == .clipboardFallback)AnalyticsService.shared.recordInsertionLatency(@@ -720,8 +735,10 @@ final class TypingService {}}- private static func analyticsOutcome(for result: TextDeliveryResult) -> AnalyticsInsertionOutcome {+ private static func analyticsOutcome(for result: TextDeliveryResult) -> AnalyticsInsertionOutcome? {switch result {+ case .cancelled:+ nilcase .commandPosted:.dispatchedcase let .recoverableFailure(failure):@@ -749,9 +766,11 @@ final class TypingService {// MARK: - Internal insertion pipeline- private func insertTextDirectlyOffMain(_ text: String, preferredTargetPID: pid_t?) async -> Bool {+ private func insertTextDirectlyOffMain(_ text: String, preferredTargetPID: pid_t?, isOutputValid: @escaping @MainActor () -> Bool) async -> Bool {await withCheckedContinuation { continuation inSelf.directInsertionQueue.async {+ let valid = DispatchQueue.main.sync { MainActor.assumeIsolated { isOutputValid() } }+ guard valid else { continuation.resume(returning: false); return }continuation.resume(returning: self.insertTextDirectly(text, preferredTargetPID: preferredTargetPID))diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swiftindex 99c76a43..7885038c 100644--- a/Sources/Fluid/UI/SettingsView.swift+++ b/Sources/Fluid/UI/SettingsView.swift@@ -744,7 +744,7 @@ struct SettingsView: View {icon: "xmark.circle.fill",iconColor: .secondary,title: "Cancel Recording",- description: "Cancel the current recording or dismiss the active recording overlay"+ description: "Stop without pasting; save to History when enabled"),shortcut: self.cancelRecordingShortcut,isRecording: self.isRecording(.cancel),diff --git a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swiftindex 483c619e..2f35489d 100644--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift@@ -934,6 +934,58 @@ final class DirectAudioReliabilityTests: XCTestCase {XCTAssertLessThan(cancellationCheck.lowerBound, readinessBranch.lowerBound, "Do not publish ready PCM before checking task cancellation")}+ func testHistoryOnlyOutputWiringSeparatesPersistenceFromDelivery() throws {+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()+ let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)+ let pipeline = try XCTUnwrap(source.components(separatedBy: "private func processStoppedTranscription(").last?.components(separatedBy: "private func processDictationPromptTest(").first)+ XCTAssertTrue(pipeline.contains("let shouldPersistOutputs = outputRoute.savesHistory"))+ XCTAssertTrue(pipeline.contains("let shouldDeliverOutputs = outputRoute.deliversText"))+ XCTAssertTrue(pipeline.contains("if shouldPersistOutputs, !sendsExistingDraft, SettingsStore.shared.saveTranscriptionHistory"))+ XCTAssertTrue(pipeline.contains("let shouldCopyToClipboard = shouldDeliverOutputs"))+ XCTAssertTrue(pipeline.contains("let shouldTypeExternally = shouldDeliverOutputs"))+ XCTAssertTrue(pipeline.contains("if isFluidFrontmost, shouldDeliverOutputs"))+ XCTAssertTrue(pipeline.contains("if outputRoute.publishesEditorResult"))+ XCTAssertTrue(pipeline.contains("shouldPersistOutputs: shouldDeliverOutputs"), "Recovery must not offer a retry that later pastes")+ XCTAssertTrue(pipeline.contains("!cancelledAtASRStop, wasRewriteMode"))+ XCTAssertTrue(pipeline.contains("!cancelledAtASRStop, wasCommandMode"))+ XCTAssertTrue(pipeline.contains("!cancelledAtASRStop, await self.routePromptTestResult"))+ XCTAssertTrue(pipeline.contains("!cancelledAtASRStop && route.deliversText && self.settings.spokenSendEnabled"))+ XCTAssertTrue(pipeline.contains("guard self.cancelledOutputLifecycleID != expectedOverlayLifecycleID else"))+ }++ func testCancelHistoryWiringSharesHandlerAndKeepsDisposableCapturesPrivate() throws {+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()+ let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)+ let callback = try XCTUnwrap(source.components(separatedBy: "self.hotkeyManager?.setCancelCallback {").last?.components(separatedBy: "// Re-insert").first)+ XCTAssertTrue(callback.contains("self.handleCancelShortcut()"))+ XCTAssertFalse(callback.contains("clearActiveRecordingMode()"), "Keep the selected style until the History pipeline snapshots it")+ let cancel = try XCTUnwrap(source.components(separatedBy: "private func handleCancelShortcut() -> Bool {").last?.components(separatedBy: "// MARK: - Model Management Helpers").first)+ XCTAssertTrue(cancel.contains("if self.isSavingCancelledRecording { return true }"))+ XCTAssertTrue(cancel.contains("self.settings.saveTranscriptionHistory"))+ XCTAssertTrue(cancel.contains("!self.asr.isDictionaryTrainingCaptureActive"))+ XCTAssertTrue(cancel.contains("!= .onboardingSandbox"))+ XCTAssertTrue(cancel.contains("!DictationPromptTestCoordinator.shared.isActive"))+ XCTAssertTrue(cancel.contains("stopAndProcessTranscription(route: .historyOnly)"))+ XCTAssertTrue(cancel.contains("self.isSavingCancelledRecording = false"))+ XCTAssertTrue(cancel.contains("manager?.traceStopUnlocked(since: stopLockStartedAt)"))+ XCTAssertTrue(cancel.contains("resetModifierOnlyShortcutTracking(reason: .cancel)"))+ XCTAssertTrue(cancel.contains("self.menuBarManager.beginProcessingCompletionAndHideOverlay()"))+ XCTAssertTrue(cancel.contains("self.spokenSendAutoStopTask?.cancel()"))+ XCTAssertTrue(cancel.contains("self.stopSpokenSendVoiceActivityMonitoring()"))+ }++ func testCancelledProcessingCannotPublishDelayedOverlayOrPracticeResult() throws {+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()+ let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)+ let status = try XCTUnwrap(source.components(separatedBy: "let onFinalTranscriptionStarted: @MainActor () -> Void = {").last?.components(separatedBy: "return (false, onFinalTranscriptionStarted)").first)+ XCTAssertTrue(status.contains("self.cancelledOutputLifecycleID != lifecycleID"))+ let prompt = try XCTUnwrap(source.components(separatedBy: "private func processDictationPromptTest(").last?.components(separatedBy: "private func routePromptTestResult(").first)+ XCTAssertTrue(prompt.contains("guard promptTest.acceptsResult(for: sessionID), self.cancelledOutputLifecycleID != lifecycleID"))+ let edit = try XCTUnwrap(source.components(separatedBy: "private func processRewriteWithVoiceInstruction(").last?.components(separatedBy: "private func setActiveRecordingMode(").first)+ XCTAssertTrue(edit.contains("guard self.cancelledOutputLifecycleID != lifecycleID else"))+ XCTAssertTrue(edit.contains("isOutputValid: { self.cancelledOutputLifecycleID != lifecycleID }"))+ }+func testReadinessWaitRespondsPromptlyToTaskCancellation() async {let gate = AudioCaptureReadinessGate()gate.arm(sessionID: 41, attemptID: 1)diff --git a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swiftindex 2355f350..9ceb5906 100644--- a/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift+++ b/Tests/FluidDictationIntegrationTests/HotkeyShortcutTests.swift@@ -1,3 +1,5 @@+// Event replay matrices share private helpers in this regression suite.+// swiftlint:disable file_lengthimport AppKitimport Combineimport CoreAudio@@ -6,6 +8,7 @@ import Foundationimport SwiftUIimport XCTest+// swiftlint:disable:next type_body_lengthfinal class HotkeyShortcutTests: XCTestCase {@MainActorfunc testOverlayAppearanceRejectsNonfiniteTransparency() {@@ -232,13 +235,17 @@ final class HotkeyShortcutTests: XCTestCase {defer { asr.isRunning = false }var starts = 0var stops = 0- let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {- starts += 1- asr.isRunning = true- }, onStop: {- stops += 1- asr.isRunning = false- })+ let manager = self.makePrimaryReleaseTestManager(+ asr: asr,+ onStart: {+ starts += 1+ asr.isRunning = true+ },+ onStop: {+ stops += 1+ asr.isRunning = false+ }+ )let down = try self.primaryReleaseTestEvent(type: .keyDown)let up = try self.primaryReleaseTestEvent(type: .keyUp, modifiers: [])@@ -669,13 +676,17 @@ final class HotkeyShortcutTests: XCTestCase {defer { asr.isRunning = false }var starts = 0var stops = 0- let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {- starts += 1- asr.isRunning = true- }, onStop: {- stops += 1- asr.isRunning = false- })+ let manager = self.makePrimaryReleaseTestManager(+ asr: asr,+ onStart: {+ starts += 1+ asr.isRunning = true+ },+ onStop: {+ stops += 1+ asr.isRunning = false+ }+ )let down = try self.primaryReleaseTestEvent(type: .keyDown)let up = try self.primaryReleaseTestEvent(type: .keyUp)for _ in 0..<2 {@@ -832,13 +843,20 @@ final class HotkeyShortcutTests: XCTestCase {let command = HotkeyShortcut(keyCode: 54, modifierFlags: [], modifierKeyCodes: [54])let option = HotkeyShortcut(keyCode: 61, modifierFlags: [], modifierKeyCodes: [61])let manager = GlobalHotkeyManager(- asrService: ASRService(), primaryShortcuts: [option], promptModeShortcut: command,- commandModeShortcut: command, rewriteModeShortcut: command,+ asrService: ASRService(),+ primaryShortcuts: [option],+ promptModeShortcut: command,+ commandModeShortcut: command,+ rewriteModeShortcut: command,promptShortcutAssignments: mode == .promptAssignment ? [(selection: SettingsStore.DictationPromptSelection.default, shortcut: command)] : [],- promptModeShortcutEnabled: mode == .promptMode, commandModeShortcutEnabled: mode == .commandMode,- rewriteModeShortcutEnabled: mode == .rewriteMode, dictationModeCallback: { starts += 1 },- promptModeCallback: { otherStarts += 1 }, promptSelectionCallback: { _ in otherStarts += 1 },- commandModeCallback: { otherStarts += 1 }, rewriteModeCallback: { otherStarts += 1 }+ promptModeShortcutEnabled: mode == .promptMode,+ commandModeShortcutEnabled: mode == .commandMode,+ rewriteModeShortcutEnabled: mode == .rewriteMode,+ dictationModeCallback: { starts += 1 },+ promptModeCallback: { otherStarts += 1 },+ promptSelectionCallback: { _ in otherStarts += 1 },+ commandModeCallback: { otherStarts += 1 },+ rewriteModeCallback: { otherStarts += 1 })manager.setHotkeyMode(.toggle)_ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: 54, modifiers: .maskCommand))@@ -1001,13 +1019,19 @@ final class HotkeyShortcutTests: XCTestCase {let old = HotkeyShortcut(keyCode: 54, modifierFlags: [], modifierKeyCodes: [54])let new = HotkeyShortcut(keyCode: 60, modifierFlags: [], modifierKeyCodes: [60])let manager = GlobalHotkeyManager(- asrService: ASRService(), primaryShortcuts: [], promptModeShortcut: old,- commandModeShortcut: old, rewriteModeShortcut: old,+ asrService: ASRService(),+ primaryShortcuts: [],+ promptModeShortcut: old,+ commandModeShortcut: old,+ rewriteModeShortcut: old,promptShortcutAssignments: mode == .promptAssignment ? [(selection: .default, shortcut: old)] : [],- promptModeShortcutEnabled: mode == .promptMode, commandModeShortcutEnabled: mode == .commandMode,+ promptModeShortcutEnabled: mode == .promptMode,+ commandModeShortcutEnabled: mode == .commandMode,rewriteModeShortcutEnabled: mode == .rewriteMode,- promptModeCallback: { starts += 1 }, promptSelectionCallback: { _ in starts += 1 },- commandModeCallback: { starts += 1 }, rewriteModeCallback: { starts += 1 }+ promptModeCallback: { starts += 1 },+ promptSelectionCallback: { _ in starts += 1 },+ commandModeCallback: { starts += 1 },+ rewriteModeCallback: { starts += 1 })manager.setHotkeyMode(.toggle)_ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: 54, modifiers: .maskCommand))@@ -1057,13 +1081,21 @@ final class HotkeyShortcutTests: XCTestCase {var starts = 0let bare = HotkeyShortcut(keyCode: 31, modifierFlags: [])let manager = GlobalHotkeyManager(- asrService: ASRService(), primaryShortcuts: mode == .transcription ? [bare] : [],- promptModeShortcut: bare, commandModeShortcut: bare, rewriteModeShortcut: bare,+ asrService: ASRService(),+ primaryShortcuts: mode == .transcription ? [bare] : [],+ promptModeShortcut: bare,+ commandModeShortcut: bare,+ rewriteModeShortcut: bare,promptShortcutAssignments: mode == .promptAssignment ? [(selection: .default, shortcut: bare)] : [],- promptModeShortcutEnabled: mode == .promptMode, commandModeShortcutEnabled: mode == .commandMode,- rewriteModeShortcutEnabled: mode == .rewriteMode, startRecordingCallback: { starts += 1 },- dictationModeCallback: { starts += 1 }, promptModeCallback: { starts += 1 },- promptSelectionCallback: { _ in starts += 1 }, commandModeCallback: { starts += 1 }, rewriteModeCallback: { starts += 1 }+ promptModeShortcutEnabled: mode == .promptMode,+ commandModeShortcutEnabled: mode == .commandMode,+ rewriteModeShortcutEnabled: mode == .rewriteMode,+ startRecordingCallback: { starts += 1 },+ dictationModeCallback: { starts += 1 },+ promptModeCallback: { starts += 1 },+ promptSelectionCallback: { _ in starts += 1 },+ commandModeCallback: { starts += 1 },+ rewriteModeCallback: { starts += 1 })manager.setHotkeyMode(activation)let down = try self.primaryReleaseTestEvent(type: .keyDown, keyCode: 31, modifiers: [])@@ -1080,7 +1112,18 @@ final class HotkeyShortcutTests: XCTestCase {@MainActorfunc testIssue556SavedBareTypingBindingsAreOffWithoutChangingModelsOrCancel() throws {- try self.withRestoredDefaults(keys: [self.primaryDictationShortcutsKey, self.legacyHotkeyShortcutKey, "DictationPromptConfigurations", "PromptModeHotkeyShortcut", "PromptModeShortcutEnabled", "CommandModeHotkeyShortcut", "CommandModeShortcutEnabled", "RewriteModeHotkeyShortcut", "RewriteModeShortcutEnabled", "CancelRecordingHotkeyShortcut"]) {+ try self.withRestoredDefaults(keys: [+ self.primaryDictationShortcutsKey,+ self.legacyHotkeyShortcutKey,+ "DictationPromptConfigurations",+ "PromptModeHotkeyShortcut",+ "PromptModeShortcutEnabled",+ "CommandModeHotkeyShortcut",+ "CommandModeShortcutEnabled",+ "RewriteModeHotkeyShortcut",+ "RewriteModeShortcutEnabled",+ "CancelRecordingHotkeyShortcut",+ ]) {let settings = SettingsStore.sharedlet bare = HotkeyShortcut(keyCode: 31, modifierFlags: [])let data = try JSONEncoder().encode(bare)@@ -1149,7 +1192,13 @@ final class HotkeyShortcutTests: XCTestCase {await Task.yield()}XCTAssertEqual(starts, 0)- let allowed = [HotkeyShortcut(keyCode: 50, modifierFlags: []), HotkeyShortcut(keyCode: 43, modifierFlags: []), HotkeyShortcut(keyCode: 47, modifierFlags: []), HotkeyShortcut(keyCode: 36, modifierFlags: .control), HotkeyShortcut(keyCode: 53, modifierFlags: .control)]+ let allowed = [+ HotkeyShortcut(keyCode: 50, modifierFlags: []),+ HotkeyShortcut(keyCode: 43, modifierFlags: []),+ HotkeyShortcut(keyCode: 47, modifierFlags: []),+ HotkeyShortcut(keyCode: 36, modifierFlags: .control),+ HotkeyShortcut(keyCode: 53, modifierFlags: .control),+ ]for shortcut in allowed {manager.updatePrimaryShortcuts([shortcut])let flags: CGEventFlags = shortcut.modifierFlags.isEmpty ? [] : .maskControl@@ -1169,7 +1218,17 @@ final class HotkeyShortcutTests: XCTestCase {@MainActorfunc testSavedPunctuationAndModifiedBindingsStayEnabled() throws {- try self.withRestoredDefaults(keys: [self.primaryDictationShortcutsKey, self.legacyHotkeyShortcutKey, "DictationPromptConfigurations", "PromptModeHotkeyShortcut", "PromptModeShortcutEnabled", "CommandModeHotkeyShortcut", "CommandModeShortcutEnabled", "RewriteModeHotkeyShortcut", "RewriteModeShortcutEnabled"]) {+ try self.withRestoredDefaults(keys: [+ self.primaryDictationShortcutsKey,+ self.legacyHotkeyShortcutKey,+ "DictationPromptConfigurations",+ "PromptModeHotkeyShortcut",+ "PromptModeShortcutEnabled",+ "CommandModeHotkeyShortcut",+ "CommandModeShortcutEnabled",+ "RewriteModeHotkeyShortcut",+ "RewriteModeShortcutEnabled",+ ]) {let settings = SettingsStore.sharedfor shortcut in [HotkeyShortcut(keyCode: 50, modifierFlags: []), HotkeyShortcut(keyCode: 2, modifierFlags: [.control, .command]), HotkeyShortcut(keyCode: 61, modifierFlags: [])] {settings.primaryDictationShortcuts = [HotkeyShortcut(keyCode: 3, modifierFlags: []), shortcut]@@ -1196,10 +1255,15 @@ final class HotkeyShortcutTests: XCTestCase {let command = HotkeyShortcut(keyCode: 54, modifierFlags: [], modifierKeyCodes: [54])let shift = HotkeyShortcut(keyCode: 60, modifierFlags: [], modifierKeyCodes: [60])let manager = GlobalHotkeyManager(- asrService: ASRService(), primaryShortcuts: [], promptModeShortcut: shift,- commandModeShortcut: nil, rewriteModeShortcut: shift,+ asrService: ASRService(),+ primaryShortcuts: [],+ promptModeShortcut: shift,+ commandModeShortcut: nil,+ rewriteModeShortcut: shift,promptShortcutAssignments: [(selection: .default, shortcut: command), (selection: .privateAI, shortcut: shift)],- promptModeShortcutEnabled: false, commandModeShortcutEnabled: false, rewriteModeShortcutEnabled: false,+ promptModeShortcutEnabled: false,+ commandModeShortcutEnabled: false,+ rewriteModeShortcutEnabled: false,promptSelectionCallback: { selections.append($0) })manager.setHotkeyMode(.toggle)@@ -1241,12 +1305,18 @@ final class HotkeyShortcutTests: XCTestCase {var stops = 0let shortcut = HotkeyShortcut(keyCode: 55, modifierFlags: [], modifierKeyCodes: [55])let manager = GlobalHotkeyManager(- asrService: asr, primaryShortcuts: [shortcut], promptModeShortcut: shortcut,- commandModeShortcut: nil, rewriteModeShortcut: shortcut,- promptModeShortcutEnabled: false, commandModeShortcutEnabled: false, rewriteModeShortcutEnabled: false,+ asrService: asr,+ primaryShortcuts: [shortcut],+ promptModeShortcut: shortcut,+ commandModeShortcut: nil,+ rewriteModeShortcut: shortcut,+ promptModeShortcutEnabled: false,+ commandModeShortcutEnabled: false,+ rewriteModeShortcutEnabled: false,startRecordingCallback: { starts += 1; asr.isRunning = true },dictationModeCallback: { starts += 1; asr.isRunning = true },- stopAndProcessCallback: { _ in stops += 1 }, isDictateRecordingProvider: { isDictate }+ stopAndProcessCallback: { _ in stops += 1 },+ isDictateRecordingProvider: { isDictate })manager.setHotkeyMode(.hold)_ = try manager.handleKeyEvent(type: .flagsChanged, event: self.primaryReleaseTestEvent(type: .flagsChanged, keyCode: 55, modifiers: .maskCommand))@@ -1377,11 +1447,18 @@ final class HotkeyShortcutTests: XCTestCase {var stops = 0let shortcut = HotkeyShortcut(keyCode: 2, modifierFlags: [.control, .command])let manager = GlobalHotkeyManager(- asrService: asr, primaryShortcuts: [shortcut], promptModeShortcut: shortcut,- commandModeShortcut: nil, rewriteModeShortcut: shortcut,- promptModeShortcutEnabled: false, commandModeShortcutEnabled: false, rewriteModeShortcutEnabled: false,- startRecordingCallback: { asr.isRunning = true }, dictationModeCallback: { asr.isRunning = true },- stopAndProcessCallback: { _ in stops += 1; asr.isRunning = false }, isDictateRecordingProvider: { isDictate }+ asrService: asr,+ primaryShortcuts: [shortcut],+ promptModeShortcut: shortcut,+ commandModeShortcut: nil,+ rewriteModeShortcut: shortcut,+ promptModeShortcutEnabled: false,+ commandModeShortcutEnabled: false,+ rewriteModeShortcutEnabled: false,+ startRecordingCallback: { asr.isRunning = true },+ dictationModeCallback: { asr.isRunning = true },+ stopAndProcessCallback: { _ in stops += 1; asr.isRunning = false },+ isDictateRecordingProvider: { isDictate })manager.setHotkeyMode(.hold)_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))@@ -1403,10 +1480,14 @@ final class HotkeyShortcutTests: XCTestCase {defer { asr.isRunning = false }var starts = 0var stops = 0- let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {- starts += 1- await Task { @MainActor in asr.isRunning = true }.value- }, onStop: { stops += 1; asr.isRunning = false })+ let manager = self.makePrimaryReleaseTestManager(+ asr: asr,+ onStart: {+ starts += 1+ await Task { @MainActor in asr.isRunning = true }.value+ },+ onStop: { stops += 1; asr.isRunning = false }+ )for _ in 0..<2 {_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))_ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))@@ -1494,12 +1575,18 @@ final class HotkeyShortcutTests: XCTestCase {let first = HotkeyShortcut(keyCode: 2, modifierFlags: .control)let second = HotkeyShortcut(keyCode: 3, modifierFlags: .control)let manager = GlobalHotkeyManager(- asrService: asr, primaryShortcuts: [], promptModeShortcut: first,- commandModeShortcut: nil, rewriteModeShortcut: first,+ asrService: asr,+ primaryShortcuts: [],+ promptModeShortcut: first,+ commandModeShortcut: nil,+ rewriteModeShortcut: first,promptShortcutAssignments: [(selection: .default, shortcut: first), (selection: .privateAI, shortcut: second)],- promptModeShortcutEnabled: false, commandModeShortcutEnabled: false, rewriteModeShortcutEnabled: false,+ promptModeShortcutEnabled: false,+ commandModeShortcutEnabled: false,+ rewriteModeShortcutEnabled: false,stopAndProcessCallback: { _ in stops += 1; asr.isRunning = false },- promptSelectionCallback: { _ in starts += 1; asr.isRunning = true }, isPromptModeRecordingProvider: { true }+ promptSelectionCallback: { _ in starts += 1; asr.isRunning = true },+ isPromptModeRecordingProvider: { true })manager.setHotkeyMode(.hold)_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 2, modifiers: .maskControl))@@ -1530,19 +1617,23 @@ final class HotkeyShortcutTests: XCTestCase {asr.isRunning = initiallyRunningvar starts = 0var stops = 0- let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {- starts += 1- await Task { @MainActor in- await Task.yield()- asr.isRunning = true- }.value- }, onStop: {- stops += 1- await Task { @MainActor in- await Task.yield()- asr.isRunning = false- }.value- })+ let manager = self.makePrimaryReleaseTestManager(+ asr: asr,+ onStart: {+ starts += 1+ await Task { @MainActor in+ await Task.yield()+ asr.isRunning = true+ }.value+ },+ onStop: {+ stops += 1+ await Task { @MainActor in+ await Task.yield()+ asr.isRunning = false+ }.value+ }+ )for _ in 0..<taps {_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))_ = try manager.handleKeyEvent(type: .keyUp, event: self.primaryReleaseTestEvent(type: .keyUp))@@ -1621,10 +1712,15 @@ final class HotkeyShortcutTests: XCTestCase {let shortcut = HotkeyShortcut(keyCode: 2, modifierFlags: .control)var selections: [SettingsStore.DictationPromptSelection] = []let manager = GlobalHotkeyManager(- asrService: ASRService(), primaryShortcuts: [], promptModeShortcut: shortcut,- commandModeShortcut: nil, rewriteModeShortcut: shortcut,+ asrService: ASRService(),+ primaryShortcuts: [],+ promptModeShortcut: shortcut,+ commandModeShortcut: nil,+ rewriteModeShortcut: shortcut,promptShortcutAssignments: [(selection: .default, shortcut: shortcut)],- promptModeShortcutEnabled: false, commandModeShortcutEnabled: false, rewriteModeShortcutEnabled: false,+ promptModeShortcutEnabled: false,+ commandModeShortcutEnabled: false,+ rewriteModeShortcutEnabled: false,promptSelectionCallback: { selections.append($0) })_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, modifiers: .maskControl))@@ -1649,14 +1745,20 @@ final class HotkeyShortcutTests: XCTestCase {var starts = 0var stops = 0let manager = GlobalHotkeyManager(- asrService: asr, primaryShortcuts: style ? [] : [keyboard, modifier], promptModeShortcut: keyboard,- commandModeShortcut: nil, rewriteModeShortcut: keyboard,+ asrService: asr,+ primaryShortcuts: style ? [] : [keyboard, modifier],+ promptModeShortcut: keyboard,+ commandModeShortcut: nil,+ rewriteModeShortcut: keyboard,promptShortcutAssignments: style ? [(selection: .default, shortcut: keyboard), (selection: .privateAI, shortcut: modifier)] : [],- promptModeShortcutEnabled: false, commandModeShortcutEnabled: false, rewriteModeShortcutEnabled: false,+ promptModeShortcutEnabled: false,+ commandModeShortcutEnabled: false,+ rewriteModeShortcutEnabled: false,startRecordingCallback: { starts += 1; asr.isRunning = true },stopAndProcessCallback: { _ in stops += 1; asr.isRunning = false },promptSelectionCallback: { _ in starts += 1; asr.isRunning = true },- isDictateRecordingProvider: { !style }, isPromptModeRecordingProvider: { style }+ isDictateRecordingProvider: { !style },+ isPromptModeRecordingProvider: { style })manager.setHotkeyMode(.hold)_ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, modifiers: .maskControl))@@ -1745,6 +1847,107 @@ final class HotkeyShortcutTests: XCTestCase {}}+ @MainActor+ func testCancelledOutputPolicySavesHistoryWithoutEditorOrDelivery() {+ let route = ContentView.DictationOutputRoute.historyOnly+ XCTAssertTrue(route.savesHistory)+ XCTAssertFalse(route.deliversText)+ XCTAssertFalse(route.publishesEditorResult)+ }++ @MainActor+ func testNormalAndPracticeOutputPoliciesStayUnchanged() {+ let normal = ContentView.DictationOutputRoute.normal+ XCTAssertTrue(normal.savesHistory)+ XCTAssertTrue(normal.deliversText)+ XCTAssertTrue(normal.publishesEditorResult)+ let practice = ContentView.DictationOutputRoute.onboardingSandbox+ XCTAssertFalse(practice.savesHistory)+ XCTAssertFalse(practice.deliversText)+ XCTAssertTrue(practice.publishesEditorResult)+ }++ @MainActor+ func testCancelCallbackOwnsAudioBeforeDiscardFallback() async throws {+ let asr = ASRService()+ asr.isRunning = true+ defer { asr.isRunning = false }+ var cancellations = 0+ let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {})+ manager.setCancelCallback { cancellations += 1; return true }+ let result = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: []))+ XCTAssertNil(result)+ for _ in 0..<20 {+ await Task.yield()+ }+ XCTAssertEqual(cancellations, 1)+ XCTAssertTrue(asr.isRunning, "The application must own stop/transcription; fallback must not discard its audio")+ }++ @MainActor+ func testCancelClearsHeldOwnerWithoutStoppingApplicationRecovery() async throws {+ let asr = ASRService()+ defer { asr.isRunning = false }+ var starts = 0+ var stops = 0+ let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: { starts += 1; asr.isRunning = true }, onStop: { stops += 1; asr.isRunning = false })+ manager.setHotkeyMode(.hold)+ manager.setCancelCallback { true }+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))+ for _ in 0..<20 {+ await Task.yield()+ }+ XCTAssertTrue(asr.isRunning)+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: []))+ let releaseEvent = try self.primaryReleaseTestEvent(type: .keyUp, modifiers: [])+ let released = manager.handleKeyEvent(type: .keyUp, event: releaseEvent)+ withExtendedLifetime(releaseEvent) {+ XCTAssertNotNil(released, "Escape invalidates the old held owner")+ }+ for _ in 0..<20 {+ await Task.yield()+ }+ XCTAssertEqual(stops, 0)+ XCTAssertTrue(asr.isRunning, "The application-owned recovery must retain audio until transcription takes it")+ asr.isRunning = false // Recovery finishes; the next real shortcut must still work.+ _ = try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown))+ for _ in 0..<20 {+ await Task.yield()+ }+ XCTAssertEqual(starts, 2)+ }++ @MainActor+ func testRepeatedCancelDoesNotInvokeDiscardWhileRecoveryIsPending() async throws {+ let asr = ASRService()+ asr.isRunning = true+ defer { asr.isRunning = false }+ var recoveryQueued = false+ var saves = 0+ let manager = self.makePrimaryReleaseTestManager(asr: asr, onStart: {})+ manager.setCancelCallback {+ if !recoveryQueued { recoveryQueued = true; saves += 1 }+ return true+ }+ for _ in 0..<5 {+ XCTAssertNil(try manager.handleKeyEvent(type: .keyDown, event: self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: [])))+ }+ for _ in 0..<20 {+ await Task.yield()+ }+ XCTAssertEqual(saves, 1)+ XCTAssertTrue(asr.isRunning)+ }++ @MainActor+ func testIdleCancelPassesThroughWhenApplicationHasNothingToHandle() throws {+ let manager = self.makePrimaryReleaseTestManager(asr: ASRService(), onStart: {})+ manager.setCancelCallback { false }+ let event = try self.primaryReleaseTestEvent(type: .keyDown, keyCode: 53, modifiers: [])+ let result = manager.handleKeyEvent(type: .keyDown, event: event)+ withExtendedLifetime(event) { XCTAssertNotNil(result) }+ }+@MainActorprivate func makePrimaryReleaseTestManager(asr: ASRService,diff --git a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swiftindex 4331f562..4e26e6ce 100644--- a/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift+++ b/Tests/FluidDictationIntegrationTests/PasteDeliveryCoordinatorTests.swift@@ -5,6 +5,95 @@ import XCTest@MainActorfinal class PasteDeliveryCoordinatorTests: XCTestCase {+ func testCancelledFocusPreparationDoesNotCopyBackup() async {+ let pasteboard = FakePasteboardManager(text: "before")+ let poster = FakePasteCommandPoster()+ let coordinator = PasteDeliveryCoordinator(pasteboard: pasteboard, commandPoster: poster, settlementDelayNanoseconds: .max)+ var valid = true+ var resumeFocus: CheckedContinuation<Bool, Never>?+ let preparation = Task { @MainActor in+ await coordinator.prepareForDelivery("cancelled", preserveTranscriptOnClipboard: true, isOutputValid: { valid }) {+ await withCheckedContinuation { resumeFocus = $0 }+ }+ }+ await self.waitUntil { resumeFocus != nil }+ valid = false+ resumeFocus?.resume(returning: false)+ let ready = await preparation.value+ XCTAssertFalse(ready)+ XCTAssertEqual(pasteboard.text, "before")+ XCTAssertEqual(pasteboard.intentionalWriteCount, 0)+ XCTAssertEqual(poster.postCount, 0)+ let next = await coordinator.deliver("next", preserveTranscriptOnClipboard: false)+ XCTAssertEqual(next, .commandPosted)+ coordinator.runPendingSettlementForTesting()+ XCTAssertEqual(pasteboard.text, "before")+ }++ func testCancelledQueuedBackupDoesNotWriteAndReleasesSlot() async {+ let pasteboard = FakePasteboardManager(text: "before")+ let poster = FakePasteCommandPoster()+ let coordinator = PasteDeliveryCoordinator(pasteboard: pasteboard, commandPoster: poster, settlementDelayNanoseconds: .max)+ _ = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)+ var valid = true+ var queued = false+ let backup = Task { @MainActor in+ queued = true+ return await coordinator.copyBackup("cancelled", enabled: true, isOutputValid: { valid })+ }+ await self.waitUntil { queued }+ valid = false+ coordinator.runPendingSettlementForTesting()+ let copied = await backup.value+ XCTAssertFalse(copied)+ XCTAssertEqual(pasteboard.text, "before")+ XCTAssertEqual(pasteboard.intentionalWriteCount, 0)+ XCTAssertEqual(pasteboard.temporaryWriteCount, 1)+ let next = await coordinator.deliver("next", preserveTranscriptOnClipboard: false)+ XCTAssertEqual(next, .commandPosted)+ XCTAssertEqual(poster.postCount, 2)+ coordinator.runPendingSettlementForTesting()+ }++ func testCancelledQueuedPasteDoesNotWriteOrPostAndNextDeliveryWorks() async {+ let pasteboard = FakePasteboardManager(text: "before")+ let poster = FakePasteCommandPoster()+ let coordinator = PasteDeliveryCoordinator(pasteboard: pasteboard, commandPoster: poster, settlementDelayNanoseconds: .max)+ _ = await coordinator.deliver("first", preserveTranscriptOnClipboard: false)+ var valid = true+ var queued = false+ let delivery = Task { @MainActor in+ queued = true+ return await coordinator.deliver("cancelled", preserveTranscriptOnClipboard: true, isOutputValid: { valid })+ }+ await self.waitUntil { queued }+ valid = false+ coordinator.runPendingSettlementForTesting()+ let result = await delivery.value+ XCTAssertEqual(result, .cancelled)+ XCTAssertEqual(pasteboard.text, "before")+ XCTAssertEqual(pasteboard.temporaryWriteCount, 1)+ XCTAssertEqual(pasteboard.intentionalWriteCount, 0)+ XCTAssertEqual(poster.postCount, 1)+ let next = await coordinator.deliver("next", preserveTranscriptOnClipboard: false)+ XCTAssertEqual(next, .commandPosted)+ XCTAssertEqual(poster.postCount, 2)+ coordinator.runPendingSettlementForTesting()+ }++ func testCancelledPostedPasteRestoresInsteadOfKeepingTranscript() async {+ let pasteboard = FakePasteboardManager(text: "before")+ let coordinator = PasteDeliveryCoordinator(pasteboard: pasteboard, commandPoster: FakePasteCommandPoster(), settlementDelayNanoseconds: .max)+ var valid = true+ let result = await coordinator.deliver("posted", preserveTranscriptOnClipboard: true, isOutputValid: { valid })+ XCTAssertEqual(result, .commandPosted)+ valid = false+ coordinator.runPendingSettlementForTesting()+ XCTAssertEqual(pasteboard.text, "before")+ XCTAssertEqual(pasteboard.intentionalWriteCount, 0)+ XCTAssertEqual(pasteboard.restoreCount, 1)+ }+func testPasteCheckAlertsDefaultOffAndRoundTripThroughBackup() {let settings = SettingsStore.sharedlet original = settings.showPasteCheckAlerts