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
Added baseline for command mode + write mode
altic-dev8ee1a9ad4fef
diff --git a/.gitignore b/.gitignoreindex b832d67f..a173bb56 100644--- a/.gitignore+++ b/.gitignore@@ -183,4 +183,16 @@ SettingsStore.xcuserstate**/.vscode/.mcp_temp/++# Build and release scripts (developer-specific)+build_dev.sh+build_and_notarize.shrelease.sh+++RELEASE_NOTES_*+.cursor+**.wav++# Documentation backups (for future reference, not needed in repo)+docs/\ No newline at end of filediff --git a/Info.plist b/Info.plistindex 42bdc392..38a21be0 100644--- a/Info.plist+++ b/Info.plist@@ -11,7 +11,7 @@<key>CFBundleVersion</key><string>1</string><key>CFBundleShortVersionString</key>- <string>1.4.1</string>+ <string>1.4.2</string><key>LSMinimumSystemVersion</key><string>$(MACOSX_DEPLOYMENT_TARGET)</string><key>LSApplicationCategoryType</key>diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 523921d5..95dc9405 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -28,6 +28,8 @@ enum SidebarItem: Hashable {case meetingToolscase statscase feedback+ case commandMode+ case rewriteMode}// MARK: - Listening Overlay View (using modular components)@@ -77,6 +79,8 @@ struct ContentView: View {@StateObject private var audioObserver = AudioHardwareObserver()@StateObject private var asr = ASRService()@StateObject private var mouseTracker = MousePositionTracker()+ @StateObject private var commandModeService = CommandModeService()+ @StateObject private var rewriteModeService = RewriteModeService()@EnvironmentObject private var menuBarManager: MenuBarManager@Environment(\.theme) private var theme@State private var hotkeyManager: GlobalHotkeyManager? = nil@@ -85,7 +89,12 @@ struct ContentView: View {@State private var appear = false@State private var accessibilityEnabled = false@State private var hotkeyShortcut: HotkeyShortcut = SettingsStore.shared.hotkeyShortcut+ @State private var commandModeHotkeyShortcut: HotkeyShortcut = SettingsStore.shared.commandModeHotkeyShortcut+ @State private var rewriteModeHotkeyShortcut: HotkeyShortcut = SettingsStore.shared.rewriteModeHotkeyShortcut+ @State private var isRecordingForRewrite: Bool = false // Track if current recording is for rewrite mode+ @State private var isRecordingForCommand: Bool = false // Track if current recording is for command mode@State private var isRecordingShortcut = false+ @State private var isRecordingRewriteShortcut = false@State private var pendingModifierFlags: NSEvent.ModifierFlags = []@State private var pendingModifierKeyCode: UInt16?@State private var pendingModifierOnly = false@@ -94,6 +103,9 @@ struct ContentView: View {@State private var selectedSidebarItem: SidebarItem? = .welcome@State private var playgroundUsed: Bool = SettingsStore.shared.playgroundUsed@State private var recordingAppInfo: (name: String, bundleId: String, windowTitle: String)? = nil++ // Command Mode State+ // @State private var showCommandMode: Bool = false// Audio Settings Tab State@State private var visualizerNoiseThreshold: Double = SettingsStore.shared.visualizerNoiseThreshold@@ -302,7 +314,8 @@ struct ContentView: View {let eventModifiers = event.modifierFlags.intersection([.function, .command, .option, .control, .shift])let shortcutModifiers = hotkeyShortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])- DebugLogger.shared.debug("NSEvent \(event.type) keyCode=\(event.keyCode) recordingShortcut=\(isRecordingShortcut)", source: "ContentView")+ let isRecordingAnyShortcut = isRecordingShortcut || isRecordingRewriteShortcut+ DebugLogger.shared.debug("NSEvent \(event.type) keyCode=\(event.keyCode) recordingShortcut=\(isRecordingShortcut) recordingRewrite=\(isRecordingRewriteShortcut)", source: "ContentView")if event.type == .keyDown {if event.keyCode == hotkeyShortcut.keyCode && eventModifiers == shortcutModifiers {@@ -310,7 +323,7 @@ struct ContentView: View {return event}- guard isRecordingShortcut else {+ guard isRecordingAnyShortcut else {if event.keyCode == 53 && asr.isRunning {DebugLogger.shared.debug("NSEvent monitor: Escape pressed, cancelling ASR recording", source: "ContentView")asr.stopWithoutTranscription()@@ -324,6 +337,7 @@ struct ContentView: View {if keyCode == 53 {DebugLogger.shared.debug("NSEvent monitor: Escape pressed, cancelling shortcut recording", source: "ContentView")isRecordingShortcut = false+ isRecordingRewriteShortcut = falseresetPendingShortcutState()return nil}@@ -331,12 +345,20 @@ struct ContentView: View {let combinedModifiers = pendingModifierFlags.union(eventModifiers)let newShortcut = HotkeyShortcut(keyCode: keyCode, modifierFlags: combinedModifiers)DebugLogger.shared.debug("NSEvent monitor: Recording new shortcut: \(newShortcut.displayString)", source: "ContentView")- hotkeyShortcut = newShortcut- SettingsStore.shared.hotkeyShortcut = newShortcut- hotkeyManager?.updateShortcut(newShortcut)- isRecordingShortcut = false++ if isRecordingRewriteShortcut {+ rewriteModeHotkeyShortcut = newShortcut+ SettingsStore.shared.rewriteModeHotkeyShortcut = newShortcut+ hotkeyManager?.updateRewriteModeShortcut(newShortcut)+ isRecordingRewriteShortcut = false+ } else {+ hotkeyShortcut = newShortcut+ SettingsStore.shared.hotkeyShortcut = newShortcut+ hotkeyManager?.updateShortcut(newShortcut)+ isRecordingShortcut = false+ }resetPendingShortcutState()- DebugLogger.shared.debug("NSEvent monitor: Finished recording shortcut, isRecordingShortcut set to false", source: "ContentView")+ DebugLogger.shared.debug("NSEvent monitor: Finished recording shortcut", source: "ContentView")return nil} else if event.type == .flagsChanged {if hotkeyShortcut.modifierFlags.isEmpty {@@ -347,7 +369,7 @@ struct ContentView: View {}}- guard isRecordingShortcut else {+ guard isRecordingAnyShortcut else {resetPendingShortcutState()return event}@@ -356,12 +378,20 @@ struct ContentView: View {if pendingModifierOnly, let modifierKeyCode = pendingModifierKeyCode {let newShortcut = HotkeyShortcut(keyCode: modifierKeyCode, modifierFlags: [])DebugLogger.shared.debug("NSEvent monitor: Recording modifier-only shortcut: \(newShortcut.displayString)", source: "ContentView")- hotkeyShortcut = newShortcut- SettingsStore.shared.hotkeyShortcut = newShortcut- hotkeyManager?.updateShortcut(newShortcut)- isRecordingShortcut = false++ if isRecordingRewriteShortcut {+ rewriteModeHotkeyShortcut = newShortcut+ SettingsStore.shared.rewriteModeHotkeyShortcut = newShortcut+ hotkeyManager?.updateRewriteModeShortcut(newShortcut)+ isRecordingRewriteShortcut = false+ } else {+ hotkeyShortcut = newShortcut+ SettingsStore.shared.hotkeyShortcut = newShortcut+ hotkeyManager?.updateShortcut(newShortcut)+ isRecordingShortcut = false+ }resetPendingShortcutState()- DebugLogger.shared.debug("NSEvent monitor: Finished recording modifier shortcut, isRecordingShortcut set to false", source: "ContentView")+ DebugLogger.shared.debug("NSEvent monitor: Finished recording modifier shortcut", source: "ContentView")return nil}@@ -501,6 +531,16 @@ struct ContentView: View {Label("Preferences", systemImage: "gearshape.fill").font(.system(size: 15, weight: .medium))}++ NavigationLink(value: SidebarItem.commandMode) {+ Label("Command Mode", systemImage: "terminal.fill")+ .font(.system(size: 15, weight: .medium))+ }++ NavigationLink(value: SidebarItem.rewriteMode) {+ Label("Rewrite Mode", systemImage: "pencil.and.outline")+ .font(.system(size: 15, weight: .medium))+ }NavigationLink(value: SidebarItem.meetingTools) {Label("File Transcription", systemImage: "doc.text.fill")@@ -553,6 +593,10 @@ struct ContentView: View {statsViewcase .feedback:feedbackView+ case .commandMode:+ commandModeView+ case .rewriteMode:+ rewriteModeView}}.transition(.opacity)@@ -697,6 +741,8 @@ struct ContentView: View {accessibilityEnabled: $accessibilityEnabled,hotkeyShortcut: $hotkeyShortcut,isRecordingShortcut: $isRecordingShortcut,+ rewriteShortcut: $rewriteModeHotkeyShortcut,+ isRecordingRewriteShortcut: $isRecordingRewriteShortcut,hotkeyManagerInitialized: $hotkeyManagerInitialized,pressAndHoldModeEnabled: $pressAndHoldModeEnabled,enableStreamingPreview: $enableStreamingPreview,@@ -720,6 +766,18 @@ struct ContentView: View {startRecording: startRecording)}++ private var commandModeView: some View {+ CommandModeView(service: commandModeService, asr: asr, onClose: {+ self.selectedSidebarItem = .welcome+ })+ }++ private var rewriteModeView: some View {+ RewriteModeView(service: rewriteModeService, asr: asr, onClose: {+ self.selectedSidebarItem = .welcome+ })+ }// MARK: - AI Settings Tabprivate var aiSettingsView: some View {@@ -752,11 +810,11 @@ struct ContentView: View {// Model status indicator with action buttonsHStack(spacing: 12) {- if asr.isDownloadingModel {+ if asr.isDownloadingModel || asr.isLoadingModel {HStack(spacing: 8) {ProgressView().controlSize(.small)- Text("Downloading…")+ Text(asr.isLoadingModel ? "Loading model…" : "Downloading…").font(.caption).foregroundStyle(.secondary)}@@ -824,9 +882,14 @@ struct ContentView: View {))- // Download warning message- if asr.isDownloadingModel {- Text("Download might take a while...")+ // Loading/Download status message+ if asr.isLoadingModel {+ Text("Loading model into memory (30-60 sec)...")+ .font(.caption2)+ .foregroundStyle(.secondary)+ .padding(.leading, 4)+ } else if asr.isDownloadingModel {+ Text("Downloading model (~500MB)...").font(.caption2).foregroundStyle(.secondary).padding(.leading, 4)@@ -1855,7 +1918,7 @@ struct ContentView: View {private func providerKey(for providerID: String) -> String {if providerID == "openai" || providerID == "groq" { return providerID }// Saved providers use their stable id- return providerID.isEmpty ? currentProvider : "custom:\\(providerID)"+ return providerID.isEmpty ? currentProvider : "custom:\(providerID)"}private func defaultModels(for providerKey: String) -> [String] {@@ -2215,6 +2278,18 @@ struct ContentView: View {private func stopAndProcessTranscription() async {DebugLogger.shared.debug("stopAndProcessTranscription called", source: "ContentView")+ // Check if we're in rewrite or command mode+ let wasRewriteMode = isRecordingForRewrite+ let wasCommandMode = isRecordingForCommand+ if wasRewriteMode {+ isRecordingForRewrite = false+ menuBarManager.setOverlayMode(.dictation) // Reset overlay mode+ }+ if wasCommandMode {+ isRecordingForCommand = false+ menuBarManager.setOverlayMode(.dictation) // Reset overlay mode+ }+// Stop the ASR service and wait for transcription to completelet transcribedText = await asr.stop()@@ -2223,6 +2298,20 @@ struct ContentView: View {return}+ // If this was a rewrite recording, process the rewrite instead of typing+ if wasRewriteMode {+ DebugLogger.shared.info("Processing rewrite with instruction: \(transcribedText)", source: "ContentView")+ await processRewriteWithVoiceInstruction(transcribedText)+ return+ }++ // If this was a command recording, process the command+ if wasCommandMode {+ DebugLogger.shared.info("Processing command: \(transcribedText)", source: "ContentView")+ await processCommandWithVoice(transcribedText)+ return+ }+let finalText: String// Check if we should use AI processing@@ -2261,6 +2350,48 @@ struct ContentView: View {}}}++ // MARK: - Rewrite Mode Voice Processing+ private func processRewriteWithVoiceInstruction(_ instruction: String) async {+ DebugLogger.shared.info("Processing rewrite - instruction: '\(instruction)', originalText length: \(rewriteModeService.originalText.count)", source: "ContentView")++ guard !rewriteModeService.originalText.isEmpty else {+ DebugLogger.shared.warning("No original text captured for rewrite", source: "ContentView")+ return+ }++ // Process the rewrite request+ await rewriteModeService.processRewriteRequest(instruction)++ // If rewrite was successful, type the result+ if !rewriteModeService.rewrittenText.isEmpty {+ DebugLogger.shared.info("Rewrite successful, typing result (chars: \(rewriteModeService.rewrittenText.count))", source: "ContentView")++ // Copy to clipboard as backup+ if SettingsStore.shared.copyTranscriptionToClipboard {+ ClipboardService.copyToClipboard(rewriteModeService.rewrittenText)+ }++ // Type the rewritten text+ asr.typeTextToActiveField(rewriteModeService.rewrittenText)++ // Clear the rewrite service state for next use+ rewriteModeService.clearState()+ } else {+ DebugLogger.shared.error("Rewrite failed - no result", source: "ContentView")+ }+ }++ // MARK: - Command Mode Voice Processing+ private func processCommandWithVoice(_ command: String) async {+ DebugLogger.shared.info("Processing voice command: '\(command)'", source: "ContentView")++ // Process the command through CommandModeService+ // This stores the conversation history and executes any terminal commands+ await commandModeService.processUserCommand(command)++ DebugLogger.shared.info("Command processed, conversation stored in Command Mode", source: "ContentView")+ }// Capture app context at start to avoid mismatches if the user switches apps mid-sessionprivate func startRecording() {@@ -2571,12 +2702,16 @@ struct ContentView: View {}private func getModelStatusText() -> String {- if asr.isDownloadingModel {- return "Model is downloading... Please wait."+ if asr.isLoadingModel {+ return "Loading model into memory... (30-60 sec)"+ } else if asr.isDownloadingModel {+ return "Downloading model... Please wait."} else if asr.isAsrReady {return "Model is ready to use!"+ } else if asr.modelsExistOnDisk {+ return "Model cached. Will load on first use."} else {- return "Model will auto-download when needed (or click Download Model Now)."+ return "Model will download when needed."}}@@ -2744,19 +2879,56 @@ struct ContentView: View {}}- // MARK: - Hotkey Manager Initialization Helpersprivate func initializeHotkeyManagerIfNeeded() {guard hotkeyManager == nil else { return }- if UserDefaults.standard.bool(forKey: "enableDebugLogs") {- print("[ContentView] Initializing hotkey manager with accessibility enabled: \(accessibilityEnabled)")- }+ hotkeyManager = GlobalHotkeyManager(+ asrService: asr,+ shortcut: hotkeyShortcut,+ commandModeShortcut: commandModeHotkeyShortcut,+ rewriteModeShortcut: rewriteModeHotkeyShortcut,+ stopAndProcessCallback: {+ await stopAndProcessTranscription()+ },+ commandModeCallback: {+ DebugLogger.shared.info("Command mode triggered", source: "ContentView")++ // Set flag so stopAndProcessTranscription knows to process as command+ self.isRecordingForCommand = true++ // Set overlay mode to command+ self.menuBarManager.setOverlayMode(.command)++ // Start recording immediately for the command+ DebugLogger.shared.info("Starting voice recording for command", source: "ContentView")+ self.asr.start()+ },+ rewriteModeCallback: {+ // Capture text first while still in the other app+ let captured = self.rewriteModeService.captureSelectedText()+ DebugLogger.shared.info("Rewrite mode triggered, text captured: \(captured)", source: "ContentView")++ guard captured else {+ DebugLogger.shared.warning("No text captured for rewrite", source: "ContentView")+ self.menuBarManager.showToast("No text selected")+ return+ }++ // Set flag so stopAndProcessTranscription knows to process as rewrite+ self.isRecordingForRewrite = true++ // Set overlay mode to rewrite+ self.menuBarManager.setOverlayMode(.rewrite)++ // Start recording immediately for the rewrite instruction+ DebugLogger.shared.info("Starting voice recording for rewrite instruction", source: "ContentView")+ self.asr.start()+ }+ )++ hotkeyManagerInitialized = hotkeyManager?.validateEventTapHealth() ?? false- hotkeyManager = GlobalHotkeyManager(asrService: asr, shortcut: hotkeyShortcut)hotkeyManager?.enablePressAndHoldMode(pressAndHoldModeEnabled)- hotkeyManager?.setStopAndProcessCallback {- await self.stopAndProcessTranscription()- }// Monitor initialization statusTask {@@ -2771,10 +2943,18 @@ struct ContentView: View {// If still not initialized and accessibility is enabled, try reinitializingif !self.hotkeyManagerInitialized && self.accessibilityEnabled {+ self.hotkeyManagerInitialized = self.hotkeyManager?.validateEventTapHealth() ?? falseif UserDefaults.standard.bool(forKey: "enableDebugLogs") {- print("[ContentView] Hotkey manager not healthy, attempting reinitalization")+ print("[ContentView] Initial hotkey manager health check: \(self.hotkeyManagerInitialized)")+ }++ // If still not initialized and accessibility is enabled, try reinitializing+ if !self.hotkeyManagerInitialized && self.accessibilityEnabled {+ if UserDefaults.standard.bool(forKey: "enableDebugLogs") {+ print("[ContentView] Hotkey manager not healthy, attempting reinitalization")+ }+ self.hotkeyManager?.reinitialize()}- self.hotkeyManager?.reinitialize()}}}diff --git a/Sources/Fluid/Networking/FunctionCallingProvider.swift b/Sources/Fluid/Networking/FunctionCallingProvider.swiftnew file mode 100644index 00000000..50b55bf9--- /dev/null+++ b/Sources/Fluid/Networking/FunctionCallingProvider.swift@@ -0,0 +1,360 @@+import Foundation++/// Extends OpenAI-compatible API to support function calling with MCP tools+final class FunctionCallingProvider {++ struct FunctionCall: Codable {+ let name: String+ let arguments: String // JSON string+ }++ struct ToolCall: Codable {+ let id: String+ let type: String+ let function: FunctionCall+ }++ struct ChatMessage: Codable {+ let role: String+ let content: String?+ let tool_calls: [ToolCall]?+ let tool_call_id: String?+ let name: String?++ init(role: String, content: String?, tool_calls: [ToolCall]? = nil, tool_call_id: String? = nil, name: String? = nil) {+ self.role = role+ self.content = content+ self.tool_calls = tool_calls+ self.tool_call_id = tool_call_id+ self.name = name+ }+ }++ struct ChatRequest: Encodable {+ let model: String+ let messages: [ChatMessage]+ let temperature: Double?+ let tools: [[String: Any]]?+ let tool_choice: String?++ enum CodingKeys: String, CodingKey {+ case model, messages, temperature, tools, tool_choice+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.container(keyedBy: CodingKeys.self)+ try container.encode(model, forKey: .model)+ try container.encode(messages, forKey: .messages)+ try container.encodeIfPresent(temperature, forKey: .temperature)+ try container.encodeIfPresent(tool_choice, forKey: .tool_choice)++ if let tools = tools {+ let toolsData = try JSONSerialization.data(withJSONObject: tools)+ let toolsArray = try JSONDecoder().decode([AnyCodable].self, from: toolsData)+ try container.encode(toolsArray, forKey: .tools)+ }+ }+ }++ struct ChatChoice: Codable {+ let index: Int?+ let message: ChatMessage+ let finish_reason: String?+ }++ struct ChatResponse: Codable {+ let choices: [ChatChoice]+ }++ // Helper for encoding/decoding Any+ struct AnyCodable: Codable {+ let value: Any++ init(_ value: Any) {+ self.value = value+ }++ init(from decoder: Decoder) throws {+ let container = try decoder.singleValueContainer()+ if let dict = try? container.decode([String: AnyCodable].self) {+ value = dict.mapValues { $0.value }+ } else if let array = try? container.decode([AnyCodable].self) {+ value = array.map { $0.value }+ } else if let string = try? container.decode(String.self) {+ value = string+ } else if let int = try? container.decode(Int.self) {+ value = int+ } else if let double = try? container.decode(Double.self) {+ value = double+ } else if let bool = try? container.decode(Bool.self) {+ value = bool+ } else {+ value = NSNull()+ }+ }++ func encode(to encoder: Encoder) throws {+ var container = encoder.singleValueContainer()+ if let dict = value as? [String: Any] {+ try container.encode(dict.mapValues { AnyCodable($0) })+ } else if let array = value as? [Any] {+ try container.encode(array.map { AnyCodable($0) })+ } else if let string = value as? String {+ try container.encode(string)+ } else if let int = value as? Int {+ try container.encode(int)+ } else if let double = value as? Double {+ try container.encode(double)+ } else if let bool = value as? Bool {+ try container.encode(bool)+ } else {+ try container.encodeNil()+ }+ }+ }++ /// Result of LLM processing - either a text response or tool calls+ enum LLMResult {+ case textResponse(String)+ case toolCalls([(name: String, arguments: [String: Any], callId: String)])+ case error(String)+ }++ // Helper function to detect if the endpoint is local+ private func isLocalEndpoint(_ urlString: String) -> Bool {+ guard let url = URL(string: urlString),+ let host = url.host else { return false }++ let hostLower = host.lowercased()++ // Check for localhost variations+ if hostLower == "localhost" || hostLower == "127.0.0.1" {+ return true+ }++ // Check for private IP ranges+ if hostLower.hasPrefix("127.") || hostLower.hasPrefix("10.") ||+ hostLower.hasPrefix("192.168.") {+ return true+ }++ // 172.16.x.x - 172.31.x.x+ if hostLower.hasPrefix("172.") {+ let components = hostLower.split(separator: ".")+ if components.count >= 2,+ let secondOctet = Int(components[1]),+ secondOctet >= 16 && secondOctet <= 31 {+ return true+ }+ }++ return false+ }++ /// Process user input with LLM and MCP tools+ func processWithTools(+ userText: String,+ conversationHistory: [ChatMessage],+ tools: [[String: Any]],+ model: String,+ apiKey: String,+ baseURL: String+ ) async -> LLMResult {+ let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?+ "https://api.openai.com/v1" : baseURL.trimmingCharacters(in: .whitespacesAndNewlines)++ // Build the full URL+ let fullEndpoint: String+ if endpoint.contains("/chat/completions") ||+ endpoint.contains("/api/chat") ||+ endpoint.contains("/api/generate") {+ fullEndpoint = endpoint+ } else {+ fullEndpoint = endpoint + "/chat/completions"+ }++ guard let url = URL(string: fullEndpoint) else {+ return .error("Invalid Base URL")+ }++ let isLocal = isLocalEndpoint(endpoint)++ // Build messages array+ var messages = conversationHistory+ messages.append(ChatMessage(role: "user", content: userText))++ let body = ChatRequest(+ model: model,+ messages: messages,+ temperature: 0.2,+ tools: tools.isEmpty ? nil : tools,+ tool_choice: tools.isEmpty ? nil : "auto"+ )++ DebugLogger.shared.info("📤 Sending to LLM: \(tools.count) tools, model: \(model)", source: "FunctionCallingProvider")+ if !tools.isEmpty {+ DebugLogger.shared.info("Tools in request: \(tools.map { ($0["function"] as? [String: Any])?["name"] as? String ?? "?" }.joined(separator: ", "))", source: "FunctionCallingProvider")+ }++ guard let jsonData = try? JSONEncoder().encode(body) else {+ DebugLogger.shared.error("Failed to encode request", source: "FunctionCallingProvider")+ return .error("Failed to encode request")+ }++ // Debug: Log request payload+ if let requestString = String(data: jsonData, encoding: .utf8) {+ DebugLogger.shared.debug("Request JSON: \(requestString)", source: "FunctionCallingProvider")+ }++ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")++ // Only add Authorization header for non-local endpoints+ if !isLocal {+ request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")+ }++ request.httpBody = jsonData++ do {+ let (data, response) = try await URLSession.shared.data(for: request)++ // Log response+ if let responseString = String(data: data, encoding: .utf8) {+ DebugLogger.shared.debug("📥 LLM Response: \(responseString)", source: "FunctionCallingProvider")+ }++ if let http = response as? HTTPURLResponse, http.statusCode >= 400 {+ let errText = String(data: data, encoding: .utf8) ?? "Unknown error"+ DebugLogger.shared.error("HTTP \(http.statusCode): \(errText)", source: "FunctionCallingProvider")+ return .error("HTTP \(http.statusCode): \(errText)")+ }++ let decoded = try JSONDecoder().decode(ChatResponse.self, from: data)+ guard let choice = decoded.choices.first else {+ DebugLogger.shared.error("No choices in LLM response", source: "FunctionCallingProvider")+ return .error("No response from LLM")+ }++ let message = choice.message++ // Check if LLM wants to call tools+ if let toolCalls = message.tool_calls, !toolCalls.isEmpty {+ DebugLogger.shared.info("🎯 LLM decided to call \(toolCalls.count) tools", source: "FunctionCallingProvider")+ var parsedCalls: [(name: String, arguments: [String: Any], callId: String)] = []++ for toolCall in toolCalls {+ DebugLogger.shared.info(" → \(toolCall.function.name)(\(toolCall.function.arguments))", source: "FunctionCallingProvider")+ // Parse arguments JSON string+ if let argsData = toolCall.function.arguments.data(using: .utf8),+ let argsDict = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any] {+ parsedCalls.append((+ name: toolCall.function.name,+ arguments: argsDict,+ callId: toolCall.id+ ))+ }+ }++ return .toolCalls(parsedCalls)+ }++ // Otherwise, return text response+ DebugLogger.shared.info("💭 LLM responded with text only (finish_reason: \(choice.finish_reason ?? "none"))", source: "FunctionCallingProvider")+ return .textResponse(message.content ?? "<no content>")++ } catch {+ DebugLogger.shared.error("❌ Function calling failed: \(error.localizedDescription)", source: "FunctionCallingProvider")+ return .error(error.localizedDescription)+ }+ }++ /// Continue conversation after tool execution+ func continueWithToolResults(+ conversationHistory: [ChatMessage],+ toolResults: [(callId: String, toolName: String, result: String)],+ model: String,+ apiKey: String,+ baseURL: String+ ) async -> LLMResult {+ let endpoint = baseURL.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty ?+ "https://api.openai.com/v1" : baseURL.trimmingCharacters(in: .whitespacesAndNewlines)++ let fullEndpoint: String+ if endpoint.contains("/chat/completions") ||+ endpoint.contains("/api/chat") ||+ endpoint.contains("/api/generate") {+ fullEndpoint = endpoint+ } else {+ fullEndpoint = endpoint + "/chat/completions"+ }++ guard let url = URL(string: fullEndpoint) else {+ return .error("Invalid Base URL")+ }++ let isLocal = isLocalEndpoint(endpoint)++ // Use conversation history as-is (tool messages should already be added by caller)+ let messages = conversationHistory++ // Don't pass tools or tool_choice in the final response request+ // Some providers (like OpenAI) reject tool_choice when tools is nil+ let body = ChatRequest(+ model: model,+ messages: messages,+ temperature: 0.2,+ tools: nil,+ tool_choice: nil+ )++ guard let jsonData = try? JSONEncoder().encode(body) else {+ return .error("Failed to encode request")+ }++ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")++ if !isLocal {+ request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")+ }++ request.httpBody = jsonData++ do {+ let (data, response) = try await URLSession.shared.data(for: request)++ if let http = response as? HTTPURLResponse, http.statusCode >= 400 {+ let errText = String(data: data, encoding: .utf8) ?? "Unknown error"+ DebugLogger.shared.error("HTTP \(http.statusCode) in continueWithToolResults: \(errText)", source: "FunctionCallingProvider")+ return .error("HTTP \(http.statusCode): \(errText)")+ }++ let decoded = try JSONDecoder().decode(ChatResponse.self, from: data)+ guard let choice = decoded.choices.first else {+ return .error("No response from LLM")+ }++ // If the model tries to call tools again despite tool_choice being "none",+ // just extract the text content or return a generic message+ if let toolCalls = choice.message.tool_calls, !toolCalls.isEmpty {+ DebugLogger.shared.warning("Model tried to call tools in final response (tool_choice was 'none'). Ignoring tool calls.", source: "FunctionCallingProvider")+ // Try to extract any text content if available+ if let content = choice.message.content, !content.isEmpty {+ return .textResponse(content)+ }+ // Otherwise, return a generic success message+ return .textResponse("Task completed successfully.")+ }++ return .textResponse(choice.message.content ?? "<no content>")++ } catch {+ DebugLogger.shared.error("Error in continueWithToolResults: \(error.localizedDescription)", source: "FunctionCallingProvider")+ return .error(error.localizedDescription)+ }+ }+}+diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swiftindex faacab8b..86d00f95 100644--- a/Sources/Fluid/Networking/ModelDownloader.swift+++ b/Sources/Fluid/Networking/ModelDownloader.swift@@ -319,27 +319,24 @@ extension HuggingFaceModelDownloader// Check if new structure existslet hasNewStructure = fm.fileExists(atPath: preprocessorUrl.path) && fm.fileExists(atPath: encoderUrl.path)- let preprocessor: MLModel- let encoder: MLModel+ let melEncoder: MLModelif hasNewStructure {// Load with new structure (separate Preprocessor and Encoder)+ // For FluidAudio API, we use the Encoder as melEncoderprint("[ModelDL] Loading with new model structure (Preprocessor + Encoder)")- preprocessor = try MLModel(contentsOf: preprocessorUrl, configuration: config)- encoder = try MLModel(contentsOf: encoderUrl, configuration: config)+ print("[ModelDL] Using Encoder as melEncoder for FluidAudio API")+ melEncoder = try MLModel(contentsOf: encoderUrl, configuration: config)} else {- // Fallback: Try old structure (MelEncoder as both preprocessor and encoder)+ // Fallback: Try old structure (MelEncoder)let melEncUrl = repoDirectory.appendingPathComponent("MelEncoder.mlmodelc")print("[ModelDL] New structure not found, trying legacy MelEncoder")print("[ModelDL] MelEncoder path: \(melEncUrl.path)")print("[ModelDL] MelEncoder exists: \(fm.fileExists(atPath: melEncUrl.path))")if fm.fileExists(atPath: melEncUrl.path) {- let melEncoder = try MLModel(contentsOf: melEncUrl, configuration: config)- // Use MelEncoder for both preprocessor and encoder- preprocessor = melEncoder- encoder = melEncoder- print("[ModelDL] Using MelEncoder for both preprocessor and encoder (legacy mode)")+ melEncoder = try MLModel(contentsOf: melEncUrl, configuration: config)+ print("[ModelDL] Using MelEncoder (legacy mode)")} else {throw NSError(domain: "ModelDL", code: -1, userInfo: [NSLocalizedDescriptionKey: "Neither new model structure (Preprocessor + Encoder) nor legacy structure (MelEncoder) found"@@ -364,13 +361,10 @@ extension HuggingFaceModelDownloaderif let idx = Int(k) { vocabulary[idx] = v }}- print("[ModelDL] Creating AsrModels (unified v3)")-- // Use the encoder as melEncoder (works with both old and new models)- // When using new model structure (Preprocessor + Encoder), encoder is separate- // When using old structure (MelEncoder), encoder IS the melEncoder+ print("[ModelDL] Creating AsrModels")+return AsrModels(- melEncoder: encoder,+ melEncoder: melEncoder,decoder: decoder,joint: joint,configuration: config,diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex bfad7160..b6b3ed1a 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -2,8 +2,9 @@ import Foundationimport ServiceManagementimport ApplicationServicesimport AppKit+import Combine-final class SettingsStore+final class SettingsStore: ObservableObject{static let shared = SettingsStore()private let defaults = UserDefaults.standard@@ -35,6 +36,16 @@ final class SettingsStorestatic let lastUpdateCheckDate = "LastUpdateCheckDate"static let lastSeenVersion = "LastSeenVersion"static let playgroundUsed = "PlaygroundUsed"++ // Command Mode Keys+ static let commandModeSelectedModel = "CommandModeSelectedModel"+ static let commandModeSelectedProviderID = "CommandModeSelectedProviderID"+ static let commandModeHotkeyShortcut = "CommandModeHotkeyShortcut"+ static let commandModeConfirmBeforeExecute = "CommandModeConfirmBeforeExecute"+ static let commandModeLinkedToGlobal = "CommandModeLinkedToGlobal"++ // Rewrite Mode Keys+ static let rewriteModeHotkeyShortcut = "RewriteModeHotkeyShortcut"}struct SavedProvider: Codable, Identifiable, Hashable@@ -58,49 +69,73 @@ final class SettingsStorevar enableAIProcessing: Bool{get { defaults.bool(forKey: Keys.enableAIProcessing) }- set { defaults.set(newValue, forKey: Keys.enableAIProcessing) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.enableAIProcessing)+ }}var availableModels: [String]{get { (defaults.array(forKey: Keys.availableAIModels) as? [String]) ?? [] }- set { defaults.set(newValue, forKey: Keys.availableAIModels) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.availableAIModels)+ }}var availableModelsByProvider: [String: [String]]{get { (defaults.dictionary(forKey: Keys.availableModelsByProvider) as? [String: [String]]) ?? [:] }- set { defaults.set(newValue, forKey: Keys.availableModelsByProvider) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.availableModelsByProvider)+ }}var enableDebugLogs: Bool{get { defaults.bool(forKey: Keys.enableDebugLogs) }- set { defaults.set(newValue, forKey: Keys.enableDebugLogs) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.enableDebugLogs)+ }}var selectedModel: String?{get { defaults.string(forKey: Keys.selectedAIModel) }- set { defaults.set(newValue, forKey: Keys.selectedAIModel) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.selectedAIModel)+ }}var selectedModelByProvider: [String: String]{get { (defaults.dictionary(forKey: Keys.selectedModelByProvider) as? [String: String]) ?? [:] }- set { defaults.set(newValue, forKey: Keys.selectedModelByProvider) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.selectedModelByProvider)+ }}var providerAPIKeys: [String: String]{get { (defaults.dictionary(forKey: Keys.providerAPIKeys) as? [String: String]) ?? [:] }- set { defaults.set(newValue, forKey: Keys.providerAPIKeys) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.providerAPIKeys)+ }}var selectedProviderID: String{get { defaults.string(forKey: Keys.selectedProviderID) ?? "openai" }- set { defaults.set(newValue, forKey: Keys.selectedProviderID) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.selectedProviderID)+ }}var savedProviders: [SavedProvider]@@ -113,6 +148,7 @@ final class SettingsStore}set{+ objectWillChange.send()if let encoded = try? JSONEncoder().encode(newValue){defaults.set(encoded, forKey: Keys.savedProviders)@@ -133,6 +169,7 @@ final class SettingsStore}set{+ objectWillChange.send()if let data = try? JSONEncoder().encode(newValue){defaults.set(data, forKey: Keys.hotkeyShortcutKey)@@ -140,6 +177,7 @@ final class SettingsStore}}+var pressAndHoldMode: Bool{get { defaults.bool(forKey: Keys.pressAndHoldMode) }@@ -273,6 +311,94 @@ final class SettingsStoreget { defaults.bool(forKey: Keys.playgroundUsed) }set { defaults.set(newValue, forKey: Keys.playgroundUsed) }}++ // MARK: - Command Mode Settings++ var commandModeSelectedModel: String?+ {+ get { defaults.string(forKey: Keys.commandModeSelectedModel) }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.commandModeSelectedModel)+ }+ }++ var commandModeSelectedProviderID: String+ {+ get { defaults.string(forKey: Keys.commandModeSelectedProviderID) ?? "openai" }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.commandModeSelectedProviderID)+ }+ }++ var commandModeLinkedToGlobal: Bool+ {+ get { defaults.bool(forKey: Keys.commandModeLinkedToGlobal) } // Default to false (let user opt-in, or true if preferred)+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.commandModeLinkedToGlobal)+ }+ }++ var commandModeHotkeyShortcut: HotkeyShortcut+ {+ get+ {+ if let data = defaults.data(forKey: Keys.commandModeHotkeyShortcut),+ let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)+ {+ return shortcut+ }+ // Default to Right Command key (keyCode: 54, no modifiers for the key itself)+ return HotkeyShortcut(keyCode: 54, modifierFlags: [])+ }+ set+ {+ objectWillChange.send()+ if let data = try? JSONEncoder().encode(newValue)+ {+ defaults.set(data, forKey: Keys.commandModeHotkeyShortcut)+ }+ }+ }++ var commandModeConfirmBeforeExecute: Bool+ {+ get {+ // Default to true (safer - ask before running commands)+ let value = defaults.object(forKey: Keys.commandModeConfirmBeforeExecute)+ return value as? Bool ?? true+ }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.commandModeConfirmBeforeExecute)+ }+ }++ // MARK: - Rewrite Mode Settings++ var rewriteModeHotkeyShortcut: HotkeyShortcut+ {+ get+ {+ if let data = defaults.data(forKey: Keys.rewriteModeHotkeyShortcut),+ let shortcut = try? JSONDecoder().decode(HotkeyShortcut.self, from: data)+ {+ return shortcut+ }+ // Default to Option+R (keyCode: 15 is R, with Option modifier)+ return HotkeyShortcut(keyCode: 15, modifierFlags: [.option])+ }+ set+ {+ objectWillChange.send()+ if let data = try? JSONEncoder().encode(newValue)+ {+ defaults.set(data, forKey: Keys.rewriteModeHotkeyShortcut)+ }+ }+ }func shouldShowWhatsNew() -> Bool {let currentVersion = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "1.0.0"@@ -354,5 +480,3 @@ final class SettingsStore#endif}}--diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex bdb76265..d4a8f40b 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -57,8 +57,18 @@ final class ASRService: ObservableObject@Published var micStatus: AVAuthorizationStatus = .notDetermined@Published var isAsrReady: Bool = false@Published var isDownloadingModel: Bool = false+ @Published var isLoadingModel: Bool = false // True when loading cached model into memory (not downloading)@Published var modelsExistOnDisk: Bool = false@Published var selectedModel: ModelOption = .parakeetTdt06bV3++ /// Returns a user-friendly status message for model loading state+ var modelStatusMessage: String {+ if isAsrReady { return "Model ready" }+ if isDownloadingModel { return "Downloading model..." }+ if isLoadingModel { return "Loading model into memory..." }+ if modelsExistOnDisk { return "Model cached, needs loading" }+ return "Model not downloaded"+ }enum ModelOption: String, CaseIterable, Identifiable, Hashable{@@ -550,44 +560,58 @@ final class ASRService: ObservableObjectif isAsrReady == false{+ let totalStartTime = Date()do{- DebugLogger.shared.debug("Starting ASR initialization...", source: "ASRService")+ DebugLogger.shared.info("=== ASR INITIALIZATION START ===", source: "ASRService")// Use separate cache directory for v3 modelslet baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()let cacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")- DebugLogger.shared.debug("Model cache directory (v3): \(cacheDir.path)", source: "ASRService")- DebugLogger.shared.debug("Cache directory exists: \(FileManager.default.fileExists(atPath: cacheDir.path))", source: "ASRService")+ let modelsAlreadyCached = FileManager.default.fileExists(atPath: cacheDir.path)++ DebugLogger.shared.info("Model cache directory: \(cacheDir.path)", source: "ASRService")+ DebugLogger.shared.info("Models already cached on disk: \(modelsAlreadyCached)", source: "ASRService")let originalStderr = dup(STDERR_FILENO)let devNull = open("/dev/null", O_WRONLY)dup2(devNull, STDERR_FILENO)close(devNull)- DebugLogger.shared.debug("Using FluidAudio's v3 loader (AsrModels.downloadAndLoad)", source: "ASRService")-// Force v3: remove any v2 cache directory so no fallback occurslet v2CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v2-coreml")if FileManager.default.fileExists(atPath: v2CacheDir.path) {try FileManager.default.removeItem(at: v2CacheDir)- DebugLogger.shared.debug("Removed v2 cache directory to force v3 download", source: "ASRService")+ DebugLogger.shared.debug("Removed v2 cache directory to force v3", source: "ASRService")}+ // Set correct loading state based on whether models are cachedDispatchQueue.main.async {- self.isDownloadingModel = true- DebugLogger.shared.info("Model download flagged as in-progress", source: "ASRService")+ if modelsAlreadyCached {+ self.isLoadingModel = true+ self.isDownloadingModel = false+ DebugLogger.shared.info("📦 LOADING cached model into memory (this takes 30-60 sec)...", source: "ASRService")+ } else {+ self.isDownloadingModel = true+ self.isLoadingModel = false+ DebugLogger.shared.info("⬇️ DOWNLOADING model from Hugging Face...", source: "ASRService")+ }}- DebugLogger.shared.debug("Invoking AsrModels.downloadAndLoad()", source: "ASRService")++ // This call either downloads (if needed) OR just loads from cache+ let downloadStartTime = Date()+ DebugLogger.shared.info("Calling AsrModels.downloadAndLoad()...", source: "ASRService")let models = try await AsrModels.downloadAndLoad()- DebugLogger.shared.info("AsrModels.downloadAndLoad() returned successfully", source: "ASRService")+ let downloadDuration = Date().timeIntervalSince(downloadStartTime)+ DebugLogger.shared.info("✓ AsrModels.downloadAndLoad() completed in \(String(format: "%.1f", downloadDuration)) seconds", source: "ASRService")+DispatchQueue.main.async {self.isDownloadingModel = false+ self.isLoadingModel = falseself.modelsExistOnDisk = true- DebugLogger.shared.info("Model download marked complete", source: "ASRService")}- DebugLogger.shared.debug("FluidAudio models loaded successfully (v3)", source: "ASRService")+ // Initialize AsrManagerif self.asrManager == nil{DebugLogger.shared.debug("Creating new AsrManager...", source: "ASRService")@@ -595,25 +619,27 @@ final class ASRService: ObservableObject}if let manager = self.asrManager{- DebugLogger.shared.debug("Initializing AsrManager with models...", source: "ASRService")+ let initStartTime = Date()+ DebugLogger.shared.info("Initializing AsrManager with loaded models...", source: "ASRService")try await manager.initialize(models: models)- DebugLogger.shared.debug("AsrManager initialized successfully", source: "ASRService")- }+ let initDuration = Date().timeIntervalSince(initStartTime)+ DebugLogger.shared.info("✓ AsrManager.initialize() completed in \(String(format: "%.1f", initDuration)) seconds", source: "ASRService")+ }dup2(originalStderr, STDERR_FILENO)close(originalStderr)- DebugLogger.shared.info("ASR initialization completed successfully", source: "ASRService")+ let totalDuration = Date().timeIntervalSince(totalStartTime)+ DebugLogger.shared.info("=== ASR INITIALIZATION COMPLETE ===", source: "ASRService")+ DebugLogger.shared.info("Total initialization time: \(String(format: "%.1f", totalDuration)) seconds", source: "ASRService")}catch{DebugLogger.shared.error("ASR initialization failed with error: \(error)", source: "ASRService")DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")DispatchQueue.main.async {- if self.isDownloadingModel {- DebugLogger.shared.warning("Model download aborted due to error; resetting state", source: "ASRService")- }self.isDownloadingModel = false+ self.isLoadingModel = false}throw error}@@ -631,8 +657,8 @@ final class ASRService: ObservableObjectTask{ [weak self] inguard let self = self else { return }- DebugLogger.shared.debug("Starting model predownload...", source: "ASRService")- await MainActor.run { self.isDownloadingModel = true }+ DebugLogger.shared.info("Starting model predownload...", source: "ASRService")+ // ensureAsrReady handles setting the correct loading/downloading statedo{try await self.ensureAsrReady()@@ -641,23 +667,21 @@ final class ASRService: ObservableObjectcatch{DebugLogger.shared.error("Model predownload failed: \(error)", source: "ASRService")- DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")}- await MainActor.run { self.isDownloadingModel = false }}}func preloadModelAfterSelection() async{- await MainActor.run { self.isDownloadingModel = true }+ // ensureAsrReady handles setting the correct loading/downloading statedo{try await self.ensureAsrReady()}catch{+ DebugLogger.shared.error("Model preload failed: \(error)", source: "ASRService")}- await MainActor.run { self.isDownloadingModel = false }}diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swiftnew file mode 100644index 00000000..2e07c29a--- /dev/null+++ b/Sources/Fluid/Services/CommandModeService.swift@@ -0,0 +1,300 @@+import Foundation+import Combine++@MainActor+final class CommandModeService: ObservableObject {+ @Published var conversationHistory: [Message] = []+ @Published var isProcessing = false+ @Published var pendingCommand: PendingCommand? = nil++ private let terminalService = TerminalService()+ private var currentTurnCount = 0+ private let maxTurns = 15++ // MARK: - Models++ struct Message: Identifiable, Equatable {+ let id = UUID()+ let role: Role+ let content: String+ let toolCall: ToolCall?++ enum Role: Equatable {+ case user+ case assistant+ case tool+ }++ struct ToolCall: Equatable {+ let id: String+ let command: String+ let workingDirectory: String?+ }++ init(role: Role, content: String, toolCall: ToolCall? = nil) {+ self.role = role+ self.content = content+ self.toolCall = toolCall+ }+ }++ struct PendingCommand {+ let id: String+ let command: String+ let workingDirectory: String?+ }++ // MARK: - Public Methods++ func clearHistory() {+ conversationHistory.removeAll()+ pendingCommand = nil+ currentTurnCount = 0+ }++ /// Process user voice/text command+ func processUserCommand(_ text: String) async {+ guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }++ isProcessing = true+ currentTurnCount = 0+ conversationHistory.append(Message(role: .user, content: text))++ await processNextTurn()+ }++ /// Execute pending command (after user confirmation)+ func confirmAndExecute() async {+ guard let pending = pendingCommand else { return }+ pendingCommand = nil+ isProcessing = true++ await executeCommand(pending.command, workingDirectory: pending.workingDirectory, callId: pending.id)+ }++ /// Cancel pending command+ func cancelPendingCommand() {+ pendingCommand = nil+ conversationHistory.append(Message(+ role: .assistant,+ content: "Command cancelled."+ ))+ isProcessing = false+ }++ // MARK: - Agent Loop++ private func processNextTurn() async {+ if currentTurnCount >= maxTurns {+ conversationHistory.append(Message(role: .assistant, content: "I've reached the maximum number of steps. stopping here."))+ isProcessing = false+ return+ }++ currentTurnCount += 1++ do {+ let response = try await callLLM()++ if let toolCall = response.toolCall {+ // AI wants to run a command+ conversationHistory.append(Message(+ role: .assistant,+ content: response.content.isEmpty ? "I'll run this command:" : response.content,+ toolCall: Message.ToolCall(+ id: toolCall.id,+ command: toolCall.command,+ workingDirectory: toolCall.workingDirectory+ )+ ))++ // Check if we need confirmation+ if SettingsStore.shared.commandModeConfirmBeforeExecute {+ pendingCommand = PendingCommand(+ id: toolCall.id,+ command: toolCall.command,+ workingDirectory: toolCall.workingDirectory+ )+ isProcessing = false+ return+ }++ // Auto-execute+ await executeCommand(toolCall.command, workingDirectory: toolCall.workingDirectory, callId: toolCall.id)++ } else {+ // Just a text response, we are done+ conversationHistory.append(Message(role: .assistant, content: response.content))+ isProcessing = false+ }++ } catch {+ conversationHistory.append(Message(+ role: .assistant,+ content: "Error: \(error.localizedDescription)"+ ))+ isProcessing = false+ }+ }++ private func executeCommand(_ command: String, workingDirectory: String?, callId: String) async {+ let result = await terminalService.execute(+ command: command,+ workingDirectory: workingDirectory+ )++ let resultJSON = terminalService.resultToJSON(result)++ // Add tool result to conversation+ conversationHistory.append(Message(+ role: .tool,+ content: resultJSON+ ))++ // Continue the loop - let the AI see the result and decide what to do next+ await processNextTurn()+ }++ // MARK: - LLM Integration++ private struct LLMResponse {+ let content: String+ let toolCall: (id: String, command: String, workingDirectory: String?)?+ }++ private func callLLM() async throws -> LLMResponse {+ let settings = SettingsStore.shared+ let providerID = settings.commandModeLinkedToGlobal ? settings.selectedProviderID : settings.commandModeSelectedProviderID+ let model = (settings.commandModeLinkedToGlobal ? settings.selectedModel : settings.commandModeSelectedModel) ?? "gpt-4o"+ let apiKey = settings.providerAPIKeys[providerID] ?? ""++ let baseURL: String+ if let provider = settings.savedProviders.first(where: { $0.id == providerID }) {+ baseURL = provider.baseURL+ } else if providerID == "groq" {+ baseURL = "https://api.groq.com/openai/v1"+ } else {+ baseURL = "https://api.openai.com/v1"+ }++ // Build conversation+ let systemPrompt = """+ You are an autonomous macOS terminal agent. Your goal is to complete the user's request by executing commands.++ IMPORTANT RULES:+ 1. You can execute shell commands using the 'execute_terminal_command' tool.+ 2. If a command fails, ANALYZE the error output and try to FIX it by running a corrected command.+ 3. You can run multiple commands in sequence to accomplish a task (e.g., make a directory, then create a file).+ 4. Always use full paths when possible.+ 5. For destructive operations (rm, overwrite), ask the user for confirmation first (unless they already gave implied permission).+ 6. When the task is fully complete, respond with a final text summary.+ 7. Keep intermediate text responses concise.++ The user is on macOS with zsh shell.+ """++ var messages: [[String: Any]] = [+ ["role": "system", "content": systemPrompt]+ ]++ // Add conversation history+ var lastToolCallId: String? = nil++ for msg in conversationHistory {+ switch msg.role {+ case .user:+ messages.append(["role": "user", "content": msg.content])+ case .assistant:+ if let tc = msg.toolCall {+ lastToolCallId = tc.id+ messages.append([+ "role": "assistant",+ "content": msg.content,+ "tool_calls": [[+ "id": tc.id,+ "type": "function",+ "function": [+ "name": "execute_terminal_command",+ "arguments": try! String(data: JSONSerialization.data(withJSONObject: [+ "command": tc.command,+ "workingDirectory": tc.workingDirectory ?? ""+ ]), encoding: .utf8)!+ ]+ ]]+ ])+ } else {+ messages.append(["role": "assistant", "content": msg.content])+ }+ case .tool:+ messages.append([+ "role": "tool",+ "content": msg.content,+ "tool_call_id": lastToolCallId ?? "call_unknown"+ ])+ }+ }++ // We assume conversationHistory contains the user's latest message already+++ // Build request+ let body: [String: Any] = [+ "model": model,+ "messages": messages,+ "tools": [TerminalService.toolDefinition],+ "tool_choice": "auto",+ "temperature": 0.1+ ]++ let endpoint = baseURL.hasSuffix("/chat/completions") ? baseURL : "\(baseURL)/chat/completions"+ guard let url = URL(string: endpoint) else {+ throw NSError(domain: "CommandMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])+ }++ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")+ request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")+ request.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (data, response) = try await URLSession.shared.data(for: request)++ if let http = response as? HTTPURLResponse, http.statusCode >= 400 {+ let err = String(data: data, encoding: .utf8) ?? "Unknown error"+ throw NSError(domain: "CommandMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: err])+ }++ guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let choices = json["choices"] as? [[String: Any]],+ let choice = choices.first,+ let message = choice["message"] as? [String: Any] else {+ throw NSError(domain: "CommandMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response"])+ }++ // Check for tool calls+ if let toolCalls = message["tool_calls"] as? [[String: Any]],+ let toolCall = toolCalls.first,+ let function = toolCall["function"] as? [String: Any],+ let name = function["name"] as? String,+ name == "execute_terminal_command",+ let argsString = function["arguments"] as? String,+ let argsData = argsString.data(using: .utf8),+ let args = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any] {++ let command = args["command"] as? String ?? ""+ let workDir = args["workingDirectory"] as? String+ let callId = toolCall["id"] as? String ?? "call_\(UUID().uuidString.prefix(8))"++ return LLMResponse(+ content: message["content"] as? String ?? "",+ toolCall: (id: callId, command: command, workingDirectory: workDir?.isEmpty == true ? nil : workDir)+ )+ }++ // Text response only+ return LLMResponse(+ content: message["content"] as? String ?? "I couldn't understand that.",+ toolCall: nil+ )+ }+}diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swiftindex ae0fda2a..c25ef747 100644--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift@@ -7,22 +7,40 @@ final class GlobalHotkeyManager: NSObjectprivate var runLoopSource: CFRunLoopSource?private let asrService: ASRServiceprivate var shortcut: HotkeyShortcut+ private var commandModeShortcut: HotkeyShortcut+ private var rewriteModeShortcut: HotkeyShortcutprivate var stopAndProcessCallback: (() async -> Void)?+ private var commandModeCallback: (() async -> Void)?+ private var rewriteModeCallback: (() async -> Void)?private var pressAndHoldMode: Bool = SettingsStore.shared.pressAndHoldModeprivate var isKeyPressed = false+ private var isCommandModeKeyPressed = false+ private var isRewriteKeyPressed = falseprivate var isInitialized = falseprivate var initializationTask: Task<Void, Never>?private var healthCheckTask: Task<Void, Never>?- private let maxRetryAttempts = 5- private let retryDelay: TimeInterval = 0.5- private let healthCheckInterval: TimeInterval = 30.0+ private var maxRetryAttempts = 5+ private var retryDelay: TimeInterval = 0.5+ private var healthCheckInterval: TimeInterval = 30.0- init(asrService: ASRService, shortcut: HotkeyShortcut, stopAndProcessCallback: (() async -> Void)? = nil)+ init(+ asrService: ASRService,+ shortcut: HotkeyShortcut,+ commandModeShortcut: HotkeyShortcut,+ rewriteModeShortcut: HotkeyShortcut,+ stopAndProcessCallback: (() async -> Void)? = nil,+ commandModeCallback: (() async -> Void)? = nil,+ rewriteModeCallback: (() async -> Void)? = nil+ ){self.asrService = asrServiceself.shortcut = shortcut+ self.commandModeShortcut = commandModeShortcut+ self.rewriteModeShortcut = rewriteModeShortcutself.stopAndProcessCallback = stopAndProcessCallback+ self.commandModeCallback = commandModeCallback+ self.rewriteModeCallback = rewriteModeCallbacksuper.init()initializeWithDelay()@@ -44,6 +62,34 @@ final class GlobalHotkeyManager: NSObject{self.stopAndProcessCallback = callback}++ func setCommandModeCallback(_ callback: @escaping () async -> Void)+ {+ self.commandModeCallback = callback+ }++ func updateShortcut(_ newShortcut: HotkeyShortcut)+ {+ self.shortcut = newShortcut+ DebugLogger.shared.info("Updated transcription hotkey", source: "GlobalHotkeyManager")+ }++ func updateCommandModeShortcut(_ newShortcut: HotkeyShortcut)+ {+ self.commandModeShortcut = newShortcut+ DebugLogger.shared.info("Updated command mode hotkey", source: "GlobalHotkeyManager")+ }++ func setRewriteModeCallback(_ callback: @escaping () async -> Void)+ {+ self.rewriteModeCallback = callback+ }++ func updateRewriteModeShortcut(_ newShortcut: HotkeyShortcut)+ {+ self.rewriteModeShortcut = newShortcut+ DebugLogger.shared.info("Updated rewrite mode hotkey", source: "GlobalHotkeyManager")+ }private func setupGlobalHotkeyWithRetry() {for attempt in 1...maxRetryAttempts {@@ -160,6 +206,53 @@ final class GlobalHotkeyManager: NSObjectswitch type{case .keyDown:+ // Check command mode hotkey first+ if matchesCommandModeShortcut(keyCode: keyCode, modifiers: eventModifiers)+ {+ if pressAndHoldMode {+ // Press and hold: start on keyDown, stop on keyUp+ if !isCommandModeKeyPressed {+ isCommandModeKeyPressed = true+ DebugLogger.shared.info("Command mode shortcut pressed (hold mode) - starting", source: "GlobalHotkeyManager")+ triggerCommandMode()+ }+ } else {+ // Toggle mode: press to start, press again to stop+ if asrService.isRunning {+ DebugLogger.shared.info("Command mode shortcut pressed while recording - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ } else {+ DebugLogger.shared.info("Command mode shortcut triggered - starting", source: "GlobalHotkeyManager")+ triggerCommandMode()+ }+ }+ return nil+ }++ // Check dedicated rewrite mode hotkey+ if matchesRewriteModeShortcut(keyCode: keyCode, modifiers: eventModifiers)+ {+ if pressAndHoldMode {+ // Press and hold: start on keyDown, stop on keyUp+ if !isRewriteKeyPressed {+ isRewriteKeyPressed = true+ DebugLogger.shared.info("Rewrite mode shortcut pressed (hold mode) - starting", source: "GlobalHotkeyManager")+ triggerRewriteMode()+ }+ } else {+ // Toggle mode: press to start, press again to stop+ if asrService.isRunning {+ DebugLogger.shared.info("Rewrite mode shortcut pressed while recording - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ } else {+ DebugLogger.shared.info("Rewrite mode shortcut triggered - starting", source: "GlobalHotkeyManager")+ triggerRewriteMode()+ }+ }+ return nil+ }++ // Then check transcription hotkeyif matchesShortcut(keyCode: keyCode, modifiers: eventModifiers){if pressAndHoldMode@@ -178,6 +271,25 @@ final class GlobalHotkeyManager: NSObject}case .keyUp:+ // Command mode key up (press and hold mode)+ if pressAndHoldMode && isCommandModeKeyPressed && matchesCommandModeShortcut(keyCode: keyCode, modifiers: eventModifiers)+ {+ isCommandModeKeyPressed = false+ DebugLogger.shared.info("Command mode shortcut released (hold mode) - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ return nil+ }++ // Rewrite mode key up (press and hold mode)+ if pressAndHoldMode && isRewriteKeyPressed && matchesRewriteModeShortcut(keyCode: keyCode, modifiers: eventModifiers)+ {+ isRewriteKeyPressed = false+ DebugLogger.shared.info("Rewrite mode shortcut released (hold mode) - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ return nil+ }++ // Transcription key upif pressAndHoldMode && isKeyPressed && matchesShortcut(keyCode: keyCode, modifiers: eventModifiers){isKeyPressed = false@@ -186,13 +298,74 @@ final class GlobalHotkeyManager: NSObject}case .flagsChanged:- guard shortcut.modifierFlags.isEmpty else { break }-let isModifierPressed = flags.contains(.maskSecondaryFn)|| flags.contains(.maskCommand)|| flags.contains(.maskAlternate)|| flags.contains(.maskControl)|| flags.contains(.maskShift)++ // Check command mode shortcut (if it's a modifier-only shortcut)+ if commandModeShortcut.modifierFlags.isEmpty && keyCode == commandModeShortcut.keyCode+ {+ if isModifierPressed+ {+ if pressAndHoldMode {+ if !isCommandModeKeyPressed {+ isCommandModeKeyPressed = true+ DebugLogger.shared.info("Command mode modifier pressed (hold mode) - starting", source: "GlobalHotkeyManager")+ triggerCommandMode()+ }+ } else {+ // Toggle mode+ if asrService.isRunning {+ DebugLogger.shared.info("Command mode modifier pressed while recording - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ } else {+ DebugLogger.shared.info("Command mode modifier pressed - starting", source: "GlobalHotkeyManager")+ triggerCommandMode()+ }+ }+ } else if pressAndHoldMode && isCommandModeKeyPressed {+ // Key released in press-and-hold mode+ isCommandModeKeyPressed = false+ DebugLogger.shared.info("Command mode modifier released (hold mode) - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ }+ return nil+ }++ // Check rewrite mode shortcut (if it's a modifier-only shortcut)+ if rewriteModeShortcut.modifierFlags.isEmpty && keyCode == rewriteModeShortcut.keyCode+ {+ if isModifierPressed+ {+ if pressAndHoldMode {+ if !isRewriteKeyPressed {+ isRewriteKeyPressed = true+ DebugLogger.shared.info("Rewrite mode modifier pressed (hold mode) - starting", source: "GlobalHotkeyManager")+ triggerRewriteMode()+ }+ } else {+ // Toggle mode+ if asrService.isRunning {+ DebugLogger.shared.info("Rewrite mode modifier pressed while recording - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ } else {+ DebugLogger.shared.info("Rewrite mode modifier pressed - starting", source: "GlobalHotkeyManager")+ triggerRewriteMode()+ }+ }+ } else if pressAndHoldMode && isRewriteKeyPressed {+ // Key released in press-and-hold mode+ isRewriteKeyPressed = false+ DebugLogger.shared.info("Rewrite mode modifier released (hold mode) - stopping", source: "GlobalHotkeyManager")+ stopRecordingIfNeeded()+ }+ return nil+ }++ // Check transcription shortcut (if it's a modifier-only shortcut)+ guard shortcut.modifierFlags.isEmpty else { break }if keyCode == shortcut.keyCode{@@ -225,6 +398,24 @@ final class GlobalHotkeyManager: NSObjectreturn Unmanaged.passUnretained(event)}++ private func triggerCommandMode()+ {+ Task { @MainActor [weak self] in+ guard let self = self else { return }+ DebugLogger.shared.info("Command mode hotkey triggered", source: "GlobalHotkeyManager")+ await self.commandModeCallback?()+ }+ }++ private func triggerRewriteMode()+ {+ Task { @MainActor [weak self] in+ guard let self = self else { return }+ DebugLogger.shared.info("Rewrite mode hotkey triggered", source: "GlobalHotkeyManager")+ await self.rewriteModeCallback?()+ }+ }func enablePressAndHoldMode(_ enable: Bool){@@ -294,24 +485,19 @@ final class GlobalHotkeyManager: NSObjectlet shortcutModifiers = shortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])return keyCode == shortcut.keyCode && relevantModifiers == shortcutModifiers}-- func updateShortcut(_ newShortcut: HotkeyShortcut)++ private func matchesCommandModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool{- shortcut = newShortcut-- if UserDefaults.standard.bool(forKey: "enableDebugLogs") {- print("[GlobalHotkeyManager] Updating shortcut to: \(newShortcut.displayString)")- }-- if setupGlobalHotkey() {- isInitialized = true- if UserDefaults.standard.bool(forKey: "enableDebugLogs") {- print("[GlobalHotkeyManager] Shortcut update successful")- }- startHealthCheckTimer()- } else {- print("[GlobalHotkeyManager] ERROR: Failed to update shortcut")- }+ let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([.function, .command, .option, .control, .shift])+ let shortcutModifiers = commandModeShortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])+ return keyCode == commandModeShortcut.keyCode && relevantModifiers == shortcutModifiers+ }++ private func matchesRewriteModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool+ {+ let relevantModifiers: NSEvent.ModifierFlags = modifiers.intersection([.function, .command, .option, .control, .shift])+ let shortcutModifiers = rewriteModeShortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])+ return keyCode == rewriteModeShortcut.keyCode && relevantModifiers == shortcutModifiers}func isEventTapEnabled() -> Bool {diff --git a/Sources/Fluid/Services/ListeningOverlayController.swift b/Sources/Fluid/Services/ListeningOverlayController.swiftindex a9127e65..9c8d6ffb 100644--- a/Sources/Fluid/Services/ListeningOverlayController.swift+++ b/Sources/Fluid/Services/ListeningOverlayController.swift@@ -1,5 +1,11 @@import AppKit+enum OverlayMode: String {+ case dictation = "Dictation"+ case rewrite = "Rewrite"+ case command = "Command"+}+final class ListeningOverlayController{private var panel: NSPanel?@@ -10,11 +16,18 @@ final class ListeningOverlayControllerprivate var unifiedContainer: NSView?private var orbView: NSView?private var isShowingPreview: Bool = true+ private var modeLabel: NSTextField?+ private var currentMode: OverlayMode = .dictationinit(asrService: ASRService){self.asrService = asrService}++ func setMode(_ mode: OverlayMode) {+ currentMode = mode+ updateModeLabel()+ }func show(with view: NSView, showPreview: Bool = true){@@ -65,6 +78,9 @@ final class ListeningOverlayControllercontainerView.addSubview(view)orbView = view+ // Add mode indicator label (top-right corner, small)+ setupModeLabel(in: containerView, width: width)+// Add text fields to container (at bottom) - only if preview enabledif showPreview {setupTranscriptionTextField(in: containerView)@@ -120,6 +136,71 @@ final class ListeningOverlayControllerself.panel?.orderOut(nil)})}++ /// Show a brief toast message in the overlay area+ func showToast(_ message: String, duration: TimeInterval = 1.5) {+ // Clean up any existing panel+ if let existingPanel = panel {+ existingPanel.orderOut(nil)+ existingPanel.contentView = nil+ panel = nil+ }++ let width: CGFloat = 280+ let height: CGFloat = 50++ let style: NSWindow.StyleMask = [.borderless, .nonactivatingPanel]+ let p = NSPanel(contentRect: NSRect(x: 0, y: 0, width: width, height: height),+ styleMask: style,+ backing: .buffered,+ defer: false)+ p.level = .statusBar+ p.isOpaque = false+ p.hasShadow = true+ p.hidesOnDeactivate = false+ p.ignoresMouseEvents = true+ p.collectionBehavior = [.canJoinAllSpaces, .transient, .fullScreenAuxiliary]+ p.backgroundColor = .clear+ p.titleVisibility = .hidden+ p.titlebarAppearsTransparent = true+ panel = p++ // Create container with dark background+ let container = NSView(frame: NSRect(x: 0, y: 0, width: width, height: height))+ container.wantsLayer = true+ container.layer?.backgroundColor = NSColor.black.withAlphaComponent(0.85).cgColor+ container.layer?.cornerRadius = 10+ unifiedContainer = container++ // Create message label+ let label = NSTextField(frame: NSRect(x: 10, y: 10, width: width - 20, height: height - 20))+ label.isEditable = false+ label.isBordered = false+ label.drawsBackground = false+ label.textColor = .white+ label.alignment = .center+ label.font = NSFont.systemFont(ofSize: 13, weight: .medium)+ label.stringValue = message+ container.addSubview(label)++ panel?.contentView = container+ positionCenteredLower()++ // Animate in+ container.alphaValue = 0.0+ panel?.orderFrontRegardless()++ NSAnimationContext.runAnimationGroup({ context in+ context.duration = 0.2+ context.timingFunction = CAMediaTimingFunction(name: .easeOut)+ container.animator().alphaValue = 1.0+ })++ // Auto-hide after duration+ DispatchQueue.main.asyncAfter(deadline: .now() + duration) { [weak self] in+ self?.hide()+ }+ }private func activeScreen() -> NSScreen?{@@ -206,6 +287,51 @@ final class ListeningOverlayControllerreturn field}+ private func setupModeLabel(in containerView: NSView, width: CGFloat) {+ // Remove existing label if any+ modeLabel?.removeFromSuperview()++ let label = NSTextField(frame: .zero)+ label.isEditable = false+ label.isBordered = false+ label.drawsBackground = false+ label.alignment = .center+ label.font = NSFont.systemFont(ofSize: 9, weight: .semibold)+ label.translatesAutoresizingMaskIntoConstraints = false++ containerView.addSubview(label)+ modeLabel = label++ // Position at top-right+ NSLayoutConstraint.activate([+ label.topAnchor.constraint(equalTo: containerView.topAnchor, constant: 6),+ label.trailingAnchor.constraint(equalTo: containerView.trailingAnchor, constant: -10)+ ])++ updateModeLabel()+ }++ private func updateModeLabel() {+ guard let label = modeLabel else { return }++ switch currentMode {+ case .dictation:+ // Hide for normal dictation mode (it's the default)+ label.alphaValue = 0+ label.stringValue = ""+ case .rewrite:+ // Show "Rewrite" badge in blue+ label.stringValue = "✏️ Rewrite"+ label.textColor = NSColor(calibratedRed: 0.4, green: 0.6, blue: 1.0, alpha: 1.0)+ label.alphaValue = 1.0+ case .command:+ // Show "Command" badge in green+ label.stringValue = "⚡ Command"+ label.textColor = NSColor(calibratedRed: 0.4, green: 0.8, blue: 0.4, alpha: 1.0)+ label.alphaValue = 1.0+ }+ }+func setPreviewEnabled(_ enabled: Bool) {guard isShowingPreview != enabled else { return }isShowingPreview = enableddiff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swiftindex 09b85e46..e1bef6af 100644--- a/Sources/Fluid/Services/MenuBarManager.swift+++ b/Sources/Fluid/Services/MenuBarManager.swift@@ -119,6 +119,14 @@ final class MenuBarManager: ObservableObject {overlay?.setPreviewEnabled(enabled)}+ func setOverlayMode(_ mode: OverlayMode) {+ overlay?.setMode(mode)+ }++ func showToast(_ message: String) {+ overlay?.showToast(message)+ }+private func setupMenuBarSafely() {// Check if window server connection is availableguard NSApp.isActive || NSApp.isRunning else {diff --git a/Sources/Fluid/Services/RewriteModeService.swift b/Sources/Fluid/Services/RewriteModeService.swiftnew file mode 100644index 00000000..9b44903d--- /dev/null+++ b/Sources/Fluid/Services/RewriteModeService.swift@@ -0,0 +1,136 @@+import Foundation+import Combine+import AppKit++@MainActor+final class RewriteModeService: ObservableObject {+ @Published var originalText: String = ""+ @Published var rewrittenText: String = ""+ @Published var isProcessing = false+ @Published var conversationHistory: [Message] = []++ private let textSelectionService = TextSelectionService.shared+ private let typingService = TypingService()++ struct Message: Identifiable, Equatable {+ let id = UUID()+ let role: Role+ let content: String++ enum Role: Equatable {+ case user+ case assistant+ }+ }++ func captureSelectedText() -> Bool {+ if let text = textSelectionService.getSelectedText(), !text.isEmpty {+ self.originalText = text+ self.rewrittenText = ""+ self.conversationHistory = []+ return true+ }+ return false+ }++ func processRewriteRequest(_ prompt: String) async {+ guard !originalText.isEmpty else { return }++ isProcessing = true++ // If this is the first request, include the original text+ if conversationHistory.isEmpty {+ conversationHistory.append(Message(role: .user, content: "Original text:\n\(originalText)\n\nRequest: \(prompt)"))+ } else {+ conversationHistory.append(Message(role: .user, content: prompt))+ }++ do {+ let response = try await callLLM(messages: conversationHistory)+ conversationHistory.append(Message(role: .assistant, content: response))+ rewrittenText = response+ isProcessing = false+ } catch {+ conversationHistory.append(Message(role: .assistant, content: "Error: \(error.localizedDescription)"))+ isProcessing = false+ }+ }++ func acceptRewrite() {+ guard !rewrittenText.isEmpty else { return }+ NSApp.hide(nil) // Restore focus to the previous app+ typingService.typeTextInstantly(rewrittenText)+ }++ func clearState() {+ originalText = ""+ rewrittenText = ""+ conversationHistory = []+ }++ // MARK: - LLM Integration (Duplicated from CommandModeService for now)++ private func callLLM(messages: [Message]) async throws -> String {+ let settings = SettingsStore.shared+ // Use global settings for now, or add specific rewrite settings+ let providerID = settings.selectedProviderID+ let model = settings.selectedModel ?? "gpt-4o"+ let apiKey = settings.providerAPIKeys[providerID] ?? ""++ let baseURL: String+ if let provider = settings.savedProviders.first(where: { $0.id == providerID }) {+ baseURL = provider.baseURL+ } else if providerID == "groq" {+ baseURL = "https://api.groq.com/openai/v1"+ } else {+ baseURL = "https://api.openai.com/v1"+ }++ let systemPrompt = """+ You are a helpful writing assistant. Your task is to rewrite or modify the text provided by the user according to their instructions.+ Output ONLY the rewritten text. Do not include explanations or conversational filler unless specifically asked.+ """++ var apiMessages: [[String: Any]] = [+ ["role": "system", "content": systemPrompt]+ ]++ for msg in messages {+ apiMessages.append(["role": msg.role == .user ? "user" : "assistant", "content": msg.content])+ }++ let body: [String: Any] = [+ "model": model,+ "messages": apiMessages,+ "temperature": 0.7+ ]++ let endpoint = baseURL.hasSuffix("/chat/completions") ? baseURL : "\(baseURL)/chat/completions"+ guard let url = URL(string: endpoint) else {+ throw NSError(domain: "RewriteMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid URL"])+ }++ var request = URLRequest(url: url)+ request.httpMethod = "POST"+ request.addValue("application/json", forHTTPHeaderField: "Content-Type")+ request.addValue("Bearer \(apiKey)", forHTTPHeaderField: "Authorization")+ request.httpBody = try JSONSerialization.data(withJSONObject: body)++ let (data, response) = try await URLSession.shared.data(for: request)++ if let http = response as? HTTPURLResponse, http.statusCode >= 400 {+ let err = String(data: data, encoding: .utf8) ?? "Unknown error"+ throw NSError(domain: "RewriteMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: err])+ }++ guard let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],+ let choices = json["choices"] as? [[String: Any]],+ let choice = choices.first,+ let message = choice["message"] as? [String: Any],+ let content = message["content"] as? String else {+ throw NSError(domain: "RewriteMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response"])+ }++ return content+ }+}diff --git a/Sources/Fluid/Services/TerminalService.swift b/Sources/Fluid/Services/TerminalService.swiftnew file mode 100644index 00000000..23fa2c45--- /dev/null+++ b/Sources/Fluid/Services/TerminalService.swift@@ -0,0 +1,147 @@+import Foundation++/// Simple terminal command execution service+/// All responses are JSON-parsable for easy AI processing+final class TerminalService {++ // MARK: - JSON Response Types++ struct CommandResult: Codable {+ let success: Bool+ let command: String+ let output: String+ let error: String?+ let exitCode: Int32+ let executionTimeMs: Int+ }++ // MARK: - Tool Definition for AI++ /// Returns the tool definition in OpenAI function calling format+ static var toolDefinition: [String: Any] {+ return [+ "type": "function",+ "function": [+ "name": "execute_terminal_command",+ "description": """+ Execute a terminal/shell command on the user's macOS computer.+ Use this to run any command-line operation like: file operations (ls, cat, mkdir, rm),+ git commands, brew, npm, python scripts, or any other CLI tool.+ Returns JSON with: success (bool), output (stdout), error (stderr if any), exitCode.+ IMPORTANT: Only suggest safe, non-destructive commands unless explicitly asked.+ """,+ "parameters": [+ "type": "object",+ "properties": [+ "command": [+ "type": "string",+ "description": "The shell command to execute (e.g., 'ls -la', 'git status', 'cat file.txt')"+ ],+ "workingDirectory": [+ "type": "string",+ "description": "Optional working directory path. Defaults to user's home directory if not specified."+ ]+ ],+ "required": ["command"]+ ]+ ]+ ]+ }++ // MARK: - Execution++ /// Execute a terminal command and return JSON-parsable result+ func execute(+ command: String,+ workingDirectory: String? = nil,+ timeout: TimeInterval = 30+ ) async -> CommandResult {+ let startTime = Date()++ let process = Process()+ let outputPipe = Pipe()+ let errorPipe = Pipe()++ // Use zsh (default macOS shell)+ process.executableURL = URL(fileURLWithPath: "/bin/zsh")+ process.arguments = ["-c", command]++ // Set working directory+ if let dir = workingDirectory, !dir.isEmpty {+ process.currentDirectoryURL = URL(fileURLWithPath: dir)+ } else {+ process.currentDirectoryURL = FileManager.default.homeDirectoryForCurrentUser+ }++ // Inherit user's environment (PATH, etc.)+ var environment = ProcessInfo.processInfo.environment+ // Ensure common paths are available+ if let path = environment["PATH"] {+ environment["PATH"] = "/opt/homebrew/bin:/usr/local/bin:\(path)"+ }+ process.environment = environment++ process.standardOutput = outputPipe+ process.standardError = errorPipe++ do {+ try process.run()++ // Wait with timeout+ let timeoutTask = Task {+ try await Task.sleep(nanoseconds: UInt64(timeout * 1_000_000_000))+ if process.isRunning {+ process.terminate()+ }+ }++ process.waitUntilExit()+ timeoutTask.cancel()++ let outputData = outputPipe.fileHandleForReading.readDataToEndOfFile()+ let errorData = errorPipe.fileHandleForReading.readDataToEndOfFile()++ let output = String(data: outputData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines) ?? ""+ let errorOutput = String(data: errorData, encoding: .utf8)?.trimmingCharacters(in: .whitespacesAndNewlines)++ let executionTime = Int(Date().timeIntervalSince(startTime) * 1000)++ return CommandResult(+ success: process.terminationStatus == 0,+ command: command,+ output: output,+ error: errorOutput?.isEmpty == true ? nil : errorOutput,+ exitCode: process.terminationStatus,+ executionTimeMs: executionTime+ )++ } catch {+ let executionTime = Int(Date().timeIntervalSince(startTime) * 1000)+ return CommandResult(+ success: false,+ command: command,+ output: "",+ error: "Failed to execute: \(error.localizedDescription)",+ exitCode: -1,+ executionTimeMs: executionTime+ )+ }+ }++ /// Convert result to JSON string for AI processing+ func resultToJSON(_ result: CommandResult) -> String {+ let encoder = JSONEncoder()+ encoder.outputFormatting = [.prettyPrinted, .sortedKeys]++ if let data = try? encoder.encode(result),+ let json = String(data: data, encoding: .utf8) {+ return json+ }++ // Fallback+ return """+ {"success": \(result.success), "output": "\(result.output)", "exitCode": \(result.exitCode)}+ """+ }+}+diff --git a/Sources/Fluid/Services/TextSelectionService.swift b/Sources/Fluid/Services/TextSelectionService.swiftnew file mode 100644index 00000000..bde36625--- /dev/null+++ b/Sources/Fluid/Services/TextSelectionService.swift@@ -0,0 +1,78 @@+import Foundation+import AppKit+import ApplicationServices++final class TextSelectionService {+ static let shared = TextSelectionService()++ private init() {}++ /// Attempts to get the currently selected text using Accessibility APIs+ func getSelectedText() -> String? {+ // Check accessibility permissions+ guard AXIsProcessTrusted() else {+ DebugLogger.shared.error("Accessibility permissions not granted", source: "TextSelectionService")+ return nil+ }++ // 1. Try to get the system-wide focused element+ if let focusedElement = getFocusedElement() {+ if let text = getSelectedText(from: focusedElement) {+ return text+ }+ }++ // 2. Fallback: Try to find focused element in frontmost app+ if let frontmostApp = NSWorkspace.shared.frontmostApplication {+ let appElement = AXUIElementCreateApplication(frontmostApp.processIdentifier)+ if let focusedElement = getFocusedElement(from: appElement) {+ if let text = getSelectedText(from: focusedElement) {+ return text+ }+ }+ }++ return nil+ }++ // MARK: - Private Helpers++ private func getFocusedElement() -> AXUIElement? {+ let systemWideElement = AXUIElementCreateSystemWide()+ var focusedElement: CFTypeRef?++ let result = AXUIElementCopyAttributeValue(systemWideElement, kAXFocusedUIElementAttribute as CFString, &focusedElement)++ if result == .success {+ return (focusedElement as! AXUIElement)+ }++ return nil+ }++ private func getFocusedElement(from appElement: AXUIElement) -> AXUIElement? {+ var focusedElement: CFTypeRef?+ let result = AXUIElementCopyAttributeValue(appElement, kAXFocusedUIElementAttribute as CFString, &focusedElement)++ if result == .success {+ return (focusedElement as! AXUIElement)+ }++ return nil+ }++ private func getSelectedText(from element: AXUIElement) -> String? {+ var value: CFTypeRef?+ let result = AXUIElementCopyAttributeValue(element, kAXSelectedTextAttribute as CFString, &value)++ if result == .success, let text = value as? String {+ return text+ }++ // Fallback: If no text is selected, some apps might return the value attribute+ // But for "rewrite selected", we strictly want selected text.+ // We could optionally return all text if we wanted to rewrite the whole field.++ return nil+ }+}diff --git a/Sources/Fluid/Theme/Components/ThemedGroupBox.swift b/Sources/Fluid/Theme/Components/ThemedGroupBox.swiftindex 3502a854..d047666d 100644--- a/Sources/Fluid/Theme/Components/ThemedGroupBox.swift+++ b/Sources/Fluid/Theme/Components/ThemedGroupBox.swift@@ -50,3 +50,5 @@ struct ThemedGroupBox<Label: View, Content: View>: View {++diff --git a/Sources/Fluid/Theme/NativeButtonStyles.swift b/Sources/Fluid/Theme/NativeButtonStyles.swiftindex 066360a1..58ef7433 100644--- a/Sources/Fluid/Theme/NativeButtonStyles.swift+++ b/Sources/Fluid/Theme/NativeButtonStyles.swift@@ -323,3 +323,5 @@ struct GlassToggleStyle: ToggleStyle {++diff --git a/Sources/Fluid/Theme/ThemeEnvironment.swift b/Sources/Fluid/Theme/ThemeEnvironment.swiftindex e586cf47..a859618a 100644--- a/Sources/Fluid/Theme/ThemeEnvironment.swift+++ b/Sources/Fluid/Theme/ThemeEnvironment.swift@@ -25,3 +25,5 @@ extension View {++diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swiftindex 6277e3fd..1c4041bc 100644--- a/Sources/Fluid/UI/SettingsView.swift+++ b/Sources/Fluid/UI/SettingsView.swift@@ -22,6 +22,8 @@ struct SettingsView: View {@Binding var accessibilityEnabled: Bool@Binding var hotkeyShortcut: HotkeyShortcut@Binding var isRecordingShortcut: Bool+ @Binding var rewriteShortcut: HotkeyShortcut+ @Binding var isRecordingRewriteShortcut: Bool@Binding var hotkeyManagerInitialized: Bool@Binding var pressAndHoldModeEnabled: Bool@Binding var enableStreamingPreview: Bool@@ -523,6 +525,72 @@ struct SettingsView: View {.onChange(of: copyToClipboard) { newValue inSettingsStore.shared.copyTranscriptionToClipboard = newValue}++ Divider()+ .padding(.vertical, 4)++ // Rewrite Mode Shortcut+ VStack(alignment: .leading, spacing: 10) {+ HStack {+ VStack(alignment: .leading, spacing: 4) {+ Text("Rewrite Mode Shortcut")+ .font(.subheadline)+ .fontWeight(.medium)+ Text("Select text, press shortcut, speak how to rewrite")+ .font(.caption)+ .foregroundStyle(.secondary)+ }++ Spacer()++ // Shortcut display+ if isRecordingRewriteShortcut {+ Text("Press new shortcut...")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(.orange)+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .background(+ RoundedRectangle(cornerRadius: 6)+ .fill(.orange.opacity(0.2))+ )+ } else {+ Text(rewriteShortcut.displayString)+ .font(.system(size: 13, weight: .semibold, design: .monospaced))+ .foregroundStyle(.primary)+ .padding(.horizontal, 10)+ .padding(.vertical, 5)+ .background(+ RoundedRectangle(cornerRadius: 6)+ .fill(.quaternary.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: 6)+ .stroke(.primary.opacity(0.2), lineWidth: 1)+ )+ )+ }++ // Change button+ Button {+ isRecordingRewriteShortcut = true+ } label: {+ Text("Change")+ .font(.system(size: 12, weight: .medium))+ }+ .buttonStyle(.bordered)+ .disabled(isRecordingRewriteShortcut)+ }+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 10)+ .background(+ RoundedRectangle(cornerRadius: 8)+ .fill(.ultraThinMaterial.opacity(0.5))+ .overlay(+ RoundedRectangle(cornerRadius: 8)+ .stroke(.white.opacity(0.08), lineWidth: 1)+ )+ )}} else {// Hotkey disabled - accessibility not enableddiff --git a/Sources/Fluid/Views/CommandModeView.swift b/Sources/Fluid/Views/CommandModeView.swiftnew file mode 100644index 00000000..aeb69e9b--- /dev/null+++ b/Sources/Fluid/Views/CommandModeView.swift@@ -0,0 +1,446 @@+import SwiftUI++struct CommandModeView: View {+ @ObservedObject var service: CommandModeService+ @ObservedObject var asr: ASRService+ @ObservedObject var settings = SettingsStore.shared+ var onClose: (() -> Void)?+ @State private var inputText: String = ""++ // Local state for available models (derived)+ @State private var availableModels: [String] = []++ // Computed Bindings+ private var selectedProviderIDBinding: Binding<String> {+ Binding(+ get: { settings.commandModeLinkedToGlobal ? settings.selectedProviderID : settings.commandModeSelectedProviderID },+ set: { newValue in+ if settings.commandModeLinkedToGlobal {+ settings.selectedProviderID = newValue+ } else {+ settings.commandModeSelectedProviderID = newValue+ }+ updateAvailableModels()+ }+ )+ }++ private var selectedModelBinding: Binding<String> {+ Binding(+ get: { (settings.commandModeLinkedToGlobal ? settings.selectedModel : settings.commandModeSelectedModel) ?? "gpt-4o" },+ set: { newValue in+ if settings.commandModeLinkedToGlobal {+ settings.selectedModel = newValue+ } else {+ settings.commandModeSelectedModel = newValue+ }+ }+ )+ }++ // UI State+ @State private var showingClearConfirmation = false++ @Environment(\.theme) private var theme++ var body: some View {+ VStack(spacing: 0) {+ // Header+ headerView++ Divider()++ // Chat Area+ chatArea++ // Pending Command Confirmation (if any)+ if let pending = service.pendingCommand {+ pendingCommandView(pending)+ }++ Divider()++ // Input Area+ inputArea+ }+ .onAppear {+ updateAvailableModels()+ }+ .onChange(of: asr.finalText) { newText in+ if !newText.isEmpty {+ inputText = newText+ }+ }+ // React to external changes (e.g. if global settings change while linked)+ .onChange(of: settings.selectedProviderID) { _ in if settings.commandModeLinkedToGlobal { updateAvailableModels() } }+ .onChange(of: settings.commandModeLinkedToGlobal) { _ in updateAvailableModels() }+ .background(+ Button("") {+ onClose?()+ }+ .keyboardShortcut(.cancelAction)+ .opacity(0)+ )+ }++ // MARK: - Header++ private var headerView: some View {+ HStack {+ Text("Command Mode")+ .font(.title2)+ .fontWeight(.bold)++ Spacer()++ // Link to AI Settings Toggle+ Toggle(isOn: $settings.commandModeLinkedToGlobal) {+ Label("Sync Settings", systemImage: "link")+ .font(.caption)+ }+ .toggleStyle(.checkbox)+ .help("Use same provider and model as main AI settings")++ Divider()+ .frame(height: 20)+ .padding(.horizontal, 4)++ // Confirm Before Execute Toggle+ Toggle(isOn: $settings.commandModeConfirmBeforeExecute) {+ Label("Confirm", systemImage: "checkmark.shield")+ .font(.caption)+ }+ .toggleStyle(.checkbox)+ .help("Ask for confirmation before running commands")++ Divider()+ .frame(height: 20)+ .padding(.horizontal, 8)++ // Provider Selector+ Picker("", selection: selectedProviderIDBinding) {+ Text("OpenAI").tag("openai")+ Text("Groq").tag("groq")+ ForEach(settings.savedProviders) { provider in+ Text(provider.name).tag(provider.id)+ }+ }+ .frame(width: 120)++ // Model Selector+ Picker("", selection: selectedModelBinding) {+ ForEach(availableModels, id: \.self) { model in+ Text(model).tag(model)+ }+ }+ .frame(width: 160)++ // Clear Chat+ Button(action: { showingClearConfirmation = true }) {+ Image(systemName: "trash")+ }+ .buttonStyle(.bordered)+ .help("Clear conversation")+ .disabled(service.conversationHistory.isEmpty)+ }+ .padding()+ .background(Color(nsColor: .windowBackgroundColor))+ .confirmationDialog(+ "Clear conversation?",+ isPresented: $showingClearConfirmation,+ titleVisibility: .visible+ ) {+ Button("Clear", role: .destructive) {+ service.clearHistory()+ }+ Button("Cancel", role: .cancel) {}+ }+ }++ // MARK: - Chat Area++ private var chatArea: some View {+ ScrollViewReader { proxy in+ ScrollView {+ LazyVStack(alignment: .leading, spacing: 12) {+ ForEach(service.conversationHistory) { message in+ MessageBubble(message: message)+ .id(message.id)+ }++ if service.isProcessing {+ HStack {+ ProgressView()+ .controlSize(.small)+ Text("Processing...")+ .font(.caption)+ .foregroundStyle(.secondary)+ }+ .padding(.leading)+ .id("processing")+ }++ Color.clear.frame(height: 1).id("bottom")+ }+ .padding()+ }+ .onChange(of: service.conversationHistory.count) { _ in+ scrollToBottom(proxy)+ }+ .onChange(of: service.isProcessing) { _ in+ scrollToBottom(proxy)+ }+ }+ }++ private func scrollToBottom(_ proxy: ScrollViewProxy) {+ DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) {+ withAnimation(.easeOut(duration: 0.2)) {+ proxy.scrollTo("bottom", anchor: .bottom)+ }+ }+ }++ // MARK: - Pending Command++ private func pendingCommandView(_ pending: CommandModeService.PendingCommand) -> some View {+ VStack(spacing: 8) {+ Divider()++ HStack {+ Image(systemName: "exclamationmark.triangle.fill")+ .foregroundStyle(.orange)+ Text("Confirm command execution?")+ .fontWeight(.medium)+ }++ Text(pending.command)+ .font(.system(.body, design: .monospaced))+ .padding(8)+ .background(Color(nsColor: .textBackgroundColor))+ .cornerRadius(6)++ HStack(spacing: 12) {+ Button("Cancel") {+ service.cancelPendingCommand()+ }+ .buttonStyle(.bordered)++ Button("Run") {+ Task {+ await service.confirmAndExecute()+ }+ }+ .buttonStyle(.borderedProminent)+ .keyboardShortcut(.return, modifiers: [])+ }+ }+ .padding()+ .background(Color.orange.opacity(0.1))+ }++ // MARK: - Input Area++ private var inputArea: some View {+ HStack {+ TextField("Type a command or ask a question...", text: $inputText)+ .textFieldStyle(.roundedBorder)+ .onSubmit {+ submitCommand()+ }++ Button(action: submitCommand) {+ Image(systemName: "arrow.up.circle.fill")+ .font(.title2)+ }+ .buttonStyle(.plain)+ .disabled(inputText.isEmpty || service.isProcessing)++ // Voice Input+ Button(action: toggleRecording) {+ Image(systemName: asr.isRunning ? "stop.circle.fill" : "mic.circle.fill")+ .font(.title2)+ .foregroundStyle(asr.isRunning ? Color.red : Color.accentColor)+ }+ .buttonStyle(.plain)+ }+ .padding()+ .background(Color(nsColor: .windowBackgroundColor))+ }++ // MARK: - Actions++ private func toggleRecording() {+ if asr.isRunning {+ Task { await asr.stop() }+ } else {+ asr.start()+ }+ }++ private func submitCommand() {+ guard !inputText.isEmpty else { return }+ let text = inputText+ inputText = ""+ Task {+ await service.processUserCommand(text)+ }+ }++ private func updateAvailableModels() {+ let currentProviderID = settings.commandModeLinkedToGlobal ? settings.selectedProviderID : settings.commandModeSelectedProviderID+ let currentModel = (settings.commandModeLinkedToGlobal ? settings.selectedModel : settings.commandModeSelectedModel) ?? "gpt-4o"++ let possibleKeys = providerKeys(for: currentProviderID)+ let storedList = possibleKeys.lazy+ .compactMap { SettingsStore.shared.availableModelsByProvider[$0] }+ .first { !$0.isEmpty }++ if let stored = storedList {+ availableModels = stored+ } else {+ availableModels = defaultModels(for: currentProviderID)+ }++ if !availableModels.contains(currentModel) {+ let newModel = availableModels.first ?? "gpt-4o"+ if settings.commandModeLinkedToGlobal {+ settings.selectedModel = newModel+ } else {+ settings.commandModeSelectedModel = newModel+ }+ }+ }++ /// Returns possible keys used to store models for a provider.+ private func providerKeys(for providerID: String) -> [String] {+ var keys: [String] = []+ let trimmed = providerID.trimmingCharacters(in: .whitespacesAndNewlines)++ if trimmed.isEmpty {+ return [providerID]+ }++ if trimmed == "openai" || trimmed == "groq" {+ return [trimmed]+ }++ if trimmed.hasPrefix("custom:") {+ keys.append(trimmed)+ keys.append(String(trimmed.dropFirst("custom:".count)))+ } else {+ keys.append("custom:\(trimmed)")+ keys.append(trimmed)+ }++ // Add legacy key used in ContentView before the fix+ keys.append("custom:\\(trimmed)")++ return Array(Set(keys))+ }++ private func defaultModels(for provider: String) -> [String] {+ switch provider {+ case "openai": return ["gpt-4o", "gpt-4-turbo", "gpt-3.5-turbo"]+ case "groq": return ["llama-3.3-70b-versatile", "llama3-70b-8192", "mixtral-8x7b-32768"]+ default: return ["gpt-4o"]+ }+ }+}++// MARK: - Message Bubble++struct MessageBubble: View {+ let message: CommandModeService.Message++ var body: some View {+ HStack(alignment: .top) {+ if message.role == .user {+ Spacer()+ Text(message.content)+ .padding(10)+ .background(Color.accentColor.opacity(0.2))+ .cornerRadius(12)+ .frame(maxWidth: 400, alignment: .trailing)+ } else {+ VStack(alignment: .leading, spacing: 4) {+ // Role indicator+ HStack(spacing: 4) {+ Image(systemName: iconName)+ .font(.caption)+ Text(roleName)+ .font(.caption)+ .fontWeight(.bold)+ }+ .foregroundStyle(.secondary)++ // Content+ if message.role == .tool {+ // Show tool output in code block style+ ScrollView(.horizontal, showsIndicators: false) {+ Text(formatToolOutput(message.content))+ .font(.system(.caption, design: .monospaced))+ .padding(8)+ .background(Color(nsColor: .textBackgroundColor))+ .cornerRadius(8)+ }+ .frame(maxWidth: 500)+ } else {+ Text(message.content)+ .padding(10)+ .background(Color(nsColor: .controlBackgroundColor))+ .cornerRadius(12)+ .textSelection(.enabled)+ }++ // Show command if present+ if let tc = message.toolCall {+ HStack(spacing: 4) {+ Image(systemName: "terminal.fill")+ .font(.caption2)+ Text(tc.command)+ .font(.system(.caption, design: .monospaced))+ .lineLimit(1)+ }+ .padding(6)+ .background(Color.blue.opacity(0.1))+ .cornerRadius(6)+ .foregroundStyle(.blue)+ }+ }+ .frame(maxWidth: 500, alignment: .leading)+ Spacer()+ }+ }+ }++ private var iconName: String {+ switch message.role {+ case .assistant: return "sparkles"+ case .tool: return "terminal"+ default: return "person"+ }+ }++ private var roleName: String {+ switch message.role {+ case .assistant: return "Assistant"+ case .tool: return "Output"+ default: return "You"+ }+ }++ private func formatToolOutput(_ json: String) -> String {+ // Try to extract just the output field for cleaner display+ if let data = json.data(using: .utf8),+ let parsed = try? JSONSerialization.jsonObject(with: data) as? [String: Any] {+ if let output = parsed["output"] as? String, !output.isEmpty {+ return output+ }+ if let error = parsed["error"] as? String {+ return "Error: \(error)"+ }+ }+ return json+ }+}diff --git a/Sources/Fluid/Views/RewriteModeView.swift b/Sources/Fluid/Views/RewriteModeView.swiftnew file mode 100644index 00000000..50dd1777--- /dev/null+++ b/Sources/Fluid/Views/RewriteModeView.swift@@ -0,0 +1,191 @@+import SwiftUI++struct RewriteModeView: View {+ @ObservedObject var service: RewriteModeService+ @ObservedObject var asr: ASRService+ @EnvironmentObject var menuBarManager: MenuBarManager+ var onClose: (() -> Void)?++ @State private var inputText: String = ""+ @State private var showOriginal: Bool = true++ var body: some View {+ VStack(spacing: 0) {+ // Header+ HStack {+ Image(systemName: "pencil.and.outline")+ .font(.title2)+ .foregroundStyle(.blue)+ Text("Rewrite Mode")+ .font(.title2)+ .fontWeight(.bold)++ Spacer()++ Button(action: { onClose?() }) {+ Image(systemName: "xmark.circle.fill")+ .foregroundStyle(.secondary)+ }+ .buttonStyle(.plain)+ }+ .padding()+ .background(Color(nsColor: .windowBackgroundColor))++ Divider()++ ScrollView {+ VStack(alignment: .leading, spacing: 16) {+ // Original Text Section+ if !service.originalText.isEmpty {+ VStack(alignment: .leading, spacing: 8) {+ HStack {+ Text("Original Text")+ .font(.caption)+ .fontWeight(.bold)+ .foregroundStyle(.secondary)+ Spacer()+ if !service.rewrittenText.isEmpty {+ Button(showOriginal ? "Hide" : "Show") {+ withAnimation { showOriginal.toggle() }+ }+ .font(.caption)+ .buttonStyle(.link)+ }+ }++ if showOriginal {+ Text(service.originalText)+ .padding()+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.gray.opacity(0.1))+ .cornerRadius(8)+ .textSelection(.enabled)+ }+ }+ } else {+ VStack(spacing: 12) {+ Image(systemName: "text.cursor")+ .font(.system(size: 48))+ .foregroundStyle(.secondary)+ Text("No text selected")+ .font(.title2)+ .fontWeight(.bold)+ Text("Select text in any app and press the Rewrite shortcut to speak your rewrite instruction")+ .foregroundStyle(.secondary)+ .multilineTextAlignment(.center)+ }+ .frame(maxWidth: .infinity)+ .padding(.vertical, 40)+ }++ // Rewritten Text Section+ if !service.rewrittenText.isEmpty {+ VStack(alignment: .leading, spacing: 8) {+ Text("Rewritten Text")+ .font(.caption)+ .fontWeight(.bold)+ .foregroundStyle(.green)++ Text(service.rewrittenText)+ .padding()+ .frame(maxWidth: .infinity, alignment: .leading)+ .background(Color.green.opacity(0.1))+ .cornerRadius(8)+ .textSelection(.enabled)++ HStack {+ Button("Try Again") {+ service.rewrittenText = ""+ }+ .buttonStyle(.bordered)++ Spacer()++ Button("Replace Original") {+ service.acceptRewrite()+ onClose?()+ }+ .buttonStyle(.borderedProminent)+ .tint(.green)+ }+ .padding(.top, 8)+ }+ .transition(.move(edge: .bottom).combined(with: .opacity))+ }++ // Conversation History (optional, maybe just last error)+ if let lastMsg = service.conversationHistory.last, lastMsg.role == .assistant, service.rewrittenText.isEmpty {+ Text(lastMsg.content) // Error message usually+ .foregroundStyle(.red)+ .padding()+ .background(Color.red.opacity(0.1))+ .cornerRadius(8)+ }+ }+ .padding()+ }++ Divider()++ // Input Area+ HStack {+ TextField("How should I rewrite this? (e.g. 'Make it professional')", text: $inputText)+ .textFieldStyle(.roundedBorder)+ .onSubmit(submitRequest)++ Button(action: submitRequest) {+ Image(systemName: "arrow.up.circle.fill")+ .font(.title2)+ }+ .buttonStyle(.plain)+ .disabled(inputText.isEmpty || service.isProcessing || service.originalText.isEmpty)++ // Voice Input+ Button(action: toggleRecording) {+ Image(systemName: asr.isRunning ? "stop.circle.fill" : "mic.circle.fill")+ .font(.title2)+ .foregroundStyle(asr.isRunning ? Color.red : Color.accentColor)+ }+ .buttonStyle(.plain)+ .disabled(service.originalText.isEmpty)++ if service.isProcessing {+ ProgressView()+ .controlSize(.small)+ }+ }+ .padding()+ .background(Color(nsColor: .windowBackgroundColor))+ }+ .onChange(of: asr.finalText) { newText in+ if !newText.isEmpty {+ inputText = newText+ }+ }+ .onAppear {+ // Set overlay mode to rewrite when this view appears+ menuBarManager.setOverlayMode(.rewrite)+ }+ .onDisappear {+ // Reset overlay mode to dictation when leaving+ menuBarManager.setOverlayMode(.dictation)+ }+ }++ private func toggleRecording() {+ if asr.isRunning {+ Task { await asr.stop() }+ } else {+ asr.start()+ }+ }++ private func submitRequest() {+ guard !inputText.isEmpty else { return }+ let prompt = inputText+ inputText = ""+ Task {+ await service.processRewriteRequest(prompt)+ }+ }+}