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
close Command cancellation race and preserve rejected follow-ups
altic-devcc3168cfa9b8
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 3b6c66be..2d250612 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -761,8 +761,14 @@ struct ContentView: View {}NotchOverlayManager.shared.onCommandFollowUp = { [weak commandModeService] text in- guard NotchOverlayManager.shared.allowsCommandNotchActions else { return }- await commandModeService?.processFollowUpCommand(text)+ guard NotchOverlayManager.shared.allowsCommandNotchActions, let commandModeService else { return false }+ let accepted = await commandModeService.processFollowUpCommand(text)+ if !accepted, commandModeService.pendingCommand != nil {+ self.asr.errorTitle = "Command Awaiting Approval"+ self.asr.errorMessage = "Approve or cancel the pending command before sending a follow-up. Your text has been kept."+ self.asr.showError = true+ }+ return accepted}NotchOverlayManager.shared.onNewChat = { [weak commandModeService] in@@ -4543,7 +4549,10 @@ struct ContentView: View {// Process the command through CommandModeService// This stores the conversation history and executes any terminal commandsawait self.commandModeService.processUserCommand(command, notifyInvalidRequest: true, isOutputValid: isOutputValid)- guard isOutputValid() else { return }+ guard isOutputValid() else {+ self.commandModeService.cancelInvalidPendingCommand()+ return+ }self.pendingVoiceCommandLifecycleID = self.commandModeService.pendingCommand == nil ? nil : lifecycleID// Hide processing animationdiff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swiftindex 6e0e8c4f..df18a996 100644--- a/Sources/Fluid/Services/CommandModeService.swift+++ b/Sources/Fluid/Services/CommandModeService.swift@@ -412,16 +412,17 @@ final class CommandModeService: ObservableObject {}/// Process follow-up command from notch input- func processFollowUpCommand(_ text: String) async {- guard !self.isProcessing, self.pendingCommand == nil else { return }+ @discardableResult+ func processFollowUpCommand(_ text: String) async -> Bool {+ guard !self.isProcessing, self.pendingCommand == nil else { return false }self.pendingVoiceCommandCancellation = nilguard let summaryActivity = MeetingSummaryActivityCoordinator.shared.beginProcessing() else {MeetingSummaryActivityCoordinator.presentBusyError()- return+ return false}defer { MeetingSummaryActivityCoordinator.shared.endProcessing(summaryActivity) }- guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return false }AnalyticsService.shared.recordUsage(mode: .command,@@ -443,6 +444,7 @@ final class CommandModeService: ObservableObject {}await self.processNextTurn()+ return true}/// Execute pending command (after user confirmation)diff --git a/Sources/Fluid/Services/NotchOverlayManager.swift b/Sources/Fluid/Services/NotchOverlayManager.swiftindex d1c6c2ae..ade6374b 100644--- a/Sources/Fluid/Services/NotchOverlayManager.swift+++ b/Sources/Fluid/Services/NotchOverlayManager.swift@@ -75,7 +75,7 @@ final class NotchOverlayManager {// Callbacks for command output interactionvar onCommandOutputDismiss: (() -> Void)?- var onCommandFollowUp: ((String) async -> Void)?+ var onCommandFollowUp: ((String) async -> Bool)?var onNotchClicked: (() -> Void)? // Called when regular notch is clicked in command mode// Callbacks for chat management@@ -619,8 +619,8 @@ final class NotchOverlayManager {}},onSubmit: { [weak self] text in- guard let self, self.allowsCommandNotchActions else { return }- await self.onCommandFollowUp?(text)+ guard let self, self.allowsCommandNotchActions else { return false }+ return await self.onCommandFollowUp?(text) ?? false},onNewChat: { [weak self] inTask { @MainActor indiff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swiftindex 1a93e410..634a8502 100644--- a/Sources/Fluid/Views/NotchContentViews.swift+++ b/Sources/Fluid/Views/NotchContentViews.swift@@ -1413,7 +1413,7 @@ struct NotchCompactBottomView: View {struct NotchCommandOutputExpandedView: View {let audioPublisher: AnyPublisher<CGFloat, Never>let onDismiss: () -> Void- let onSubmit: (String) async -> Void+ let onSubmit: (String) async -> Boollet onNewChat: () -> Voidlet onSwitchChat: (String) -> Voidlet onClearChat: () -> Void@@ -1850,10 +1850,11 @@ struct NotchCommandOutputExpandedView: View {private func submitFollowUp() {guard !self.inputText.isEmpty else { return }let text = self.inputText- self.inputText = ""Task {- await self.onSubmit(text)+ if await self.onSubmit(text), self.inputText == text {+ self.inputText = ""+ }}}}diff --git a/Tests/CommandCancellationTests.swift b/Tests/CommandCancellationTests.swiftindex e4f57446..29e57ba8 100644--- a/Tests/CommandCancellationTests.swift+++ b/Tests/CommandCancellationTests.swift@@ -184,6 +184,38 @@ enum LLMError: Error { case invalidRequest(String), invalidResponse }func reset() { self.configs = []; self.responses = []; self.delay = true; self.delayOnCallNumber = nil; self.pending = nil }}+@MainActor final class CommandMenuDouble {+ var updates: [Bool] = []+ func setProcessing(_ value: Bool) { self.updates.append(value) }+}++@MainActor final class CommandBoundaryDouble {+ let service: CommandModeService+ var afterRequest: (() -> Void)?+ var pendingCommand: CommandModeService.PendingCommand? { self.service.pendingCommand }+ init(_ service: CommandModeService) { self.service = service }+ func processUserCommand(_ text: String, notifyInvalidRequest: Bool, isOutputValid: @escaping @MainActor () -> Bool) async {+ await self.service.processUserCommand(text, notifyInvalidRequest: notifyInvalidRequest, isOutputValid: isOutputValid)+ self.afterRequest?()+ }++ @discardableResult func cancelInvalidPendingCommand() -> Bool { self.service.cancelInvalidPendingCommand() }+}++@MainActor final class VoiceCommandOwner {+ var overlayLifecycleID: UInt64 = 7+ var cancelledOutputLifecycleID: UInt64?+ var pendingVoiceCommandLifecycleID: UInt64?+ let commandModeService: CommandBoundaryDouble+ let menuBarManager = CommandMenuDouble()+ init(_ service: CommandModeService) { self.commandModeService = CommandBoundaryDouble(service) }+}++@MainActor final class NotchInputOwner {+ var inputText = ""+ var onSubmit: (String) async -> Bool = { _ in false }+}+@main @MainActor enum CommandCancellationTests {static var checks = 0static func check(_ condition: Bool, _ message: String) {@@ -228,6 +260,8 @@ enum LLMError: Error { case invalidRequest(String), invalidResponse }await self.cancelVoiceConfirmation(cancelThroughEscape: false)await self.cancelVoiceConfirmationAfterCompletedTool()await self.confirmedVoiceDoesNotOwnLaterTypedConfirmation()+ await self.voiceConfirmationCancelledAtCallerContinuation()+ await self.notchInputClearsOnlyAcceptedText()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)")@@ -247,7 +281,8 @@ enum LLMError: Error { case invalidRequest(String), invalidResponse }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")+ let accepted = await service.processFollowUpCommand("interleaved follow-up")+ self.check(!accepted, "Blocked follow-up falsely reported acceptance")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@@ -402,7 +437,8 @@ enum LLMError: Error { case invalidRequest(String), invalidResponse }static func validFollowUpAndConfirmationStillWork() async {let followUp = self.fixture()LLMClient.shared.delay = false- await followUp.processFollowUpCommand("typed follow-up")+ let accepted = await followUp.processFollowUpCommand("typed follow-up")+ self.check(accepted, "Normal follow-up was not accepted")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")@@ -432,7 +468,8 @@ enum LLMError: Error { case invalidRequest(String), invalidResponse }self.check(service.pendingCommand != nil && TerminalService.executed.isEmpty && !service.isProcessing, "Voice request did not defer for confirmation")let count = service.conversationHistory.countawait service.processUserCommand("interleaved typed request")- await service.processFollowUpCommand("interleaved follow-up")+ let accepted = await service.processFollowUpCommand("interleaved follow-up")+ self.check(!accepted, "Blocked follow-up falsely reported acceptance")self.check(service.conversationHistory.count == count && LLMClient.shared.configs.count == 1, "Another request replaced pending voice ownership")valid = falseif cancelThroughEscape {@@ -483,6 +520,58 @@ enum LLMError: Error { case invalidRequest(String), invalidResponse }self.check(TerminalService.executed.count == 2 && service.pendingCommand == nil, "Later typed confirmation lost its normal behavior")}+ static func voiceConfirmationCancelledAtCallerContinuation() async {+ for cancel in [true, false] {+ let service = self.fixture()+ SettingsStore.shared.commandModeConfirmBeforeExecute = true+ LLMClient.shared.delay = false+ LLMClient.shared.responses = [self.destructiveResponse]+ let owner = VoiceCommandOwner(service)+ if cancel {+ owner.commandModeService.afterRequest = { owner.cancelledOutputLifecycleID = 7 }+ }+ await owner.processCommandWithVoice("voice awaiting approval", lifecycleID: 7)+ self.check(TerminalService.executed.isEmpty, "Voice continuation dispatched without approval")+ if cancel {+ self.check(service.pendingCommand == nil && service.conversationHistory.isEmpty, "Escape at caller continuation left hidden confirmation or intent")+ self.check(owner.pendingVoiceCommandLifecycleID == nil && owner.menuBarManager.updates == [true], "Canceled continuation published pending owner or late UI")+ await service.processUserCommand("next typed request")+ self.check(service.conversationHistory.last?.content == "Done", "Race cleanup left future commands blocked")+ } else {+ self.check(service.pendingCommand != nil && owner.pendingVoiceCommandLifecycleID == 7, "Valid voice confirmation lost ownership")+ self.check(owner.menuBarManager.updates == [true, false], "Valid continuation failed to finish processing UI")+ }+ }+ }++ static func notchInputClearsOnlyAcceptedText() async {+ for accepted in [true, false] {+ for editsDraft in [true, false] {+ let owner = NotchInputOwner()+ owner.inputText = "follow-up"+ var resume: CheckedContinuation<Bool, Never>?+ var returned = false+ owner.onSubmit = { text in+ self.check(text == "follow-up", "Notch submitted the wrong draft")+ let result = await withCheckedContinuation { resume = $0 }+ returned = true+ return result+ }+ owner.submitFollowUp()+ await self.waitFor { resume != nil }+ self.check(owner.inputText == "follow-up", "Notch erased text before acceptance")+ if editsDraft { owner.inputText = "new draft" }+ resume?.resume(returning: accepted)+ await self.waitFor { returned }+ for _ in 0..<10 {+ await Task.yield()+ }+ let expected = editsDraft ? "new draft" : (accepted ? "" : "follow-up")+ self.check(owner.inputText == expected, "Notch lost rejected or newly edited text")+ }+ }+ }+static func invalidRequestDoesNothing() async {let service = self.fixture()let messages = service.conversationHistorydiff --git a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swiftindex 35aaea8d..929335f7 100644--- a/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift+++ b/Tests/FluidDictationIntegrationTests/DirectAudioReliabilityTests.swift@@ -1000,6 +1000,18 @@ final class DirectAudioReliabilityTests: XCTestCase {XCTAssertTrue(command.contains("self.pendingVoiceCommandLifecycleID = self.commandModeService.pendingCommand == nil ? nil : lifecycleID"))}+ func testCommandFollowUpAcceptanceReachesNotchWithoutDroppingDraft() 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("let accepted = await commandModeService.processFollowUpCommand(text)"))+ XCTAssertTrue(source.contains("if !accepted, commandModeService.pendingCommand != nil"))+ XCTAssertTrue(source.contains("self.asr.errorTitle = \"Command Awaiting Approval\""))+ let overlay = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/Services/NotchOverlayManager.swift"), encoding: .utf8)+ XCTAssertTrue(overlay.contains("return await self.onCommandFollowUp?(text) ?? false"))+ let command = try XCTUnwrap(source.components(separatedBy: "private func processCommandWithVoice(").last?.components(separatedBy: "/// Capture app context").first)+ XCTAssertTrue(command.contains("guard isOutputValid() else {\n self.commandModeService.cancelInvalidPendingCommand()"))+ }+func testCancelledProcessingCannotPublishDelayedOverlayOrPracticeResult() throws {let root = URL(fileURLWithPath: #filePath).deletingLastPathComponent().deletingLastPathComponent().deletingLastPathComponent()let source = try String(contentsOf: root.appendingPathComponent("Sources/Fluid/ContentView.swift"), encoding: .utf8)diff --git a/Tests/run_command_cancellation_tests.sh b/Tests/run_command_cancellation_tests.shindex 4ab3a9b5..bb552e85 100644--- a/Tests/run_command_cancellation_tests.sh+++ b/Tests/run_command_cancellation_tests.sh@@ -9,11 +9,24 @@ fiexport DEVELOPER_DIR="$task_developer_dir"task_test_dir=$(mktemp -d /tmp/fluidvoice-command-cancellation.XXXXXX)trap 'rm -rf "$task_test_dir"' EXIT+# Include the actual voice continuation and notch submit methods to cover their await boundaries.+python3 - "$task_test_dir/CommandUI.swift" <<'PYCODE'+from pathlib import Path+import sys+voice = Path('Sources/Fluid/ContentView.swift').read_text()+a = voice.index(' private func processCommandWithVoice(')+b = voice.index(' /// Capture app context', a)+notch = Path('Sources/Fluid/Views/NotchContentViews.swift').read_text()+c = notch.index(' private func submitFollowUp()')+d = notch.index('\n}\n', c)+Path(sys.argv[1]).write_text('import Foundation\n@MainActor extension VoiceCommandOwner {\n' + voice[a:b].replace('private func', 'func', 1) + '}\n@MainActor extension NotchInputOwner {\n' + notch[c:d].replace('private func', 'func', 1) + '\n}\n')+PYCODE# 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 \+ "$task_test_dir/CommandUI.swift" \-o "$task_test_dir/cancellation-tests""$task_test_dir/cancellation-tests"