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
limit Escape recovery to dictation History and remove Command changes
altic-devd027b8df02de
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 2068930f..76e55035 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -275,6 +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 cancelledOutputLifecycleID: UInt64?@State private var isSavingCancelledRecording = false@@ -2926,8 +2927,13 @@ 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 }+ if self.processingDictationLifecycleID == outputLifecycleID {+ self.processingDictationLifecycleID = nil+ self.processingAllowsHistoryCancellation = false+ }}var closeTrace = OverlayCloseTrace("content.stopCallback")defer { closeTrace.finish() }@@ -3035,7 +3041,7 @@ struct ContentView: View {return}- var cancelledAtASRStop = route == .historyOnly || self.cancelledOutputLifecycleID == expectedOverlayLifecycleID+ let cancelledAtASRStop = route == .historyOnly || self.cancelledOutputLifecycleID == expectedOverlayLifecycleIDif cancelledAtASRStop, promptTestSessionID != nil || route == .onboardingSandbox { return }// Prompt Test Mode: reroute dictation hotkey output into the prompt editor (no typing/clipboard/history).@@ -3048,7 +3054,7 @@ struct ContentView: View {}// If this was a rewrite recording, process the rewrite instead of typing- if !cancelledAtASRStop, wasRewriteMode {+ if wasRewriteMode {DebugLogger.shared.info("Processing rewrite with instruction: \(transcribedText)", source: "ContentView")AnalyticsService.shared.recordModelUsage(role: .transcription,@@ -3056,22 +3062,20 @@ struct ContentView: View {descriptor: self.settings.selectedSpeechModel.analyticsDescriptor)let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()- await self.processRewriteWithVoiceInstruction(transcribedText, appInfo: appInfo, lifecycleID: expectedOverlayLifecycleID)- cancelledAtASRStop = self.cancelledOutputLifecycleID == expectedOverlayLifecycleID- if !cancelledAtASRStop { return }+ await self.processRewriteWithVoiceInstruction(transcribedText, appInfo: appInfo)+ return}// If this was a command recording, process the command- if !cancelledAtASRStop, wasCommandMode {+ if wasCommandMode {DebugLogger.shared.info("Processing command: \(transcribedText)", source: "ContentView")AnalyticsService.shared.recordModelUsage(role: .transcription,mode: .command,descriptor: self.settings.selectedSpeechModel.analyticsDescriptor)- await self.processCommandWithVoice(transcribedText, lifecycleID: expectedOverlayLifecycleID)- cancelledAtASRStop = self.cancelledOutputLifecycleID == expectedOverlayLifecycleID- if !cancelledAtASRStop { return }+ await self.processCommandWithVoice(transcribedText)+ return}var finalText: String@@ -3100,7 +3104,7 @@ struct ContentView: View {let practiceModelID = route == .onboardingSandbox && self.settings.onboardingCurrentStep == 5? PrivateAIProviderPromptFormat.verifiedModelID(settings: self.settings) : nil- let shouldUseAI = !(cancelledAtASRStop && (wasRewriteMode || wasCommandMode)) && !sendsExistingDraft && (practiceModelID != nil || (stopSnapshot?.usesAI ?? DictationAIPostProcessingGate.isConfigured(+ let shouldUseAI = !sendsExistingDraft && (practiceModelID != nil || (stopSnapshot?.usesAI ?? DictationAIPostProcessingGate.isConfigured(for: activeDictationSlot ?? .primary,appBundleID: appInfo.bundleId)))@@ -4381,8 +4385,7 @@ struct ContentView: View {private func processRewriteWithVoiceInstruction(_ instruction: String,- appInfo: (name: String, bundleId: String, windowTitle: String),- lifecycleID: UInt64+ appInfo: (name: String, bundleId: String, windowTitle: String)) async {self.rewriteModeService.setPromptAppBundleID(appInfo.bundleId)let hasOriginalText = !self.rewriteModeService.originalText.isEmpty@@ -4398,7 +4401,6 @@ 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 {@@ -4407,8 +4409,7 @@ struct ContentView: View {// Type the rewritten textlet typingTarget = self.resolveTypingTargetPID()if typingTarget.shouldRestoreOriginalFocus {- guard await self.prepareRecordingTargetForDelivery(self.rewriteModeService.rewrittenText, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard, isOutputValid: { self.cancelledOutputLifecycleID != lifecycleID }) else {- guard self.cancelledOutputLifecycleID != lifecycleID else { return }+ guard await self.prepareRecordingTargetForDelivery(self.rewriteModeService.rewrittenText, keepBackup: SettingsStore.shared.copyTranscriptionToClipboard) else {self.showTextDeliveryFailure(.targetRestoreFailed,transcript: self.rewriteModeService.rewrittenText@@ -4419,10 +4420,8 @@ struct ContentView: View {let deliveryResult = await self.asr.typeTextToActiveField(self.rewriteModeService.rewrittenText,preferredTargetPID: typingTarget.pid,- preserveTranscriptOnClipboard: SettingsStore.shared.copyTranscriptionToClipboard,- isOutputValid: { self.cancelledOutputLifecycleID != lifecycleID }+ preserveTranscriptOnClipboard: SettingsStore.shared.copyTranscriptionToClipboard)- guard self.cancelledOutputLifecycleID != lifecycleID else { return }if case let .recoverableFailure(failure) = deliveryResult {self.showTextDeliveryFailure(failure, transcript: self.rewriteModeService.rewrittenText)return@@ -4521,8 +4520,7 @@ struct ContentView: View {// MARK: - Command Mode Voice Processing- private func processCommandWithVoice(_ command: String, lifecycleID: UInt64) async {- guard self.cancelledOutputLifecycleID != lifecycleID else { return }+ private func processCommandWithVoice(_ command: String) async {DebugLogger.shared.info("Processing voice command: '\(command)'", source: "ContentView")// Show processing animation@@ -4530,10 +4528,7 @@ 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, isOutputValid: {- self.cancelledOutputLifecycleID != lifecycleID- })- guard self.cancelledOutputLifecycleID != lifecycleID else { return }+ await self.commandModeService.processUserCommand(command, notifyInvalidRequest: true)// Hide processing animationself.menuBarManager.setProcessing(false)@@ -5046,10 +5041,14 @@ struct ContentView: View {if let lifecycleID = self.processingDictationLifecycleID {// A stop already owns the audio; suppress its pending output without stopping again.- self.cancelledOutputLifecycleID = lifecycleID- handled = true+ if self.processingAllowsHistoryCancellation {+ 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)+ && !self.isRecordingForRewrite && !self.isRecordingForCommand&& self.currentDictationOutputRouteForHotkeyStop() != .onboardingSandbox&& !DictationPromptTestCoordinator.shared.isActive && !self.showsFluidIntelligenceDemoif preservesHistory {diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swiftindex d65130c8..055a310b 100644--- a/Sources/Fluid/Services/CommandModeService.swift+++ b/Sources/Fluid/Services/CommandModeService.swift@@ -358,8 +358,7 @@ final class CommandModeService: ObservableObject {}/// Process user voice/text command- func processUserCommand(_ text: String, notifyInvalidRequest: Bool = false, isOutputValid: @escaping @MainActor () -> Bool = { true }) async {- guard isOutputValid() else { return }+ func processUserCommand(_ text: String, notifyInvalidRequest: Bool = false) async {guard let summaryActivity = MeetingSummaryActivityCoordinator.shared.beginProcessing() else {MeetingSummaryActivityCoordinator.presentBusyError()return@@ -374,16 +373,6 @@ final class CommandModeService: ObservableObject {)self.isProcessing = true- defer {- if !isOutputValid() {- 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))@@ -396,7 +385,7 @@ final class CommandModeService: ObservableObject {NotchContentState.shared.setCommandProcessing(true)}- await self.processNextTurn(notifyInvalidRequest: notifyInvalidRequest, isOutputValid: isOutputValid)+ await self.processNextTurn(notifyInvalidRequest: notifyInvalidRequest)}/// Process follow-up command from notch input@@ -460,8 +449,7 @@ final class CommandModeService: ObservableObject {// MARK: - Agent Loop- private func processNextTurn(notifyInvalidRequest: Bool = false, isOutputValid: @escaping @MainActor () -> Bool = { true }) async {- guard isOutputValid() else { return }+ private func processNextTurn(notifyInvalidRequest: Bool = false) async {if self.currentTurnCount >= self.maxTurns {let errorMsg = "Reached maximum steps limit. Please review the progress and continue if needed."self.conversationHistory.append(Message(@@ -493,8 +481,7 @@ final class CommandModeService: ObservableObject {}do {- let response = try await callLLM(isOutputValid: isOutputValid)- guard isOutputValid() else { return }+ let response = try await callLLM()if let tc = response.toolCall {// Determine step type based on command purpose@@ -542,7 +529,7 @@ final class CommandModeService: ObservableObject {}// Auto-execute- await self.executeCommand(tc.command, workingDirectory: tc.workingDirectory, callId: tc.id, purpose: tc.purpose, isOutputValid: isOutputValid)+ await self.executeCommand(tc.command, workingDirectory: tc.workingDirectory, callId: tc.id, purpose: tc.purpose)} else {// Just a text response - check if it's a final summary@@ -573,7 +560,6 @@ final class CommandModeService: ObservableObject {}} catch {- guard isOutputValid() else { return }let errorMsg: Stringif case LLMError.invalidRequest = error {errorMsg = error.localizedDescription@@ -688,8 +674,7 @@ final class CommandModeService: ObservableObject {return false}- private func executeCommand(_ command: String, workingDirectory: String?, callId: String, purpose: String? = nil, isOutputValid: @escaping @MainActor () -> Bool = { true }) async {- guard isOutputValid() else { return }+ private func executeCommand(_ command: String, workingDirectory: String?, callId: String, purpose: String? = nil) async {self.currentStep = .executing(command)let result = await terminalService.execute(@@ -697,8 +682,6 @@ 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,@@ -717,13 +700,8 @@ 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(isOutputValid: isOutputValid)+ await self.processNextTurn()}// MARK: - Enhanced Result@@ -776,8 +754,7 @@ final class CommandModeService: ObservableObject {}}- private func callLLM(isOutputValid: @escaping @MainActor () -> Bool) async throws -> LLMResponse {- guard isOutputValid() else { throw CancellationError() }+ private func callLLM() async throws -> LLMResponse {let settings = SettingsStore.sharedif let issue = settings.commandModeReadinessIssue {throw LLMError.invalidRequest(issue)@@ -977,7 +954,6 @@ 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@@ -993,7 +969,6 @@ 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@@ -1015,7 +990,6 @@ 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()@@ -1028,7 +1002,6 @@ 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/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swiftindex d500c76d..19253102 100644--- a/Sources/Fluid/Services/TypingService.swift+++ b/Sources/Fluid/Services/TypingService.swift@@ -1451,12 +1451,7 @@ final class TypingService {}private nonisolated func setTextViaSelection(_ element: AXUIElement, _ text: String, isOutputValid: () -> Bool) -> Bool {- // First, select all existing text- guard isOutputValid() else { return false }- let selectAllResult = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, "" as CFString)- self.log("[TypingService] Select all result: \(selectAllResult.rawValue)")-- // Then replace the selection with our text+ // Replace the current selection in one write; never erase it first.let cfText = text as CFStringguard isOutputValid() else { return false }let result = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, cfText)diff --git a/Tests/CommandCancellationTests.swift b/Tests/CommandCancellationTests.swiftdeleted file mode 100644index 5b5a3fd1..00000000--- a/Tests/CommandCancellationTests.swift+++ /dev/null@@ -1,370 +0,0 @@-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()- var active = false- func beginProcessing() -> UUID? {- guard !self.active else { return nil }- self.active = true- return UUID()- }-- func endProcessing(_ id: UUID) { self.active = false }- 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 responses: [Response] = []- var pending: CheckedContinuation<Response, Error>?- func call(_ config: Config) async throws -> Response {- self.configs.append(config)- if self.delay {- 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.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()- 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.cancelRenderDelay()- await self.validRecursiveToolRequestStillWorks()- 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()- var valid = true- let task = Task { await service.processUserCommand("voice", notifyInvalidRequest: true, isOutputValid: { valid }) }- await self.waitFor { LLMClient.shared.pending != nil }- let messages = service.conversationHistory- let saved = ChatHistoryStore.shared.currentSession- let writes = UserDefaults.standard.writes- let notch = NotchContentState.shared.commandConversationHistory- 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, "Canceled response changed conversation")- self.check(ChatHistoryStore.shared.currentSession == saved && UserDefaults.standard.writes == writes, "Canceled response persisted chat")- 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")- 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()- var valid = true- let task = Task { await service.processUserCommand("voice error", notifyInvalidRequest: true, isOutputValid: { valid }) }- await self.waitFor { LLMClient.shared.pending != nil }- let count = service.conversationHistory.count- let writes = UserDefaults.standard.writes- valid = false- LLMClient.shared.pending?.resume(throwing: LLMError.invalidRequest("fake failure"))- await task.value- self.check(service.conversationHistory.count == count && UserDefaults.standard.writes == writes, "Canceled model error mutated chat")- 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 cancelRenderDelay() async {- let service = self.fixture()- 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 messages = service.conversationHistory- 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, "Cancellation during render delay mutated chat")- 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 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 ed4a9a53..90466fd7 100644--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift@@ -946,8 +946,8 @@ final class DirectAudioReliabilityTests: XCTestCase {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("if wasRewriteMode {"))+ XCTAssertTrue(pipeline.contains("if 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"))@@ -976,16 +976,23 @@ final class DirectAudioReliabilityTests: XCTestCase {XCTAssertTrue(cancel.contains("self.stopSpokenSendVoiceActivityMonitoring()"))}- func testVoiceCommandForwardsEscapeCancellationIntoAgentLoop() throws {+ func testHistoryRecoveryKeepsEditAndCommandOutsideDictationCancellation() 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("await self.processCommandWithVoice(transcribedText, lifecycleID: expectedOverlayLifecycleID)"))- let start = try XCTUnwrap(source.range(of: "private func processCommandWithVoice("))- let end = try XCTUnwrap(source.range(of: "/// Capture app context", range: start.upperBound..<source.endIndex))- let command = String(source[start.lowerBound..<end.lowerBound])- XCTAssertTrue(command.contains("notifyInvalidRequest: true, isOutputValid: {"))- XCTAssertTrue(command.contains("self.cancelledOutputLifecycleID != lifecycleID"))- XCTAssertEqual(command.components(separatedBy: "guard self.cancelledOutputLifecycleID != lifecycleID else { return }").count - 1, 2)+ XCTAssertTrue(source.contains("self.processingAllowsHistoryCancellation = self.activeRecordingMode != .edit && self.activeRecordingMode != .command"))+ XCTAssertTrue(source.contains("self.processingAllowsHistoryCancellation = false"))+ 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.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:"))+ 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"))}func testCancelledProcessingCannotPublishDelayedOverlayOrPracticeResult() throws {@@ -996,9 +1003,6 @@ final class DirectAudioReliabilityTests: XCTestCase {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 {diff --git a/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift b/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swiftindex 853faa8a..8fb2d5ec 100644--- a/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift+++ b/Tests/FluidDictationIntegrationTests/TypingServiceTransientPasteboardTests.swift@@ -527,6 +527,17 @@ final class TypingServiceTransientPasteboardTests: XCTestCase {XCTAssertEqual(attempts, 2)}+ func testAXSelectionReplacementNeverErasesSelectionBeforeInsertion() throws {+ let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()+ let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/Services/TypingService.swift"), encoding: .utf8)+ let start = try XCTUnwrap(source.range(of: "private nonisolated func setTextViaSelection("))+ let end = try XCTUnwrap(source.range(of: "private nonisolated func insertTextAtInsertionPoint", range: start.upperBound..<source.endIndex))+ let selection = String(source[start.lowerBound..<end.lowerBound])+ XCTAssertEqual(selection.components(separatedBy: "AXUIElementSetAttributeValue(").count - 1, 1, "Selection replacement must be a single committed write")+ XCTAssertFalse(selection.contains("\"\" as CFString"), "Never delete the selection before the cancel guard")+ XCTAssertTrue(selection.contains("guard isOutputValid() else { return false }\n let result = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, cfText)"))+ }+func testDirectFallbacksAndAXWritesForwardAndRecheckOutputValidity() throws {let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent()diff --git a/Tests/run_command_cancellation_tests.sh b/Tests/run_command_cancellation_tests.shdeleted file mode 100644index 4ab3a9b5..00000000--- a/Tests/run_command_cancellation_tests.sh+++ /dev/null@@ -1,19 +0,0 @@-#!/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"