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
fix Escape cancellation for voice Edit and Command
altic-deva6313761d42d
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 76e55035..3b6c66be 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -275,7 +275,7 @@ struct ContentView: View {@State private var hotkeyManager: GlobalHotkeyManager? = nil@State private var hotkeyManagerInitialized: Bool = false@State private var processingDictationLifecycleID: UInt64?- @State private var processingAllowsHistoryCancellation = false+ @State private var pendingVoiceCommandLifecycleID: UInt64?@State private var cancelledOutputLifecycleID: UInt64?@State private var isSavingCancelledRecording = false@@ -2927,12 +2927,9 @@ struct ContentView: View {guard self.processingDictationLifecycleID == nil else { return }let outputLifecycleID = self.overlayLifecycleIDself.processingDictationLifecycleID = outputLifecycleID- self.processingAllowsHistoryCancellation = self.activeRecordingMode != .edit && self.activeRecordingMode != .command- && !self.isRecordingForRewrite && !self.isRecordingForCommanddefer {if self.processingDictationLifecycleID == outputLifecycleID {self.processingDictationLifecycleID = nil- self.processingAllowsHistoryCancellation = false}}var closeTrace = OverlayCloseTrace("content.stopCallback")@@ -3055,6 +3052,10 @@ struct ContentView: View {// If this was a rewrite recording, process the rewrite instead of typingif wasRewriteMode {+ guard !cancelledAtASRStop else {+ self.rewriteModeService.clearState()+ return+ }DebugLogger.shared.info("Processing rewrite with instruction: \(transcribedText)", source: "ContentView")AnalyticsService.shared.recordModelUsage(role: .transcription,@@ -3062,19 +3063,20 @@ struct ContentView: View {descriptor: self.settings.selectedSpeechModel.analyticsDescriptor)let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()- await self.processRewriteWithVoiceInstruction(transcribedText, appInfo: appInfo)+ await self.processRewriteWithVoiceInstruction(transcribedText, appInfo: appInfo, lifecycleID: expectedOverlayLifecycleID)return}// If this was a command recording, process the commandif wasCommandMode {+ guard !cancelledAtASRStop else { return }DebugLogger.shared.info("Processing command: \(transcribedText)", source: "ContentView")AnalyticsService.shared.recordModelUsage(role: .transcription,mode: .command,descriptor: self.settings.selectedSpeechModel.analyticsDescriptor)- await self.processCommandWithVoice(transcribedText)+ await self.processCommandWithVoice(transcribedText, lifecycleID: expectedOverlayLifecycleID)return}@@ -4385,8 +4387,14 @@ 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 {+ let isOutputValid: @MainActor () -> Bool = { self.overlayLifecycleID == lifecycleID && self.cancelledOutputLifecycleID != lifecycleID }+ guard isOutputValid() else { return }+ defer {+ if !isOutputValid() { self.rewriteModeService.clearState() }+ }self.rewriteModeService.setPromptAppBundleID(appInfo.bundleId)let hasOriginalText = !self.rewriteModeService.originalText.isEmptyDebugLogger.shared.info(@@ -4401,6 +4409,7 @@ struct ContentView: View {// - With originalText: rewrites existing text based on instruction// - Without originalText: improves/refines the spoken textawait self.rewriteModeService.processRewriteRequest(instruction)+ guard isOutputValid() else { return }// If rewrite was successful, type the resultif !self.rewriteModeService.rewrittenText.isEmpty {@@ -4409,7 +4418,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: isOutputValid) else {+ guard isOutputValid() else { return }self.showTextDeliveryFailure(.targetRestoreFailed,transcript: self.rewriteModeService.rewrittenText@@ -4420,8 +4430,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: isOutputValid)+ guard isOutputValid() else { return }if case let .recoverableFailure(failure) = deliveryResult {self.showTextDeliveryFailure(failure, transcript: self.rewriteModeService.rewrittenText)return@@ -4520,7 +4532,9 @@ struct ContentView: View {// MARK: - Command Mode Voice Processing- private func processCommandWithVoice(_ command: String) async {+ private func processCommandWithVoice(_ command: String, lifecycleID: UInt64) async {+ let isOutputValid: @MainActor () -> Bool = { self.overlayLifecycleID == lifecycleID && self.cancelledOutputLifecycleID != lifecycleID }+ guard isOutputValid() else { return }DebugLogger.shared.info("Processing voice command: '\(command)'", source: "ContentView")// Show processing animation@@ -4528,7 +4542,9 @@ struct ContentView: View {// Process the command through CommandModeService// This stores the conversation history and executes any terminal commands- await self.commandModeService.processUserCommand(command, notifyInvalidRequest: true)+ await self.commandModeService.processUserCommand(command, notifyInvalidRequest: true, isOutputValid: isOutputValid)+ guard isOutputValid() else { return }+ self.pendingVoiceCommandLifecycleID = self.commandModeService.pendingCommand == nil ? nil : lifecycleID// Hide processing animationself.menuBarManager.setProcessing(false)@@ -5039,12 +5055,16 @@ struct ContentView: View {handled = true}+ if let lifecycleID = self.pendingVoiceCommandLifecycleID {+ self.cancelledOutputLifecycleID = lifecycleID+ self.pendingVoiceCommandLifecycleID = nil+ handled = self.commandModeService.cancelInvalidPendingCommand() || handled+ }+if let lifecycleID = self.processingDictationLifecycleID {// A stop already owns the audio; suppress its pending output without stopping again.- if self.processingAllowsHistoryCancellation {- self.cancelledOutputLifecycleID = lifecycleID- handled = true- }+ self.cancelledOutputLifecycleID = lifecycleID+ handled = true} else if self.asr.isRunningOrStarting {let preservesHistory = self.settings.saveTranscriptionHistory && self.asr.isRunning && !self.asr.isDictionaryTrainingCaptureActive&& (self.activeRecordingMode == .dictate || self.activeRecordingMode == .promptMode)@@ -5071,6 +5091,9 @@ struct ContentView: View {AnalyticsService.shared.recordOnboardingTryoutAttemptResult(outcome: .cancelled)}}+ if self.activeRecordingMode == .edit || self.isRecordingForRewrite {+ self.rewriteModeService.clearState()+ }self.clearActiveRecordingMode()}self.cancelPrewarmDictationIfNeeded()diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swiftindex 055a310b..6e0e8c4f 100644--- a/Sources/Fluid/Services/CommandModeService.swift+++ b/Sources/Fluid/Services/CommandModeService.swift@@ -13,6 +13,7 @@ final class CommandModeService: ObservableObject {private let terminalService = TerminalService()private let chatStore = ChatHistoryStore.shared+ private var pendingVoiceCommandCancellation: (commandID: String, requestStartIndex: Int, isOutputValid: @MainActor () -> Bool)?private var currentTurnCount = 0private let maxTurns = 20@@ -115,6 +116,7 @@ final class CommandModeService: ObservableObject {func clearHistory() {self.conversationHistory.removeAll()self.pendingCommand = nil+ self.pendingVoiceCommandCancellation = nilself.currentTurnCount = 0// Clear in store as well@@ -228,6 +230,7 @@ final class CommandModeService: ObservableObject {private func resetChatTransientState() {self.pendingCommand = nil+ self.pendingVoiceCommandCancellation = nilself.currentTurnCount = 0self.currentStep = nilself.streamingText = ""@@ -358,7 +361,11 @@ final class CommandModeService: ObservableObject {}/// Process user voice/text command- func processUserCommand(_ text: String, notifyInvalidRequest: Bool = false) async {+ func processUserCommand(_ text: String, notifyInvalidRequest: Bool = false, isOutputValid: (@MainActor () -> Bool)? = nil) async {+ let voiceOutputValidity = isOutputValid+ let isOutputValid: @MainActor () -> Bool = voiceOutputValidity ?? { true }+ guard isOutputValid(), !self.isProcessing, self.pendingCommand == nil else { return }+ self.pendingVoiceCommandCancellation = nilguard let summaryActivity = MeetingSummaryActivityCoordinator.shared.beginProcessing() else {MeetingSummaryActivityCoordinator.presentBusyError()return@@ -372,7 +379,20 @@ final class CommandModeService: ObservableObject {aiModel: SettingsStore.shared.analyticsAIModelDescriptor(for: .command))+ let requestStartIndex = self.conversationHistory.countself.isProcessing = true+ defer {+ if !isOutputValid() {+ self.discardUndispatchedMessages(from: requestStartIndex)+ self.saveCurrentChat()+ self.isProcessing = false+ self.resetChatTransientState()+ if self.shouldSyncCommandNotchState {+ NotchContentState.shared.setCommandProcessing(false)+ NotchContentState.shared.updateCommandStreamingText("")+ }+ }+ }self.currentTurnCount = 0self.conversationHistory.append(Message(role: .user, content: text))@@ -385,11 +405,16 @@ final class CommandModeService: ObservableObject {NotchContentState.shared.setCommandProcessing(true)}- await self.processNextTurn(notifyInvalidRequest: notifyInvalidRequest)+ await self.processNextTurn(notifyInvalidRequest: notifyInvalidRequest, isOutputValid: isOutputValid)+ if isOutputValid(), let pending = self.pendingCommand, let voiceOutputValidity {+ self.pendingVoiceCommandCancellation = (pending.id, requestStartIndex, voiceOutputValidity)+ }}/// Process follow-up command from notch inputfunc processFollowUpCommand(_ text: String) async {+ guard !self.isProcessing, self.pendingCommand == nil else { return }+ self.pendingVoiceCommandCancellation = nilguard let summaryActivity = MeetingSummaryActivityCoordinator.shared.beginProcessing() else {MeetingSummaryActivityCoordinator.presentBusyError()return@@ -422,6 +447,8 @@ final class CommandModeService: ObservableObject {/// Execute pending command (after user confirmation)func confirmAndExecute() async {+ guard !self.isProcessing else { return }+ guard !self.cancelInvalidPendingCommand() else { return }guard let summaryActivity = MeetingSummaryActivityCoordinator.shared.beginProcessing() else {MeetingSummaryActivityCoordinator.presentBusyError()return@@ -430,6 +457,7 @@ final class CommandModeService: ObservableObject {guard let pending = pendingCommand else { return }self.pendingCommand = nil+ self.pendingVoiceCommandCancellation = nilself.isProcessing = trueawait self.executeCommand(pending.command, workingDirectory: pending.workingDirectory, callId: pending.id)@@ -438,6 +466,7 @@ final class CommandModeService: ObservableObject {/// Cancel pending commandfunc cancelPendingCommand() {self.pendingCommand = nil+ self.pendingVoiceCommandCancellation = nilself.conversationHistory.append(Message(role: .assistant,content: "Command cancelled.",@@ -447,9 +476,38 @@ final class CommandModeService: ObservableObject {self.currentStep = nil}+ /// Escape invalidates the voice owner before canceling its deferred confirmation.+ @discardableResult+ func cancelInvalidPendingCommand() -> Bool {+ guard !self.isProcessing,+ let cancellation = self.pendingVoiceCommandCancellation,+ self.pendingCommand?.id == cancellation.commandID,+ !cancellation.isOutputValid() else { return false }+ self.discardUndispatchedMessages(from: cancellation.requestStartIndex)+ self.saveCurrentChat()+ self.resetChatTransientState()+ if self.shouldSyncCommandNotchState {+ NotchContentState.shared.setCommandProcessing(false)+ NotchContentState.shared.updateCommandStreamingText("")+ }+ return true+ }++ private func discardUndispatchedMessages(from requestStartIndex: Int) {+ guard requestStartIndex < self.conversationHistory.count else { return }+ // Actual terminal completions remain paired with their tool calls. Remove+ // the undispatched tail, including a later deferred destructive command.+ let lastCompletion = self.conversationHistory[requestStartIndex...].lastIndex(where: { $0.role == .tool })+ let discardStart = lastCompletion.map { $0 + 1 } ?? requestStartIndex+ guard discardStart < self.conversationHistory.count else { return }+ self.conversationHistory.removeSubrange(discardStart...)+ self.syncToNotchState()+ }+// MARK: - Agent Loop- private func processNextTurn(notifyInvalidRequest: Bool = false) async {+ private func processNextTurn(notifyInvalidRequest: Bool = false, isOutputValid: @escaping @MainActor () -> Bool = { true }) async {+ guard isOutputValid() else { return }if self.currentTurnCount >= self.maxTurns {let errorMsg = "Reached maximum steps limit. Please review the progress and continue if needed."self.conversationHistory.append(Message(@@ -481,7 +539,8 @@ final class CommandModeService: ObservableObject {}do {- let response = try await callLLM()+ let response = try await callLLM(isOutputValid: isOutputValid)+ guard isOutputValid() else { return }if let tc = response.toolCall {// Determine step type based on command purpose@@ -529,7 +588,7 @@ final class CommandModeService: ObservableObject {}// Auto-execute- await self.executeCommand(tc.command, workingDirectory: tc.workingDirectory, callId: tc.id, purpose: tc.purpose)+ await self.executeCommand(tc.command, workingDirectory: tc.workingDirectory, callId: tc.id, purpose: tc.purpose, isOutputValid: isOutputValid)} else {// Just a text response - check if it's a final summary@@ -560,6 +619,7 @@ final class CommandModeService: ObservableObject {}} catch {+ guard isOutputValid() else { return }let errorMsg: Stringif case LLMError.invalidRequest = error {errorMsg = error.localizedDescription@@ -674,7 +734,8 @@ final class CommandModeService: ObservableObject {return false}- private func executeCommand(_ command: String, workingDirectory: String?, callId: String, purpose: String? = nil) async {+ private func executeCommand(_ command: String, workingDirectory: String?, callId: String, purpose: String? = nil, isOutputValid: @escaping @MainActor () -> Bool = { true }) async {+ guard isOutputValid() else { return }self.currentStep = .executing(command)let result = await terminalService.execute(@@ -682,6 +743,8 @@ final class CommandModeService: ObservableObject {workingDirectory: workingDirectory)+ // A command already dispatched cannot be undone. Record its actual outcome+ // even if Escape suppresses every subsequent agent turn and visible output.// Create enhanced result with contextlet enhancedResult = EnhancedCommandResult(result: result,@@ -700,8 +763,13 @@ final class CommandModeService: ObservableObject {stepType: resultStepType))+ guard isOutputValid() else {+ self.saveCurrentChat()+ return+ }+// Continue the loop - let the AI see the result and decide what to do next- await self.processNextTurn()+ await self.processNextTurn(isOutputValid: isOutputValid)}// MARK: - Enhanced Result@@ -754,7 +822,8 @@ final class CommandModeService: ObservableObject {}}- private func callLLM() async throws -> LLMResponse {+ private func callLLM(isOutputValid: @escaping @MainActor () -> Bool) async throws -> LLMResponse {+ guard isOutputValid() else { throw CancellationError() }let settings = SettingsStore.sharedif let issue = settings.commandModeReadinessIssue {throw LLMError.invalidRequest(issue)@@ -954,6 +1023,7 @@ final class CommandModeService: ObservableObject {config.onThinkingChunk = { [weak self] (chunk: String) inguard let self = self else { return }Task { @MainActor in+ guard isOutputValid() else { return }self.thinkingBuffer.append(chunk)// 60fps UI update throttle for thinking@@ -969,6 +1039,7 @@ final class CommandModeService: ObservableObject {config.onContentChunk = { [weak self] (chunk: String) inguard let self = self else { return }Task { @MainActor in+ guard isOutputValid() else { return }self.streamingBuffer.append(chunk)// 60fps UI update throttle@@ -990,6 +1061,7 @@ final class CommandModeService: ObservableObject {DebugLogger.shared.info("Using LLMClient for Command Mode (streaming=\(enableStreaming), messages=\(messages.count), history=\(self.conversationHistory.count))", source: "CommandModeService")let response = try await LLMClient.shared.call(config)+ guard isOutputValid() else { throw CancellationError() }// Final UI update - ensure all content is displayedlet fullContent = self.streamingBuffer.joined()@@ -1002,6 +1074,7 @@ final class CommandModeService: ObservableObject {// Small delay to let the final content render, then cleartry? await Task.sleep(nanoseconds: 50_000_000) // 50ms+ guard isOutputValid() else { throw CancellationError() }// Capture final thinking before clearing (for message storage)let finalThinking = response.thinking ?? (self.thinkingBuffer.isEmpty ? nil : self.thinkingBuffer.joined())diff --git a/Tests/CommandCancellationTests.swift b/Tests/CommandCancellationTests.swiftnew file mode 100644index 00000000..e4f57446--- /dev/null+++ b/Tests/CommandCancellationTests.swift@@ -0,0 +1,494 @@+import Foundation++// Shadows Foundation.UserDefaults so the real chat store never accesses app preferences.+final class UserDefaults {+ static let standard = UserDefaults()+ var values: [String: Any] = [:]+ var writes = 0+ func data(forKey key: String) -> Data? { self.values[key] as? Data }+ func string(forKey key: String) -> String? { self.values[key] as? String }+ func set(_ value: Any?, forKey key: String) { self.values[key] = value; self.writes += 1 }+}++@MainActor final class TerminalService {+ struct CommandResult: Codable {+ let success: Bool+ let command: String+ let output: String+ let error: String?+ let exitCode: Int32+ let executionTimeMs: Int+ }++ static let toolDefinition: [String: Any] = [:]+ static var executed: [String] = []+ static var delay = false+ static var pending: CheckedContinuation<CommandResult, Never>?+ func execute(command: String, workingDirectory: String?) async -> CommandResult {+ Self.executed.append(command)+ if Self.delay {+ return await withCheckedContinuation { Self.pending = $0 }+ }+ return Self.result(command)+ }++ static func result(_ command: String) -> CommandResult {+ .init(success: true, command: command, output: "fake output", error: nil, exitCode: 0, executionTimeMs: 1)+ }+}++@MainActor final class SettingsStore {+ enum Mode { case command }+ struct Provider { let id: String; let baseURL: String }+ struct ReasoningConfig { let isEnabled: Bool; let parameterName: String; let parameterValue: String }+ static let shared = SettingsStore()+ var commandModeConfirmBeforeExecute = false+ let commandModeReadinessIssue: String? = nil+ let effectiveCommandModeProviderID = "fake"+ let effectiveCommandModeSelectedModel = "fake"+ let savedProviders = [Provider(id: "fake", baseURL: "https://fake.invalid")]+ let enableAIStreaming = true+ func analyticsAIModelDescriptor(for mode: Mode) -> String { "fake" }+ func getAPIKey(for provider: String) -> String? { nil }+ func isReasoningModel(_ model: String) -> Bool { false }+ func isTemperatureUnsupported(_ model: String) -> Bool { false }+ func getReasoningConfig(forModel: String, provider: String) -> ReasoningConfig? { nil }+}++@MainActor final class ModelRepository {+ static let shared = ModelRepository()+ func isBuiltIn(_ provider: String) -> Bool { false }+ func defaultBaseURL(for provider: String) -> String { "" }+}++@MainActor final class AnalyticsService {+ static let shared = AnalyticsService()+ func recordUsage(mode: SettingsStore.Mode, aiModel: String) {}+}++@MainActor final class MeetingSummaryActivityCoordinator {+ static let shared = MeetingSummaryActivityCoordinator()+ private var processing = Set<UUID>()+ var active: Bool { !self.processing.isEmpty }+ func beginProcessing() -> UUID? {+ let token = UUID()+ self.processing.insert(token)+ return token+ }++ func endProcessing(_ id: UUID) { self.processing.remove(id) }+ static var busyErrors = 0+ static func presentBusyError() { self.busyErrors += 1 }+}++@MainActor final class NotificationService {+ static var failures = 0+ static func showCommandModeFailure(error: String) { self.failures += 1 }+}++@MainActor final class DebugLogger {+ static let shared = DebugLogger()+ var errors = 0+ func debug(_ message: String, source: String) {}+ func info(_ message: String, source: String) {}+ func error(_ message: String, source: String) { self.errors += 1 }+}++@MainActor final class NotchOverlayManager {+ static let shared = NotchOverlayManager()+ var shouldSyncCommandConversationToNotch = true+ var canShowExpandedCommandOutput = true+ var shows = 0+ func showExpandedCommandOutput() { self.shows += 1 }+}++@MainActor final class NotchContentState {+ struct CommandOutputMessage: Equatable {+ enum Role { case user, assistant, status }+ let role: Role+ let content: String+ }++ static let shared = NotchContentState()+ var commandConversationHistory: [CommandOutputMessage] = []+ var processing = false+ var streaming = ""+ var nonemptyStreamUpdates = 0+ func clearCommandOutput() { self.commandConversationHistory = [] }+ func refreshRecentChats() {}+ func addCommandMessage(role: CommandOutputMessage.Role, content: String) {+ self.commandConversationHistory.append(.init(role: role, content: content))+ }++ func setCommandProcessing(_ value: Bool) { self.processing = value }+ func updateCommandStreamingText(_ text: String) {+ self.streaming = text+ if !text.isEmpty { self.nonemptyStreamUpdates += 1 }+ }+}++enum LLMError: Error { case invalidRequest(String), invalidResponse }+@MainActor final class LLMClient {+ struct ToolCall {+ let id: String+ let name = "execute_terminal_command"+ let command: String+ func getString(_ key: String) -> String? { key == "command" ? self.command : nil }+ func getOptionalString(_ key: String) -> String? { nil }+ }++ struct Response {+ let content: String+ let thinking: String?+ let toolCalls: [ToolCall]+ static let done = Self(content: "Done", thinking: nil, toolCalls: [])+ static let tool = Self(content: "Run tool", thinking: nil, toolCalls: [.init(id: "tool", command: "fake command")])+ }++ struct Config {+ let messages: [[String: Any]]+ var maxRetries = 0+ var retryDelayMs = 0+ var onThinkingChunk: (@Sendable (String) -> Void)?+ var onContentChunk: (@Sendable (String) -> Void)?+ init(+ messages: [[String: Any]],+ model: String,+ baseURL: String,+ apiKey: String,+ streaming: Bool,+ tools: [[String: Any]],+ temperature: Double?,+ maxTokens: Int?,+ extraParameters: [String: Any]+ ) {+ self.messages = messages+ }+ }++ static let shared = LLMClient()+ var configs: [Config] = []+ var delay = true+ var delayOnCallNumber: Int?+ var responses: [Response] = []+ var pending: CheckedContinuation<Response, Error>?+ func call(_ config: Config) async throws -> Response {+ self.configs.append(config)+ if self.delay || self.delayOnCallNumber == self.configs.count {+ defer { self.pending = nil }+ return try await withCheckedThrowingContinuation { self.pending = $0 }+ }+ return self.responses.isEmpty ? .done : self.responses.removeFirst()+ }++ func reset() { self.configs = []; self.responses = []; self.delay = true; self.delayOnCallNumber = nil; self.pending = nil }+}++@main @MainActor enum CommandCancellationTests {+ static var checks = 0+ static func check(_ condition: Bool, _ message: String) {+ precondition(condition, message)+ self.checks += 1+ }++ static func waitFor(_ predicate: () -> Bool) async {+ for _ in 0..<10_000 {+ if predicate() { return }+ await Task.yield()+ }+ preconditionFailure("Timed out awaiting fake dependency")+ }++ static func fixture() -> CommandModeService {+ LLMClient.shared.reset()+ SettingsStore.shared.commandModeConfirmBeforeExecute = false+ TerminalService.executed = []+ TerminalService.delay = false+ TerminalService.pending = nil+ DebugLogger.shared.errors = 0+ NotificationService.failures = 0+ NotchOverlayManager.shared.shows = 0+ NotchContentState.shared.nonemptyStreamUpdates = 0+ let service = CommandModeService()+ service.clearHistory()+ return service+ }++ static func main() async {+ await self.cancelDelayedLLM(response: .tool)+ await self.cancelDelayedLLM(response: .done)+ await self.cancelDelayedLLMError()+ await self.cancelRunningTerminal(result: TerminalService.result("fake command"))+ await self.cancelRunningTerminal(result: .init(success: false, command: "fake command", output: "partial stdout", error: "actual failure", exitCode: 17, executionTimeMs: 42))+ await self.cancelAfterCompletedTool()+ await self.cancelRenderDelay()+ await self.validRecursiveToolRequestStillWorks()+ await self.validFollowUpAndConfirmationStillWork()+ await self.cancelVoiceConfirmation(cancelThroughEscape: true)+ await self.cancelVoiceConfirmation(cancelThroughEscape: false)+ await self.cancelVoiceConfirmationAfterCompletedTool()+ await self.confirmedVoiceDoesNotOwnLaterTypedConfirmation()+ await self.invalidRequestDoesNothing()+ self.check(MeetingSummaryActivityCoordinator.busyErrors == 0, "A canceled request left processing locked")+ print("Command cancellation: \(self.checks) checks passed (production agent loop, streaming callbacks, real in-memory chat store)")+ }++ static func cancelDelayedLLM(response: LLMClient.Response) async {+ let service = self.fixture()+ service.conversationHistory.append(.init(role: .assistant, content: "prior completed answer"))+ service.saveCurrentChat()+ NotchContentState.shared.addCommandMessage(role: .assistant, content: "prior completed answer")+ let messages = service.conversationHistory+ let savedMessages = ChatHistoryStore.shared.currentSession?.messages+ let notch = NotchContentState.shared.commandConversationHistory+ var valid = true+ let task = Task { await service.processUserCommand("voice", notifyInvalidRequest: true, isOutputValid: { valid }) }+ await self.waitFor { LLMClient.shared.pending != nil }+ let writes = UserDefaults.standard.writes+ // Every API entry must reject another command while the voice request awaits.+ await service.processUserCommand("interleaved typed command")+ await service.processFollowUpCommand("interleaved follow-up")+ await service.confirmAndExecute()+ self.check(LLMClient.shared.configs.count == 1 && service.conversationHistory.count == messages.count + 1, "Another entry point interleaved with canceled request cleanup")+ valid = false+ // Both callbacks enqueue Tasks; the guards must live inside those Tasks.+ LLMClient.shared.configs[0].onContentChunk?("late content")+ LLMClient.shared.configs[0].onThinkingChunk?("late thinking")+ for _ in 0..<10 {+ await Task.yield()+ }+ self.check(service.streamingText.isEmpty && service.streamingThinkingText.isEmpty, "Canceled stream reached editor")+ self.check(NotchContentState.shared.nonemptyStreamUpdates == 0, "Canceled stream reached notch")+ LLMClient.shared.pending?.resume(returning: response)+ await task.value+ self.check(TerminalService.executed.isEmpty, "Canceled model response executed tool")+ self.check(LLMClient.shared.configs.count == 1, "Canceled response continued agent loop")+ self.check(service.conversationHistory == messages, "Undispatched canceled intent remained in conversation")+ self.check(ChatHistoryStore.shared.currentSession?.messages == savedMessages && UserDefaults.standard.writes == writes + 2, "Undispatched canceled intent remained in saved chat")+ self.check(CommandModeService().conversationHistory.map(\.content) == messages.map(\.content), "Reloaded chat revived canceled intent")+ self.check(NotchContentState.shared.commandConversationHistory == notch && NotchOverlayManager.shared.shows == 0, "Canceled response displayed output")+ self.check(!service.isProcessing && service.currentStep == nil && service.pendingCommand == nil && !NotchContentState.shared.processing, "Canceled request left pending UI")+ self.check(!MeetingSummaryActivityCoordinator.shared.active, "Canceled request left processing lock")+ // Keep the canceled callback false even while the next request succeeds.+ LLMClient.shared.delay = false+ await service.processUserCommand("typed next")+ self.check(service.conversationHistory.last?.content == "Done" && !service.isProcessing, "Next default request failed")+ self.check(LLMClient.shared.configs[1].messages.allSatisfy { $0["content"] as? String != "voice" }, "Next request inherited canceled intent")+ LLMClient.shared.configs[0].onContentChunk?("stale old callback")+ LLMClient.shared.configs[0].onThinkingChunk?("stale old thinking")+ for _ in 0..<10 {+ await Task.yield()+ }+ self.check(service.streamingText.isEmpty && service.streamingThinkingText.isEmpty, "Old canceled callback contaminated next request")+ }++ static func cancelDelayedLLMError() async {+ let service = self.fixture()+ let messages = service.conversationHistory+ var valid = true+ let task = Task { await service.processUserCommand("voice error", notifyInvalidRequest: true, isOutputValid: { valid }) }+ await self.waitFor { LLMClient.shared.pending != nil }+ let writes = UserDefaults.standard.writes+ valid = false+ LLMClient.shared.pending?.resume(throwing: LLMError.invalidRequest("fake failure"))+ await task.value+ self.check(service.conversationHistory == messages && UserDefaults.standard.writes == writes + 2, "Canceled model error left its undispatched intent in chat")+ self.check(CommandModeService().conversationHistory.map(\.content) == messages.map(\.content), "Reloaded error case revived canceled intent")+ self.check(DebugLogger.shared.errors == 0 && NotificationService.failures == 0 && NotchOverlayManager.shared.shows == 0, "Canceled model error published failure")+ self.check(!service.isProcessing, "Canceled error left processing flag")+ }++ static func cancelRunningTerminal(result: TerminalService.CommandResult) async {+ let service = self.fixture()+ LLMClient.shared.delay = false+ LLMClient.shared.responses = [.tool]+ TerminalService.delay = true+ var valid = true+ let task = Task { await service.processUserCommand("voice tool", isOutputValid: { valid }) }+ await self.waitFor { TerminalService.pending != nil }+ let messages = service.conversationHistory+ let writes = UserDefaults.standard.writes+ let notch = NotchContentState.shared.commandConversationHistory+ valid = false+ TerminalService.pending?.resume(returning: result)+ await task.value+ self.check(TerminalService.executed.count == 1, "Started terminal operation was duplicated")+ self.check(LLMClient.shared.configs.count == 1, "Canceled terminal result continued loop")+ let completion = service.conversationHistory.last+ self.check(+ service.conversationHistory.count == messages.count + 1 && Array(service.conversationHistory.dropLast()) == messages && completion?.role == .tool,+ "Canceled terminal did not append exactly its actual completion"+ )+ let completionJSON = completion?.content.data(using: .utf8).flatMap { try? JSONSerialization.jsonObject(with: $0) } as? [String: Any]+ self.check(+ completionJSON?["output"] as? String == result.output && completionJSON?["exitCode"] as? Int32 == result.exitCode && completionJSON?["success"] as? Bool == result.success,+ "Canceled terminal lost actual stdout, exit code, or success"+ )+ self.check(completionJSON?["error"] as? String == result.error && completion?.stepType == (result.success ? .success : .failure), "Canceled terminal lost actual error or result status")+ self.check(+ UserDefaults.standard.writes == writes + 2 && ChatHistoryStore.shared.currentSession?.messages.count == service.conversationHistory.count,+ "Canceled terminal completion was not persisted exactly once"+ )+ self.check(NotchContentState.shared.commandConversationHistory == notch && NotchOverlayManager.shared.shows == 0, "Canceled terminal result displayed output")+ self.check(!service.isProcessing && service.currentStep == nil, "Canceled terminal left pending UI")+ self.check(service.conversationHistory[messages.count - 1].toolCall?.command == "fake command", "Canceled terminal lost already-started execution evidence")+ await service.processUserCommand("next typed request")+ let nextMessages = LLMClient.shared.configs[1].messages+ let nextToolCalls = nextMessages.filter { $0["tool_calls"] != nil }+ let nextToolResults = nextMessages.filter { $0["role"] as? String == "tool" }+ self.check(nextToolCalls.count == 1 && nextToolResults.count == 1 && nextToolResults[0]["tool_call_id"] as? String == "tool", "Next request did not retain a valid completed tool pair")+ self.check(nextToolResults[0]["content"] as? String == completion?.content, "Next request lost the actual executed result")+ self.check(service.conversationHistory.last?.content == "Done" && !service.isProcessing, "Next request after terminal cancellation failed")+ }++ static func cancelAfterCompletedTool() async {+ let service = self.fixture()+ LLMClient.shared.delay = false+ LLMClient.shared.delayOnCallNumber = 2+ LLMClient.shared.responses = [.tool]+ var valid = true+ let task = Task { await service.processUserCommand("partially executed voice", isOutputValid: { valid }) }+ await self.waitFor { LLMClient.shared.pending != nil }+ let messages = service.conversationHistory+ let writes = UserDefaults.standard.writes+ valid = false+ LLMClient.shared.pending?.resume(returning: .tool)+ await task.value+ self.check(TerminalService.executed.count == 1 && LLMClient.shared.configs.count == 2, "Canceled second model turn executed another tool")+ self.check(service.conversationHistory == messages && messages.last?.role == .tool, "Cancellation removed completed execution evidence")+ self.check(UserDefaults.standard.writes == writes + 2 && ChatHistoryStore.shared.currentSession?.messages.count == messages.count, "Cancellation after a completed tool lost its saved result")+ self.check(CommandModeService().conversationHistory.map(\.content) == messages.map(\.content), "Reload lost completed tool output")+ self.check(!service.isProcessing && service.pendingCommand == nil && NotchOverlayManager.shared.shows == 0, "Canceled second turn left pending UI or reopened output")+ }++ static func cancelRenderDelay() async {+ let service = self.fixture()+ let messages = service.conversationHistory+ var valid = true+ let task = Task { await service.processUserCommand("voice render", isOutputValid: { valid }) }+ await self.waitFor { LLMClient.shared.pending != nil }+ LLMClient.shared.configs[0].onContentChunk?("live content")+ for _ in 0..<10 {+ await Task.yield()+ }+ LLMClient.shared.pending?.resume(returning: .tool)+ // The fake call has returned and production callLLM published its final buffer,+ // so the real agent is suspended in its existing 50ms rendering sleep.+ await self.waitFor { LLMClient.shared.pending == nil && service.streamingText == "live content" }+ valid = false+ let writes = UserDefaults.standard.writes+ await task.value+ self.check(TerminalService.executed.isEmpty && LLMClient.shared.configs.count == 1, "Cancellation during render delay executed a tool")+ self.check(service.conversationHistory == messages && UserDefaults.standard.writes == writes + 2, "Cancellation during render delay left its undispatched intent")+ self.check(!service.isProcessing, "Render-delay cancellation left pending UI")+ }++ static func validRecursiveToolRequestStillWorks() async {+ let service = self.fixture()+ LLMClient.shared.delay = false+ LLMClient.shared.responses = [.tool, .done]+ await service.processUserCommand("valid tool")+ self.check(TerminalService.executed == ["fake command"], "Valid tool failed")+ self.check(LLMClient.shared.configs.count == 2, "Valid tool did not continue agent loop")+ let requestMessages = LLMClient.shared.configs[1].messages+ let assistantCall = requestMessages.first { $0["tool_calls"] != nil }+ let toolResult = requestMessages.first { $0["role"] as? String == "tool" }+ self.check(assistantCall != nil && toolResult?["tool_call_id"] as? String == "tool", "Valid paired tool call lost its wire format")+ self.check(service.conversationHistory.map(\.role) == [.user, .assistant, .tool, .assistant], "Valid conversation lost messages")+ self.check(ChatHistoryStore.shared.currentSession?.messages.count == 4, "Valid request failed to persist")+ self.check(!service.isProcessing && NotchOverlayManager.shared.shows == 1, "Valid request did not finish visibly")+ }++ static func validFollowUpAndConfirmationStillWork() async {+ let followUp = self.fixture()+ LLMClient.shared.delay = false+ await followUp.processFollowUpCommand("typed follow-up")+ self.check(followUp.conversationHistory.map(\.role) == [.user, .assistant] && !followUp.isProcessing, "Default follow-up stopped working")+ self.check(ChatHistoryStore.shared.currentSession?.messages.last?.content == "Done", "Default follow-up failed to persist")++ let confirmed = self.fixture()+ SettingsStore.shared.commandModeConfirmBeforeExecute = true+ LLMClient.shared.delay = false+ LLMClient.shared.responses = [.init(content: "Confirm removal", thinking: nil, toolCalls: [.init(id: "confirmed", command: "rm -rf fake")])]+ await confirmed.processUserCommand("typed destructive request")+ self.check(confirmed.pendingCommand != nil && TerminalService.executed.isEmpty, "Default confirmation did not defer terminal execution")+ self.check(!confirmed.cancelInvalidPendingCommand(), "Escape canceled a typed confirmation")+ await confirmed.confirmAndExecute()+ self.check(TerminalService.executed == ["rm -rf fake"] && confirmed.pendingCommand == nil && !confirmed.isProcessing, "Default confirmed command stopped working")+ self.check(confirmed.conversationHistory.map(\.role) == [.user, .assistant, .tool, .assistant], "Default confirmation lost its complete tool pair")+ }++ static var destructiveResponse: LLMClient.Response {+ .init(content: "Confirm removal", thinking: nil, toolCalls: [.init(id: "pending-voice", command: "rm -rf fake")])+ }++ static func cancelVoiceConfirmation(cancelThroughEscape: Bool) async {+ let service = self.fixture()+ SettingsStore.shared.commandModeConfirmBeforeExecute = true+ LLMClient.shared.delay = false+ LLMClient.shared.responses = [self.destructiveResponse]+ var valid = true+ await service.processUserCommand("undispatched voice deletion", isOutputValid: { valid })+ self.check(service.pendingCommand != nil && TerminalService.executed.isEmpty && !service.isProcessing, "Voice request did not defer for confirmation")+ let count = service.conversationHistory.count+ await service.processUserCommand("interleaved typed request")+ await service.processFollowUpCommand("interleaved follow-up")+ self.check(service.conversationHistory.count == count && LLMClient.shared.configs.count == 1, "Another request replaced pending voice ownership")+ valid = false+ if cancelThroughEscape {+ self.check(service.cancelInvalidPendingCommand(), "Escape did not clear invalid voice confirmation")+ }+ await service.confirmAndExecute()+ self.check(service.pendingCommand == nil && TerminalService.executed.isEmpty && LLMClient.shared.configs.count == 1, "Canceled pending voice command remained executable")+ self.check(service.conversationHistory.isEmpty && ChatHistoryStore.shared.currentSession?.messages.isEmpty == true, "Canceled pending voice intent remained in chat")+ self.check(!service.cancelInvalidPendingCommand() && NotchOverlayManager.shared.shows == 0, "Repeated pending cancellation reopened output")+ await service.processUserCommand("next typed request")+ self.check(LLMClient.shared.configs[1].messages.allSatisfy { $0["content"] as? String != "undispatched voice deletion" }, "Next typed request revived canceled pending intent")+ self.check(service.conversationHistory.last?.content == "Done", "Next typed request after canceled confirmation failed")+ }++ static func cancelVoiceConfirmationAfterCompletedTool() async {+ let service = self.fixture()+ SettingsStore.shared.commandModeConfirmBeforeExecute = true+ LLMClient.shared.delay = false+ LLMClient.shared.responses = [.tool, self.destructiveResponse]+ var valid = true+ await service.processUserCommand("check then delete by voice", isOutputValid: { valid })+ self.check(TerminalService.executed == ["fake command"] && service.pendingCommand != nil, "Fixture did not execute one tool before deferred confirmation")+ valid = false+ self.check(service.cancelInvalidPendingCommand(), "Voice confirmation after completed tool was not canceled")+ await service.confirmAndExecute()+ self.check(TerminalService.executed == ["fake command"] && service.pendingCommand == nil, "Canceled second tool still executed")+ self.check(service.conversationHistory.map(\.role) == [.user, .assistant, .tool], "Pending cleanup damaged completed tool pair or retained undispatched tail")+ self.check(ChatHistoryStore.shared.currentSession?.messages.count == 3 && NotchOverlayManager.shared.shows == 0, "Pending cleanup lost saved execution evidence or reopened output")+ await service.processUserCommand("next typed request")+ let next = LLMClient.shared.configs[2].messages+ self.check(next.filter { $0["tool_calls"] != nil }.count == 1 && next.filter { $0["role"] as? String == "tool" }.count == 1, "Next request inherited an orphan pending tool call")+ }++ static func confirmedVoiceDoesNotOwnLaterTypedConfirmation() async {+ let service = self.fixture()+ SettingsStore.shared.commandModeConfirmBeforeExecute = true+ LLMClient.shared.delay = false+ LLMClient.shared.responses = [self.destructiveResponse]+ var valid = true+ await service.processUserCommand("explicitly confirmed voice", isOutputValid: { valid })+ await service.confirmAndExecute()+ self.check(TerminalService.executed.count == 1 && service.pendingCommand == nil, "Explicit voice confirmation did not execute normally")+ LLMClient.shared.responses = [self.destructiveResponse]+ await service.processUserCommand("later typed deletion")+ valid = false+ self.check(!service.cancelInvalidPendingCommand() && service.pendingCommand != nil, "Stale voice validity canceled a later typed confirmation with the same tool ID")+ await service.confirmAndExecute()+ self.check(TerminalService.executed.count == 2 && service.pendingCommand == nil, "Later typed confirmation lost its normal behavior")+ }++ static func invalidRequestDoesNothing() async {+ let service = self.fixture()+ let messages = service.conversationHistory+ let writes = UserDefaults.standard.writes+ await service.processUserCommand("already canceled", isOutputValid: { false })+ self.check(service.conversationHistory == messages && UserDefaults.standard.writes == writes, "Already canceled request wrote chat")+ self.check(LLMClient.shared.configs.isEmpty && TerminalService.executed.isEmpty && !service.isProcessing, "Already canceled request started work")+ }+}diff --git a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swiftindex 90466fd7..35aaea8d 100644--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift@@ -976,23 +976,28 @@ final class DirectAudioReliabilityTests: XCTestCase {XCTAssertTrue(cancel.contains("self.stopSpokenSendVoiceActivityMonitoring()"))}- func testHistoryRecoveryKeepsEditAndCommandOutsideDictationCancellation() throws {+ func testEscapeCancelsVoiceEditAndCommandWithoutAddingThemToDictationHistory() throws {let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)- XCTAssertTrue(source.contains("self.processingAllowsHistoryCancellation = self.activeRecordingMode != .edit && self.activeRecordingMode != .command"))- XCTAssertTrue(source.contains("self.processingAllowsHistoryCancellation = false"))+ XCTAssertFalse(source.contains("processingAllowsHistoryCancellation"))+ XCTAssertTrue(source.contains("if wasRewriteMode {\n guard !cancelledAtASRStop else {\n self.rewriteModeService.clearState()"))+ XCTAssertTrue(source.contains("if wasCommandMode {\n guard !cancelledAtASRStop else { return }"))let start = try XCTUnwrap(source.range(of: "private func handleCancelShortcutResult("))let end = try XCTUnwrap(source.range(of: "// MARK: - Model Management Helpers", range: start.upperBound..<source.endIndex))let cancel = String(source[start.lowerBound..<end.lowerBound])- XCTAssertTrue(cancel.contains("if self.processingAllowsHistoryCancellation {"))+ XCTAssertTrue(cancel.contains("self.cancelledOutputLifecycleID = lifecycleID"))XCTAssertTrue(cancel.contains("(self.activeRecordingMode == .dictate || self.activeRecordingMode == .promptMode)"))XCTAssertTrue(cancel.contains("!self.isRecordingForRewrite && !self.isRecordingForCommand"))let edit = try XCTUnwrap(source.components(separatedBy: "private func processRewriteWithVoiceInstruction(").last?.components(separatedBy: "private func setActiveRecordingMode(").first)- XCTAssertFalse(edit.contains("cancelledOutputLifecycleID"))- XCTAssertFalse(edit.contains("isOutputValid:"))+ XCTAssertTrue(edit.contains("self.cancelledOutputLifecycleID != lifecycleID"))+ XCTAssertEqual(edit.components(separatedBy: "isOutputValid: isOutputValid").count - 1, 2)+ XCTAssertTrue(edit.contains("if !isOutputValid() { self.rewriteModeService.clearState() }"))+ XCTAssertTrue(edit.contains("await self.rewriteModeService.processRewriteRequest(instruction)\n guard isOutputValid() else { return }"))let command = try XCTUnwrap(source.components(separatedBy: "private func processCommandWithVoice(").last?.components(separatedBy: "/// Capture app context").first)- XCTAssertFalse(command.contains("isOutputValid:"))- XCTAssertFalse(command.contains("cancelledOutputLifecycleID"))+ XCTAssertTrue(command.contains("processUserCommand(command, notifyInvalidRequest: true, isOutputValid: isOutputValid)"))+ XCTAssertTrue(command.contains("self.overlayLifecycleID == lifecycleID && self.cancelledOutputLifecycleID != lifecycleID"))+ XCTAssertTrue(cancel.contains("self.commandModeService.cancelInvalidPendingCommand()"))+ XCTAssertTrue(command.contains("self.pendingVoiceCommandLifecycleID = self.commandModeService.pendingCommand == nil ? nil : lifecycleID"))}func testCancelledProcessingCannotPublishDelayedOverlayOrPracticeResult() throws {diff --git a/Tests/VoiceEditCancellationTests.swift b/Tests/VoiceEditCancellationTests.swiftnew file mode 100644index 00000000..96a41e8c--- /dev/null+++ b/Tests/VoiceEditCancellationTests.swift@@ -0,0 +1,145 @@+import Foundation++// Production voice processing runs above these boundary doubles.+@MainActor final class DebugLogger {+ static let shared = DebugLogger()+ func info(_: String, source _: String) {}+ func error(_: String, source _: String) {}+}++@MainActor final class SettingsStore {+ static let shared = SettingsStore()+ var copyTranscriptionToClipboard = true+}++enum DeliveryFailure { case targetRestoreFailed }+enum TextDeliveryResult { case delivered, cancelled, recoverableFailure(DeliveryFailure) }++@MainActor final class RewriteDouble {+ var originalText = "original"+ var rewrittenText = ""+ var requests = 0+ var clears = 0+ var respond: CheckedContinuation<Void, Never>?+ func setPromptAppBundleID(_: String) {}+ func processRewriteRequest(_: String) async {+ self.requests += 1+ await withCheckedContinuation { self.respond = $0 }+ self.rewrittenText = "rewrite"+ }++ func clearState() { self.originalText = ""; self.rewrittenText = ""; self.clears += 1 }+}++@MainActor final class MenuDouble {+ var finishes = 0+ func setProcessing(_: Bool) {}+ func finishProcessingAndHideOverlay() async { self.finishes += 1 }+}++@MainActor final class ASRDouble {+ var deliveries = 0+ var writes = 0+ var resume: CheckedContinuation<Void, Never>?+ var failure = false+ func typeTextToActiveField(+ _: String,+ preferredTargetPID _: Int?,+ preserveTranscriptOnClipboard _: Bool,+ isOutputValid: @escaping @MainActor () -> Bool+ ) async -> TextDeliveryResult {+ self.deliveries += 1+ await withCheckedContinuation { self.resume = $0 }+ guard isOutputValid() else { return .cancelled }+ if self.failure { return .recoverableFailure(.targetRestoreFailed) }+ self.writes += 1+ return .delivered+ }+}++@MainActor final class VoiceEditOwner {+ var overlayLifecycleID: UInt64 = 7+ var cancelledOutputLifecycleID: UInt64?+ let rewriteModeService = RewriteDouble()+ let menuBarManager = MenuDouble()+ let asr = ASRDouble()+ var restoreFocus = true+ var focus: CheckedContinuation<Bool, Never>?+ var failures = 0+ var hides = 0+ func resolveTypingTargetPID() -> (pid: Int?, shouldRestoreOriginalFocus: Bool) { (1, self.restoreFocus) }+ func prepareRecordingTargetForDelivery(+ _: String,+ keepBackup _: Bool,+ isOutputValid: @escaping @MainActor () -> Bool+ ) async -> Bool {+ guard isOutputValid() else { return false }+ let result = await withCheckedContinuation { self.focus = $0 }+ return result && isOutputValid()+ }++ func showTextDeliveryFailure(_: DeliveryFailure, transcript _: String) { self.failures += 1 }+ func hideOverlayAfterOutput() { self.hides += 1 }+}++@main enum VoiceEditCancellationTests {+ @MainActor static func waitUntil(_ predicate: () -> Bool) async {+ for _ in 0..<10_000 {+ if predicate() { return }+ await Task.yield()+ }+ fatalError("Boundary was never reached")+ }++ @MainActor static func main() async {+ let context = (name: "Editor", bundleId: "editor", windowTitle: "Document")+ let before = VoiceEditOwner()+ before.cancelledOutputLifecycleID = 7+ await before.processRewriteWithVoiceInstruction("rewrite", appInfo: context, lifecycleID: 7)+ precondition(before.rewriteModeService.requests == 0)++ // Escape while the model is working: no focus, paste, clipboard, or failure UI.+ let model = VoiceEditOwner()+ let modelTask = Task { await model.processRewriteWithVoiceInstruction("rewrite", appInfo: context, lifecycleID: 7) }+ await waitUntil { model.rewriteModeService.respond != nil }+ model.cancelledOutputLifecycleID = 7+ model.rewriteModeService.respond?.resume()+ await modelTask.value+ precondition(model.focus == nil && model.asr.deliveries == 0 && model.failures == 0 && model.hides == 0)+ precondition(model.rewriteModeService.clears == 1 && model.rewriteModeService.rewrittenText.isEmpty)++ for focusResult in [true, false] {+ let owner = VoiceEditOwner()+ let task = Task { await owner.processRewriteWithVoiceInstruction("rewrite", appInfo: context, lifecycleID: 7) }+ await waitUntil { owner.rewriteModeService.respond != nil }+ owner.rewriteModeService.respond?.resume()+ await self.waitUntil { owner.focus != nil }+ owner.cancelledOutputLifecycleID = 7+ owner.focus?.resume(returning: focusResult)+ await task.value+ precondition(owner.asr.deliveries == 0 && owner.failures == 0 && owner.hides == 0)+ precondition(owner.rewriteModeService.clears == 1)+ }++ // Cancel queued OS delivery, and prove a new request still delivers normally.+ for outcome in ["cancel", "stale", "success", "failure"] {+ let owner = VoiceEditOwner()+ owner.cancelledOutputLifecycleID = 6+ owner.restoreFocus = false+ let task = Task { await owner.processRewriteWithVoiceInstruction("rewrite", appInfo: context, lifecycleID: 7) }+ await waitUntil { owner.rewriteModeService.respond != nil }+ owner.rewriteModeService.respond?.resume()+ await self.waitUntil { owner.asr.resume != nil }+ if outcome == "cancel" { owner.cancelledOutputLifecycleID = 7 }+ if outcome == "stale" { owner.overlayLifecycleID = 8 }+ owner.asr.failure = outcome == "failure"+ owner.asr.resume?.resume()+ await task.value+ precondition(owner.asr.writes == (outcome == "success" ? 1 : 0))+ precondition(owner.hides == (outcome == "success" ? 1 : 0))+ precondition(owner.failures == (outcome == "failure" ? 1 : 0))+ precondition(owner.rewriteModeService.clears == (outcome == "failure" ? 0 : 1))+ }+ print("Voice Edit cancellation: 8 production-path scenarios passed")+ }+}diff --git a/Tests/run_command_cancellation_tests.sh b/Tests/run_command_cancellation_tests.shnew file mode 100644index 00000000..4ab3a9b5--- /dev/null+++ b/Tests/run_command_cancellation_tests.sh@@ -0,0 +1,19 @@+#!/bin/sh+set -eu+cd "$(dirname "$0")/.."+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then+ echo "Select a full Xcode with DEVELOPER_DIR before running these tests." >&2+ exit 1+fi+export DEVELOPER_DIR="$task_developer_dir"+task_test_dir=$(mktemp -d /tmp/fluidvoice-command-cancellation.XXXXXX)+trap 'rm -rf "$task_test_dir"' EXIT+# Compile the entire production agent, including streaming callbacks and recursive turns.+# Only its model, terminal, UI, and UserDefaults dependencies are test doubles.+xcrun swiftc -parse-as-library \+ Sources/Fluid/Services/CommandModeService.swift \+ Sources/Fluid/Persistence/ChatHistoryStore.swift \+ Tests/CommandCancellationTests.swift \+ -o "$task_test_dir/cancellation-tests"+"$task_test_dir/cancellation-tests"diff --git a/Tests/run_voice_edit_cancellation_tests.sh b/Tests/run_voice_edit_cancellation_tests.shnew file mode 100644index 00000000..c150ef5a--- /dev/null+++ b/Tests/run_voice_edit_cancellation_tests.sh@@ -0,0 +1,22 @@+#!/bin/sh+set -eu+cd "$(dirname "$0")/.."+task_developer_dir="${DEVELOPER_DIR:-$(xcode-select -p)}"+if [ ! -d "$task_developer_dir/Platforms/MacOSX.platform" ]; then+ echo "Select a full Xcode with DEVELOPER_DIR before running these tests." >&2+ exit 1+fi+export DEVELOPER_DIR="$task_developer_dir"+task_test_dir=$(mktemp -d /tmp/fluidvoice-voice-edit.XXXXXX)+trap 'rm -rf "$task_test_dir"' EXIT+# Exercise the production voice caller; replace only model, focus, and OS delivery.+python3 - "$task_test_dir/VoiceEdit.swift" <<'PY'+from pathlib import Path+import sys+source = Path('Sources/Fluid/ContentView.swift').read_text()+start = source.index(' private func processRewriteWithVoiceInstruction(')+end = source.index(' private func setActiveRecordingMode(', start)+Path(sys.argv[1]).write_text('import Foundation\n@MainActor extension VoiceEditOwner {\n' + source[start:end].replace('private func', 'func', 1) + '}\n')+PY+xcrun swiftc -parse-as-library "$task_test_dir/VoiceEdit.swift" Tests/VoiceEditCancellationTests.swift -o "$task_test_dir/edit-tests"+"$task_test_dir/edit-tests"