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
Merge #1
altic-dev6e7152775a1e
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex 7c6c7037..927878c8 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -26,19 +26,7 @@ enum SidebarItem: Hashable {// Removed deprecated inline service and model-// MARK: - Streaming Response Structures--private struct StreamingDelta: Codable { let role: String?; let content: String? }-private struct StreamingChoice: Codable { let index: Int?; let delta: StreamingDelta; let finish_reason: String? }-private struct StreamingChunk: Codable { let choices: [StreamingChoice] }--// MARK: - AI Processing Response Structures--// NOTE: Keep Codable types out of View methods to avoid SwiftUI/metadata blowups at launch.-private struct AIProcessingMessage: Codable { let role: String; let content: String }-private struct AIProcessingChoiceMessage: Codable { let role: String; let content: String }-private struct AIProcessingChoice: Codable { let index: Int?; let message: AIProcessingChoiceMessage }-private struct AIProcessingResponse: Codable { let choices: [AIProcessingChoice] }+// NOTE: Streaming and AI response parsing is now handled by LLMClientstruct ContentView: View {@StateObject private var audioObserver = AudioHardwareObserver()@@ -311,21 +299,9 @@ struct ContentView: View {NSEvent.addLocalMonitorForEvents(matching: [.keyDown, .flagsChanged]) { event inlet eventModifiers = event.modifierFlags.intersection([.function, .command, .option, .control, .shift])- let shortcutModifiers = self.hotkeyShortcut.modifierFlags.intersection([- .function,- .command,- .option,- .control,- .shift,- ])-- let isRecordingAnyShortcut = self.isRecordingShortcut || self.isRecordingCommandModeShortcut || self- .isRecordingRewriteShortcut- DebugLogger.shared- .debug(- "NSEvent \(event.type) keyCode=\(event.keyCode) recordingShortcut=\(self.isRecordingShortcut) recordingCommand=\(self.isRecordingCommandModeShortcut) recordingRewrite=\(self.isRecordingRewriteShortcut)",- source: "ContentView"- )+ let shortcutModifiers = hotkeyShortcut.modifierFlags.intersection([.function, .command, .option, .control, .shift])++ let isRecordingAnyShortcut = isRecordingShortcut || isRecordingCommandModeShortcut || isRecordingRewriteShortcutif event.type == .keyDown {if event.keyCode == self.hotkeyShortcut.keyCode && eventModifiers == shortcutModifiers {@@ -1225,6 +1201,8 @@ struct ContentView: View {return false}++ // NOTE: Thinking token filtering is now handled by LLMClient.stripThinkingTags()// MARK: - Modular AI Processing@@ -1279,219 +1257,92 @@ struct ContentView: View {#endifreturn inputText // Fallback if not available}-- let endpoint = derivedBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)- .isEmpty ? "https://api.openai.com/v1" : derivedBaseURL- .trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)-- // Build the full URL - only append /chat/completions if not already present- let fullEndpoint: String- if endpoint.contains("/chat/completions") ||- endpoint.contains("/api/chat") ||- endpoint.contains("/api/generate")- {- // URL already has a complete path, use as-is- fullEndpoint = endpoint- } else {- // Append /chat/completions for OpenAI-compatible endpoints- fullEndpoint = endpoint + "/chat/completions"- }-- guard let url = URL(string: fullEndpoint) else {- return "Error: Invalid Base URL"- }-- let isLocal = self.isLocalEndpoint(endpoint)- let apiKey = storedProviderAPIKeys[derivedCurrentProvider] ?? ""-+// Skip API key validation for local endpoints+ let isLocal = isLocalEndpoint(derivedBaseURL)+ let apiKey = storedProviderAPIKeys[derivedCurrentProvider] ?? ""+if !isLocal {guard !apiKey.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else {return "Error: API Key not set for \(derivedCurrentProvider)"}}-+// Get app context captured at start of recording if available- let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()- let systemPrompt = self.buildSystemPrompt(appInfo: appInfo)- DebugLogger.shared- .debug(- "Using app context for AI: app=\(appInfo.name), bundleId=\(appInfo.bundleId), title=\(appInfo.windowTitle)",- source: "ContentView"- )-- // Get reasoning config for this model (uses per-model settings or auto-detection)- let providerKey = self.providerKey(for: currentSelectedProviderID)- let reasoningConfig = SettingsStore.shared.getReasoningConfig(- forModel: derivedSelectedModel,- provider: providerKey- )-- if let config = reasoningConfig {- DebugLogger.shared- .debug(- "Model '\(derivedSelectedModel)' reasoning config: \(config.parameterName)=\(config.parameterValue), enabled=\(config.isEnabled)",- source: "ContentView"- )- } else {- DebugLogger.shared.debug("Model '\(derivedSelectedModel)' has no reasoning config", source: "ContentView")- }-- // Get streaming setting- let enableStreaming = SettingsStore.shared.enableAIStreaming-+ let appInfo = recordingAppInfo ?? getCurrentAppInfo()+ let systemPrompt = buildSystemPrompt(appInfo: appInfo)+ DebugLogger.shared.debug("Using app context for AI: app=\(appInfo.name), bundleId=\(appInfo.bundleId), title=\(appInfo.windowTitle)", source: "ContentView")+// Check if this is a reasoning model that doesn't support temperature parameterlet modelLower = derivedSelectedModel.lowercased()let isReasoningModel = modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower.hasPrefix("gpt-5")-- // Build request body dynamically to support different reasoning parameters- var requestDict: [String: Any] = [- "model": derivedSelectedModel,- "messages": [- ["role": "system", "content": systemPrompt],- ["role": "user", "content": inputText],- ],- ]-- // Only add temperature for non-reasoning models- // OpenAI reasoning models (o1, o3, gpt-5) don't support custom temperature- if !isReasoningModel {- requestDict["temperature"] = 0.2- }-- // Add reasoning parameter if configured for this model++ // Get reasoning config for this model (uses per-model settings or auto-detection)+ // This handles custom parameters like reasoning_effort, enable_thinking, etc.+ let providerKey = self.providerKey(for: currentSelectedProviderID)+ let reasoningConfig = SettingsStore.shared.getReasoningConfig(forModel: derivedSelectedModel, provider: providerKey)++ // Build extra parameters from reasoning config+ var extraParams: [String: Any]? = nilif let config = reasoningConfig, config.isEnabled {if config.parameterName == "enable_thinking" {// DeepSeek uses boolean- requestDict[config.parameterName] = config.parameterValue == "true"+ extraParams = [config.parameterName: config.parameterValue == "true"]} else {- // OpenAI/Groq use string values- requestDict[config.parameterName] = config.parameterValue+ // OpenAI/Groq use string values (reasoning_effort, etc.)+ extraParams = [config.parameterName: config.parameterValue]}DebugLogger.shared.debug("Added reasoning param: \(config.parameterName)=\(config.parameterValue)",source: "ContentView")}-- // Add streaming if enabled- if enableStreaming {- requestDict["stream"] = true- }-- guard let jsonData = try? JSONSerialization.data(withJSONObject: requestDict, options: []) else {- return "Error: Failed to encode request"- }-- // Debug: Log request body- if let bodyStr = String(data: jsonData, encoding: .utf8) {- DebugLogger.shared.debug("AI Request body: \(bodyStr)", source: "ContentView")- }-- 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-++ // Build messages array+ let messages: [[String: Any]] = [+ ["role": "system", "content": systemPrompt],+ ["role": "user", "content": inputText]+ ]++ // NOTE: Transcription doesn't need streaming - the full result appears at once+ // Streaming is only useful for Command/Rewrite modes where real-time display helps+ // Using non-streaming is simpler and more reliable for transcription cleanup+ let enableStreaming = false // Hardcoded off for transcription++ // Build LLMClient configuration+ // Note: No onContentChunk callback needed since we don't display real-time+ // Thinking tokens are extracted but not displayed (no onThinkingChunk)+ let config = LLMClient.Config(+ messages: messages,+ model: derivedSelectedModel,+ baseURL: derivedBaseURL,+ apiKey: apiKey,+ streaming: enableStreaming,+ tools: nil,+ temperature: isReasoningModel ? nil : 0.2,+ extraParameters: extraParams+ )++ DebugLogger.shared.info("Using LLMClient for transcription (streaming=\(enableStreaming))", source: "ContentView")+do {- if enableStreaming {- // Streaming mode - parse SSE response- DebugLogger.shared.info("Using STREAMING mode for AI request", source: "ContentView")- return try await self.processStreamingResponse(request: request)- } else {- // Non-streaming mode - single JSON response- DebugLogger.shared.info("Using NON-STREAMING mode for AI request", source: "ContentView")- 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"- return "Error: HTTP \(http.statusCode): \(errText)"- }- let decoded = try JSONDecoder().decode(AIProcessingResponse.self, from: data)- return decoded.choices.first?.message.content ?? "<no content>"+ let response = try await LLMClient.shared.call(config)++ // Log thinking if present (for debugging)+ if let thinking = response.thinking {+ DebugLogger.shared.debug("LLM thinking tokens extracted (\(thinking.count) chars)", source: "ContentView")}++ return response.content.isEmpty ? "<no content>" : response.content} catch {DebugLogger.shared.error("AI API error: \(error.localizedDescription)", source: "ContentView")return "Error: \(error.localizedDescription)"}}-- // MARK: - Streaming Response Handler-- private func processStreamingResponse(request: URLRequest) async throws -> String {- DebugLogger.shared.debug(- "Starting streaming request to: \(request.url?.absoluteString ?? "unknown")",- source: "Streaming"- )-- let (bytes, response) = try await URLSession.shared.bytes(for: request)-- if let http = response as? HTTPURLResponse {- DebugLogger.shared.debug("Streaming response status: \(http.statusCode)", source: "Streaming")- if http.statusCode >= 400 {- var errorData = Data()- for try await byte in bytes {- errorData.append(byte)- }- let errText = String(data: errorData, encoding: .utf8) ?? "Unknown error"- DebugLogger.shared.error("Streaming error: \(errText)", source: "Streaming")- return "Error: HTTP \(http.statusCode): \(errText)"- }- }-- var fullContent = ""-- // Use efficient line-based iteration instead of byte-by-byte- for try await rawLine in bytes.lines {- let line = rawLine.trimmingCharacters(in: .whitespaces)-- guard line.hasPrefix("data:") else { continue }-- // Handle both "data: " and "data:" formats- var jsonString = String(line.dropFirst(5))- if jsonString.hasPrefix(" ") {- jsonString = String(jsonString.dropFirst(1))- }-- // Skip [DONE] marker- if jsonString.trimmingCharacters(in: .whitespaces) == "[DONE]" {- DebugLogger.shared.debug("Received [DONE] marker", source: "Streaming")- continue- }-- // Parse the JSON chunk- guard let jsonData = jsonString.data(using: .utf8) else { continue }-- do {- let chunk = try JSONDecoder().decode(StreamingChunk.self, from: jsonData)- if let delta = chunk.choices.first?.delta,- let content = delta.content- {- fullContent += content- }- } catch {- // Try alternative parsing for different response formats- if let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],- let choices = json["choices"] as? [[String: Any]],- let firstChoice = choices.first,- let delta = firstChoice["delta"] as? [String: Any],- let content = delta["content"] as? String- {- fullContent += content- }- }- }-- DebugLogger.shared.debug("Streaming complete. Content length: \(fullContent.count)", source: "Streaming")- return fullContent.isEmpty ? "<no content>" : fullContent- }-++ // MARK: - Streaming Response Handler (DEPRECATED - Now handled by LLMClient)+ // This method is no longer used - LLMClient.call() handles streaming internally+// MARK: - Stop and Process Transcriptionprivate func stopAndProcessTranscription() async {diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swiftindex 696d5fb0..ae25b076 100644--- a/Sources/Fluid/Persistence/SettingsStore.swift+++ b/Sources/Fluid/Persistence/SettingsStore.swift@@ -57,7 +57,8 @@ final class SettingsStore: ObservableObject {// Model Reasoning Config Keysstatic let modelReasoningConfigs = "ModelReasoningConfigs"static let rewriteModeShortcutEnabled = "RewriteModeShortcutEnabled"-+ static let showThinkingTokens = "ShowThinkingTokens"+// Stats Keysstatic let userTypingWPM = "UserTypingWPM"@@ -582,7 +583,34 @@ final class SettingsStore: ObservableObject {self.defaults.set(newValue, forKey: Keys.rewriteModeShortcutEnabled)}}-++ /// Global check if a model is a reasoning model (requires special params/max_completion_tokens)+ func isReasoningModel(_ model: String) -> Bool {+ let modelLower = model.lowercased()+ return modelLower.hasPrefix("gpt-5") ||+ modelLower.contains("gpt-5.") ||+ modelLower.hasPrefix("o1") ||+ modelLower.hasPrefix("o3") ||+ modelLower.contains("gpt-oss") ||+ modelLower.hasPrefix("openai/") ||+ (modelLower.contains("deepseek") && modelLower.contains("reasoner"))+ }+++ /// Whether to display thinking tokens in the UI (Command Mode, Rewrite Mode)+ /// If false, thinking tokens are extracted but not shown to user+ var showThinkingTokens: Bool+ {+ get {+ let value = defaults.object(forKey: Keys.showThinkingTokens)+ return value as? Bool ?? true // Default to true (show thinking)+ }+ set {+ objectWillChange.send()+ defaults.set(newValue, forKey: Keys.showThinkingTokens)+ }+ }+// MARK: - Stats Settings/// User's typing speed in words per minute (for time saved calculation)diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swiftindex 6bc422e0..3fdf5495 100644--- a/Sources/Fluid/Services/CommandModeService.swift+++ b/Sources/Fluid/Services/CommandModeService.swift@@ -7,7 +7,8 @@ final class CommandModeService: ObservableObject {@Published var isProcessing = false@Published var pendingCommand: PendingCommand? = nil@Published var currentStep: AgentStep? = nil- @Published var streamingText: String = "" // Real-time streaming text for UI+ @Published var streamingText: String = "" // Real-time streaming text for UI+ @Published var streamingThinkingText: String = "" // Real-time thinking tokens for UI@Published private(set) var currentChatID: String?private let terminalService = TerminalService()@@ -20,8 +21,10 @@ final class CommandModeService: ObservableObject {// Streaming UI update throttling - adaptive rate based on content lengthprivate var lastUIUpdate: CFAbsoluteTime = 0- private var streamingBuffer: [String] = [] // Buffer tokens instead of string concat-+ private var lastThinkingUIUpdate: CFAbsoluteTime = 0+ private var streamingBuffer: [String] = [] // Buffer tokens instead of string concat+ private var thinkingBuffer: [String] = [] // Buffer thinking tokens+// MARK: - Initializationinit() {@@ -58,6 +61,7 @@ final class CommandModeService: ObservableObject {let id = UUID()let role: Rolelet content: String+ let thinking: String? // Display-only: AI reasoning tokens (NOT sent to API)let toolCall: ToolCall?let stepType: StepTypelet timestamp: Date@@ -84,10 +88,11 @@ final class CommandModeService: ObservableObject {let workingDirectory: String?let purpose: String? // Why this command is being run}-- init(role: Role, content: String, toolCall: ToolCall? = nil, stepType: StepType = .normal) {++ init(role: Role, content: String, thinking: String? = nil, toolCall: ToolCall? = nil, stepType: StepType = .normal) {self.role = roleself.content = content+ self.thinking = thinkingself.toolCall = toolCallself.stepType = stepTypeself.timestamp = Date()@@ -385,13 +390,14 @@ final class CommandModeService: ObservableObject {if let tc = response.toolCall {// Determine step type based on command purpose- let stepType = self.determineStepType(for: tc.command, purpose: tc.purpose)- self.currentStep = stepType == .checking ? .checking(tc.command) : .executing(tc.command)-- // AI wants to run a command- self.conversationHistory.append(Message(+ let stepType = determineStepType(for: tc.command, purpose: tc.purpose)+ currentStep = stepType == .checking ? .checking(tc.command) : .executing(tc.command)++ // AI wants to run a command - include thinking for display+ conversationHistory.append(Message(role: .assistant,- content: response.content.isEmpty ? self.stepDescription(for: stepType) : response.content,+ content: response.content.isEmpty ? stepDescription(for: stepType) : response.content,+ thinking: response.thinking, // Display-onlytoolCall: Message.ToolCall(id: tc.id,command: tc.command,@@ -448,6 +454,7 @@ final class CommandModeService: ObservableObject {self.conversationHistory.append(Message(role: .assistant,content: response.content,+ thinking: response.thinking, // Display-onlystepType: isFinal ? .success : .normal))self.isProcessing = false@@ -644,6 +651,7 @@ final class CommandModeService: ObservableObject {private struct LLMResponse {let content: String+ let thinking: String? // Display-only, NOT sent back to APIlet toolCall: ToolCallData?struct ToolCallData {@@ -800,191 +808,94 @@ final class CommandModeService: ObservableObject {])}}-- // We assume conversationHistory contains the user's latest message already-+// Check streaming settinglet enableStreaming = SettingsStore.shared.enableAIStreaming-- // Build request+// Reasoning models (o1, o3, gpt-5) don't support temperature parameter at all- let isReasoningModel = model.hasPrefix("o1") || model.hasPrefix("o3") || model.hasPrefix("gpt-5")-- var body: [String: Any] = [- "model": model,- "messages": messages,- "tools": [TerminalService.toolDefinition],- "tool_choice": "auto",- ]-- // Only add temperature for non-reasoning models- if !isReasoningModel {- body["temperature"] = 0.1- }-- if enableStreaming {- body["stream"] = true- }-- 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)-- // Retry logic for transient network errors (DNS resolution, connection cold start)- var lastError: Error?- for attempt in 1...3 {- do {- if enableStreaming {- return try await self.processStreamingLLMResponse(request: request)- } else {- return try await self.processNonStreamingLLMResponse(request: request)- }- } catch let error as URLError where error.code == .notConnectedToInternet ||- error.code == .timedOut ||- error.code == .networkConnectionLost ||- error.code == .cannotFindHost ||- error.code == .cannotConnectToHost- {- lastError = error- if attempt < 3 {- // Wait before retry (exponential backoff: 200ms, 400ms)- try? await Task.sleep(nanoseconds: UInt64(200_000_000 * attempt))- continue- }- } catch {- throw error // Non-retryable error+ let isReasoningModel = settings.isReasoningModel(model)++ // Get reasoning config for this model (e.g., reasoning_effort, enable_thinking)+ let reasoningConfig = SettingsStore.shared.getReasoningConfig(forModel: model, provider: providerID)+ var extraParams: [String: Any]? = nil+ if let rConfig = reasoningConfig, rConfig.isEnabled {+ if rConfig.parameterName == "enable_thinking" {+ extraParams = [rConfig.parameterName: rConfig.parameterValue == "true"]+ } else {+ extraParams = [rConfig.parameterName: rConfig.parameterValue]}- }- throw lastError ?? NSError(- domain: "CommandMode",- code: -1,- userInfo: [NSLocalizedDescriptionKey: "Network request failed after retries"]+ DebugLogger.shared.debug("Added reasoning param: \(rConfig.parameterName)=\(rConfig.parameterValue)", source: "CommandModeService")+ }++ // Reset streaming state+ streamingText = ""+ streamingThinkingText = ""+ streamingBuffer = []+ thinkingBuffer = []+ lastUIUpdate = CFAbsoluteTimeGetCurrent()+ lastThinkingUIUpdate = CFAbsoluteTimeGetCurrent()++ // Build LLMClient configuration+ var config = LLMClient.Config(+ messages: messages,+ model: model,+ baseURL: baseURL,+ apiKey: apiKey,+ streaming: enableStreaming,+ tools: [TerminalService.toolDefinition],+ temperature: isReasoningModel ? nil : 0.1,+ extraParameters: extraParams)- }-- // MARK: - Non-Streaming Response-- private func processNonStreamingLLMResponse(request: URLRequest) async throws -> LLMResponse {- 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"])- }-- return self.parseMessageResponse(message)- }-- // MARK: - Streaming Response with Real-time UI Updates-- private func processStreamingLLMResponse(request: URLRequest) async throws -> LLMResponse {- self.streamingText = ""- self.streamingBuffer = []- self.lastUIUpdate = CFAbsoluteTimeGetCurrent()-- let (bytes, response) = try await URLSession.shared.bytes(for: request)-- if let http = response as? HTTPURLResponse, http.statusCode >= 400 {- var errorData = Data()- for try await byte in bytes {- errorData.append(byte)- }- let errText = String(data: errorData, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "CommandMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: errText])- }-- var toolCallId: String?- var toolCallName: String?- var toolCallArguments = ""-- // Use efficient line-based iteration instead of byte-by-byte- for try await rawLine in bytes.lines {- let line = rawLine.trimmingCharacters(in: .whitespaces)-- guard line.hasPrefix("data:") else { continue }-- var jsonString = String(line.dropFirst(5))- if jsonString.hasPrefix(" ") {- jsonString = String(jsonString.dropFirst(1))- }-- if jsonString.trimmingCharacters(in: .whitespaces) == "[DONE]" {- continue- }-- guard let jsonData = jsonString.data(using: .utf8),- let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],- let choices = json["choices"] as? [[String: Any]],- let firstChoice = choices.first,- let delta = firstChoice["delta"] as? [String: Any]- else {- continue- }-- // Handle text content - use buffer to avoid O(n²) string concat- if let content = delta["content"] as? String {- self.streamingBuffer.append(content)-- // Adaptive throttle: slower updates as content grows (reduces SwiftUI layout overhead)- let bufferLength = self.streamingBuffer.count- let updateInterval: CFAbsoluteTime- if bufferLength < 50 {- updateInterval = 0.016 // 60fps for first ~50 tokens- } else if bufferLength < 200 {- updateInterval = 0.033 // 30fps for medium content- } else {- updateInterval = 0.066 // 15fps for long content- }-- let now = CFAbsoluteTimeGetCurrent()- if now - self.lastUIUpdate >= updateInterval {- self.lastUIUpdate = now- let fullContent = self.streamingBuffer.joined()- self.streamingText = fullContent-- // Push to notch for real-time display- if self.enableNotchOutput {- NotchContentState.shared.updateCommandStreamingText(fullContent)++ // Keep retry logic (exponential backoff)+ config.maxRetries = 3+ config.retryDelayMs = 200++ // Add real-time streaming callbacks for UI updates (60fps throttled)+ if enableStreaming {+ // Thinking tokens callback+ config.onThinkingChunk = { [weak self] (chunk: String) in+ guard let self = self else { return }+ Task { @MainActor in+ self.thinkingBuffer.append(chunk)++ // 60fps UI update throttle for thinking+ let now = CFAbsoluteTimeGetCurrent()+ if now - self.lastThinkingUIUpdate >= 0.016 {+ self.lastThinkingUIUpdate = now+ self.streamingThinkingText = self.thinkingBuffer.joined()}}}-- // Handle tool calls (streamed in parts)- if let toolCalls = delta["tool_calls"] as? [[String: Any]],- let toolCall = toolCalls.first- {- if let id = toolCall["id"] as? String {- toolCallId = id- }-- if let function = toolCall["function"] as? [String: Any] {- if let name = function["name"] as? String {- toolCallName = name- }- if let args = function["arguments"] as? String {- toolCallArguments += args++ // Content callback+ config.onContentChunk = { [weak self] (chunk: String) in+ guard let self = self else { return }+ Task { @MainActor in+ self.streamingBuffer.append(chunk)++ // 60fps UI update throttle+ let now = CFAbsoluteTimeGetCurrent()+ if now - self.lastUIUpdate >= 0.016 {+ self.lastUIUpdate = now+ let fullContent = self.streamingBuffer.joined()+ self.streamingText = fullContent++ // Push to notch for real-time display+ if self.enableNotchOutput {+ NotchContentState.shared.updateCommandStreamingText(fullContent)+ }}}}}-- // Final update - join buffer once at the end- let fullContent = self.streamingBuffer.joined()++ DebugLogger.shared.info("Using LLMClient for Command Mode (streaming=\(enableStreaming), messages=\(messages.count), history=\(conversationHistory.count))", source: "CommandModeService")++ let response = try await LLMClient.shared.call(config)++ // Final UI update - ensure all content is displayed+ let fullContent = streamingBuffer.joined()if !fullContent.isEmpty {self.streamingText = fullContentif self.enableNotchOutput {@@ -993,70 +904,42 @@ final class CommandModeService: ObservableObject {}// Small delay to let the final content render, then clear- try? await Task.sleep(nanoseconds: 50_000_000) // 50ms-- self.streamingText = "" // Clear streaming text when done- self.streamingBuffer = [] // Clear buffer-+ try? await Task.sleep(nanoseconds: 50_000_000) // 50ms++ // Capture final thinking before clearing (for message storage)+ let finalThinking = response.thinking ?? (thinkingBuffer.isEmpty ? nil : thinkingBuffer.joined())++ streamingText = "" // Clear streaming text when done+ streamingThinkingText = "" // Clear thinking text when done+ streamingBuffer = [] // Clear buffer+ thinkingBuffer = [] // Clear thinking buffer+// Clear notch streaming text as wellif self.enableNotchOutput {NotchContentState.shared.updateCommandStreamingText("")}-- // If we got a tool call, parse it- if let name = toolCallName, name == "execute_terminal_command",- let argsData = toolCallArguments.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 purpose = args["purpose"] as? String- let callId = toolCallId ?? "call_\(UUID().uuidString.prefix(8))"-- return LLMResponse(- content: fullContent,- toolCall: LLMResponse.ToolCallData(- id: callId,- command: command,- workingDirectory: workDir?- .isEmpty == true ? nil : workDir,- purpose: purpose- )- )++ // Log thinking if present (for debugging)+ if let thinking = finalThinking {+ DebugLogger.shared.debug("LLM thinking tokens extracted (\(thinking.count) chars)", source: "CommandModeService")}-- // Text response only- return LLMResponse(- content: fullContent.isEmpty ? "I couldn't understand that." : fullContent,- toolCall: nil- )- }-- // MARK: - Parse Message Helper-- private func parseMessageResponse(_ message: [String: Any]) -> LLMResponse {++ // Convert LLMClient.Response to our internal LLMResponse// 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 purpose = args["purpose"] as? String- let callId = toolCall["id"] as? String ?? "call_\(UUID().uuidString.prefix(8))"-+ if let toolCalls = response.toolCalls,+ let tc = toolCalls.first,+ tc.name == "execute_terminal_command" {+ let command = tc.getString("command") ?? ""+ let workDir = tc.getOptionalString("workingDirectory")+ let purpose = tc.getString("purpose")+return LLMResponse(- content: message["content"] as? String ?? "",+ content: response.content,+ thinking: finalThinking, // Display-onlytoolCall: LLMResponse.ToolCallData(- id: callId,+ id: tc.id,command: command,- workingDirectory: workDir?- .isEmpty == true ? nil : workDir,+ workingDirectory: workDir,purpose: purpose))@@ -1064,8 +947,12 @@ final class CommandModeService: ObservableObject {// Text response onlyreturn LLMResponse(- content: message["content"] as? String ?? "I couldn't understand that.",+ content: response.content.isEmpty ? "I couldn't understand that." : response.content,+ thinking: finalThinking, // Display-onlytoolCall: nil)}}+++diff --git a/Sources/Fluid/Services/LLMClient.swift b/Sources/Fluid/Services/LLMClient.swiftnew file mode 100644index 00000000..31cbeacc--- /dev/null+++ b/Sources/Fluid/Services/LLMClient.swift@@ -0,0 +1,587 @@+import Foundation++// MARK: - Error Types++enum LLMError: Error, LocalizedError {+ case invalidURL+ case invalidResponse+ case httpError(Int, String)+ case networkError(Error)+ case encodingError++ var errorDescription: String? {+ switch self {+ case .invalidURL:+ return "Invalid URL"+ case .invalidResponse:+ return "Invalid response from LLM"+ case .httpError(let code, let message):+ return "HTTP \(code): \(message)"+ case .networkError(let error):+ return "Network error: \(error.localizedDescription)"+ case .encodingError:+ return "Failed to encode request"+ }+ }+}++// MARK: - LLMClient++/// Unified LLM communication layer for all modes (Transcription, Command, Rewrite).+/// Handles HTTP requests, SSE streaming, thinking token extraction, and tool call parsing.+@MainActor+final class LLMClient {++ static let shared = LLMClient()++ private init() {}++ // MARK: - Response Types++ struct Response {+ /// Extracted <think>...</think> content (nil if none)+ let thinking: String?+ /// Main response content with thinking tags stripped+ let content: String+ /// Parsed tool calls for agentic modes (nil if none)+ let toolCalls: [ToolCall]?+ }++ struct ToolCall {+ let id: String+ let name: String+ let arguments: [String: Any]++ /// Get a string argument by key+ func getString(_ key: String) -> String? {+ return arguments[key] as? String+ }++ /// Get an optional string argument, returning nil if empty+ func getOptionalString(_ key: String) -> String? {+ guard let value = arguments[key] as? String, !value.isEmpty else { return nil }+ return value+ }+ }++ // MARK: - Configuration++ struct Config {+ let messages: [[String: Any]]+ let model: String+ let baseURL: String+ let apiKey: String+ let streaming: Bool+ let tools: [[String: Any]]?+ let temperature: Double?++ /// Optional token limit (max_tokens or max_completion_tokens depending on model)+ var maxTokens: Int?++ /// Extra parameters to add to the request body (e.g., reasoning_effort, enable_thinking)+ /// These are model-specific and come from user settings+ var extraParameters: [String: Any]?++ // Retry configuration+ var maxRetries: Int = 3+ var retryDelayMs: Int = 200++ // Optional real-time callbacks (for streaming UI updates)+ var onThinkingStart: (() -> Void)?+ var onThinkingChunk: ((String) -> Void)?+ var onThinkingEnd: (() -> Void)?+ var onContentChunk: ((String) -> Void)?+ var onToolCallStart: ((String) -> Void)?++ init(+ messages: [[String: Any]],+ model: String,+ baseURL: String,+ apiKey: String,+ streaming: Bool = true,+ tools: [[String: Any]]? = nil,+ temperature: Double? = nil,+ maxTokens: Int? = nil,+ extraParameters: [String: Any]? = nil+ ) {+ self.messages = messages+ self.model = model+ self.baseURL = baseURL+ self.apiKey = apiKey+ self.streaming = streaming+ self.tools = tools+ self.temperature = temperature+ self.maxTokens = maxTokens+ self.extraParameters = extraParameters+ }+ }++ // MARK: - Main Entry Point++ /// Make an LLM API call with the given configuration.+ /// Supports both streaming and non-streaming modes.+ /// Handles thinking token extraction, tool call parsing, and retries.+ func call(_ config: Config) async throws -> Response {+ let request = try buildRequest(config)++ // Retry logic for transient network errors+ var lastError: Error?+ for attempt in 1...config.maxRetries {+ do {+ if config.streaming {+ return try await processStreaming(request: request, config: config)+ } else {+ return try await processNonStreaming(request: request)+ }+ } catch let error as URLError where isRetryableError(error) {+ lastError = error+ if attempt < config.maxRetries {+ // Exponential backoff+ let delayNs = UInt64(config.retryDelayMs * 1_000_000 * attempt)+ try? await Task.sleep(nanoseconds: delayNs)+ continue+ }+ } catch {+ throw error // Non-retryable error+ }+ }++ throw lastError ?? LLMError.networkError(+ NSError(domain: "LLMClient", code: -1, userInfo: [NSLocalizedDescriptionKey: "Request failed after retries"])+ )+ }++ // MARK: - Request Building++ private func buildRequest(_ config: Config) throws -> URLRequest {+ // Build endpoint URL+ let baseURL = config.baseURL.trimmingCharacters(in: .whitespacesAndNewlines)+ let endpoint: String+ if baseURL.contains("/chat/completions") ||+ baseURL.contains("/api/chat") ||+ baseURL.contains("/api/generate") {+ endpoint = baseURL+ } else {+ endpoint = baseURL.isEmpty ? "https://api.openai.com/v1/chat/completions" : "\(baseURL)/chat/completions"+ }++ guard let url = URL(string: endpoint) else {+ throw LLMError.invalidURL+ }++ // Detect if this is a local endpoint (skip auth for local)+ let isLocal = isLocalEndpoint(baseURL)++ // Build request body+ var body: [String: Any] = [+ "model": config.model,+ "messages": config.messages+ ]++ // Add temperature if provided (reasoning models like o1/o3/gpt-5 don't support it)+ if let temp = config.temperature {+ body["temperature"] = temp+ }++ // Add tools if provided+ if let tools = config.tools, !tools.isEmpty {+ body["tools"] = tools+ body["tool_choice"] = "auto"+ }++ // Add streaming flag+ if config.streaming {+ body["stream"] = true+ }++ // Add extra parameters in layers:+ // 1. Model-specific parameters (from ThinkingParserFactory)+ // 2. User-provided parameters (can override model defaults)++ // Layer 1: Model-specific parameters (e.g., enable_thinking for Nemotron)+ if let modelExtras = ThinkingParserFactory.getExtraParameters(for: config.model) {+ for (key, value) in modelExtras {+ body[key] = value+ }+ }++ // Layer 2: User-provided extra parameters (e.g., reasoning_effort from settings)+ if let extras = config.extraParameters {+ for (key, value) in extras {+ body[key] = value+ }+ }++ // Final Layer: Common parameters with model-specific keys+ if let tokens = config.maxTokens {+ if SettingsStore.shared.isReasoningModel(config.model) {+ body["max_completion_tokens"] = tokens+ } else {+ body["max_tokens"] = tokens+ }+ }+++ // Serialize to JSON+ guard let jsonData = try? JSONSerialization.data(withJSONObject: body, options: []) else {+ throw LLMError.encodingError+ }++ // Log the request for debugging+ let messageCount = config.messages.count+ if let bodyStr = String(data: jsonData, encoding: .utf8) {+ let truncated = bodyStr.count > 500 ? String(bodyStr.prefix(500)) + "..." : bodyStr+ DebugLogger.shared.debug("LLMClient: Request (\(messageCount) messages, model=\(config.model), streaming=\(config.streaming)): \(truncated)", source: "LLMClient")+ }++ // Build URLRequest+ 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 && !config.apiKey.isEmpty {+ request.addValue("Bearer \(config.apiKey)", forHTTPHeaderField: "Authorization")+ }++ request.httpBody = jsonData++ return request+ }++ // MARK: - Non-Streaming Response++ private func processNonStreaming(request: URLRequest) async throws -> Response {+ DebugLogger.shared.debug("LLMClient: Making non-streaming request to \(request.url?.absoluteString ?? "unknown")", source: "LLMClient")++ 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("LLMClient: HTTP error \(http.statusCode): \(errText.prefix(200))", source: "LLMClient")+ throw LLMError.httpError(http.statusCode, errText)+ }++ DebugLogger.shared.debug("LLMClient: Non-streaming response received (\(data.count) bytes)", source: "LLMClient")++ 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 LLMError.invalidResponse+ }++ return parseMessageResponse(message)+ }+++ private func processStreaming(request: URLRequest, config: Config) async throws -> Response {+ DebugLogger.shared.debug("LLMClient: Starting streaming request to \(request.url?.absoluteString ?? "unknown")", source: "LLMClient")++ let (bytes, response) = try await URLSession.shared.bytes(for: request)++ // Check for HTTP errors+ if let http = response as? HTTPURLResponse, http.statusCode >= 400 {+ var errorData = Data()+ for try await byte in bytes {+ errorData.append(byte)+ }+ let errText = String(data: errorData, encoding: .utf8) ?? "Unknown error"+ throw LLMError.httpError(http.statusCode, errText)+ }++ // Create the appropriate parser for this model+ var parser = ThinkingParserFactory.createParser(for: config.model)++ // Streaming state+ var state = ThinkingParserState.initial+ var thinkingBuffer: [String] = []+ var contentBuffer: [String] = []+ var tagDetectionBuffer = ""++ // Tool call accumulation+ var toolCallId: String?+ var toolCallName: String?+ var toolCallArguments = ""++ // Process SSE lines+ for try await rawLine in bytes.lines {+ let line = rawLine.trimmingCharacters(in: .whitespaces)+ guard line.hasPrefix("data:") else { continue }++ var jsonString = String(line.dropFirst(5))+ if jsonString.hasPrefix(" ") {+ jsonString = String(jsonString.dropFirst(1))+ }++ if jsonString.trimmingCharacters(in: .whitespaces) == "[DONE]" {+ continue+ }++ guard let jsonData = jsonString.data(using: .utf8),+ let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],+ let choices = json["choices"] as? [[String: Any]],+ let delta = choices.first?["delta"] as? [String: Any] else {+ continue+ }++ // Handle reasoning_content field (DeepSeek style - separate from text content)+ if let reasoning = delta["reasoning_content"] as? String {+ if state == .initial {+ state = .inThinking+ config.onThinkingStart?()+ }+ thinkingBuffer.append(reasoning)+ config.onThinkingChunk?(reasoning)+ }++ // Handle content with potential <think> tags+ if let content = delta["content"] as? String {+ // Debug: Log first few chunks and any chunk containing think tags+ let containsThinkTag = content.contains("<think") || content.contains("</think") || content.contains("<thinking") || content.contains("</thinking")+ if thinkingBuffer.count + contentBuffer.count < 8 || containsThinkTag {+ let escaped = content.replacingOccurrences(of: "\n", with: "\\n")+ let marker = containsThinkTag ? " [HAS THINK TAG!]" : ""+ DebugLogger.shared.debug("LLMClient: Chunk '\(escaped)'\(marker)", source: "LLMClient")+ }++ let previousState = state+ let (newState, thinkChunk, contentChunk) = parser.processChunk(+ content,+ currentState: state,+ tagBuffer: &tagDetectionBuffer+ )++ // Handle state transitions for callbacks+ if previousState != .inThinking && newState == .inThinking {+ DebugLogger.shared.debug("LLMClient: State transition → inThinking", source: "LLMClient")+ config.onThinkingStart?()+ }+ if previousState == .inThinking && newState == .inContent {+ DebugLogger.shared.debug("LLMClient: State transition → inContent", source: "LLMClient")+ config.onThinkingEnd?()+ }+ state = newState++ // Accumulate and callback+ if !thinkChunk.isEmpty {+ thinkingBuffer.append(thinkChunk)+ config.onThinkingChunk?(thinkChunk)+ }+ if !contentChunk.isEmpty {+ contentBuffer.append(contentChunk)+ config.onContentChunk?(contentChunk)+ }+ }++ // Handle tool calls (streamed in parts)+ if let toolCalls = delta["tool_calls"] as? [[String: Any]],+ let tc = toolCalls.first {+ if let id = tc["id"] as? String {+ toolCallId = id+ }+ if let function = tc["function"] as? [String: Any] {+ if let name = function["name"] as? String {+ toolCallName = name+ config.onToolCallStart?(name)+ }+ if let args = function["arguments"] as? String {+ toolCallArguments += args+ }+ }+ }+ }++ // Finalize - flush any remaining content in tagDetectionBuffer+ if !tagDetectionBuffer.isEmpty {+ // Anything left in the buffer should go to the appropriate place+ if state == .inThinking {+ thinkingBuffer.append(tagDetectionBuffer)+ config.onThinkingChunk?(tagDetectionBuffer)+ DebugLogger.shared.debug("LLMClient: Flushing remaining tagBuffer to thinking (\(tagDetectionBuffer.count) chars)", source: "LLMClient")+ } else {+ contentBuffer.append(tagDetectionBuffer)+ config.onContentChunk?(tagDetectionBuffer)+ DebugLogger.shared.debug("LLMClient: Flushing remaining tagBuffer to content (\(tagDetectionBuffer.count) chars)", source: "LLMClient")+ }+ }++ // Use parser's finalize to get final clean thinking and content+ let (thinkingText, contentText) = parser.finalize(thinkingBuffer: thinkingBuffer, contentBuffer: contentBuffer, finalState: state)++ DebugLogger.shared.debug("LLMClient: Streaming complete. Thinking: \(thinkingText.count) chars, Content: \(contentText.count) chars", source: "LLMClient")++ // Build tool calls array+ var parsedToolCalls: [ToolCall]? = nil+ if let name = toolCallName,+ let argsData = toolCallArguments.data(using: .utf8),+ let args = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any] {+ parsedToolCalls = [+ ToolCall(+ id: toolCallId ?? "call_\(UUID().uuidString.prefix(8))",+ name: name,+ arguments: args+ )+ ]+ DebugLogger.shared.debug("LLMClient: Parsed tool call: \(name)", source: "LLMClient")+ }++ DebugLogger.shared.debug("LLMClient: Returning response. Content length: \(contentText.count), Has thinking: \(thinkingText.isEmpty ? "No" : "Yes (\(thinkingText.count) chars)")", source: "LLMClient")++ return Response(+ thinking: thinkingText.isEmpty ? nil : thinkingText,+ content: contentText,+ toolCalls: parsedToolCalls+ )+ }+++ // MARK: - Parse Non-Streaming Message++ private func parseMessageResponse(_ message: [String: Any]) -> Response {+ // Extract content+ let rawContent = message["content"] as? String ?? ""++ // Check for tool calls+ var parsedToolCalls: [ToolCall]? = nil+ if let toolCalls = message["tool_calls"] as? [[String: Any]] {+ parsedToolCalls = toolCalls.compactMap { tc -> ToolCall? in+ guard let function = tc["function"] as? [String: Any],+ let name = function["name"] as? String,+ let argsString = function["arguments"] as? String,+ let argsData = argsString.data(using: .utf8),+ let args = try? JSONSerialization.jsonObject(with: argsData) as? [String: Any] else {+ return nil+ }+ let id = tc["id"] as? String ?? "call_\(UUID().uuidString.prefix(8))"+ return ToolCall(id: id, name: name, arguments: args)+ }+ if parsedToolCalls?.isEmpty == true {+ parsedToolCalls = nil+ }+ }++ // Strip thinking tags and extract thinking content+ let (thinking, cleanedContent) = stripThinkingTags(rawContent)++ // Also check for reasoning_content field (DeepSeek style)+ let reasoningContent = message["reasoning_content"] as? String+ let finalThinking = [thinking, reasoningContent].compactMap { $0 }.filter { !$0.isEmpty }.joined(separator: "\n")++ return Response(+ thinking: finalThinking.isEmpty ? nil : finalThinking,+ content: cleanedContent.isEmpty ? rawContent : cleanedContent,+ toolCalls: parsedToolCalls+ )+ }++ // MARK: - Thinking Token Extraction++ /// Pattern matches both <think>...</think> and <thinking>...</thinking> including multiline+ private static let thinkingTagPattern = #"<think(?:ing)?>([\s\S]*?)</think(?:ing)?>"#++ /// Pattern for orphan closing tags with content before them (no opening tag)+ private static let orphanThinkingPattern = #"^([\s\S]*?)</think(?:ing)?>"#++ /// Strips thinking tags from text and returns (thinking, cleanedContent)+ func stripThinkingTags(_ text: String) -> (thinking: String, content: String) {+ var workingText = text+ var thinking = ""++ // First, handle proper <think>...</think> pairs+ if let regex = try? NSRegularExpression(pattern: Self.thinkingTagPattern, options: []) {+ let range = NSRange(workingText.startIndex..., in: workingText)+ let matches = regex.matches(in: workingText, options: [], range: range)++ for match in matches {+ if let thinkRange = Range(match.range(at: 1), in: workingText) {+ thinking += String(workingText[thinkRange])+ }+ }++ workingText = regex.stringByReplacingMatches(in: workingText, options: [], range: range, withTemplate: "")+ }++ // Second, handle orphan closing tags (content before </think> without opening tag)+ // This handles cases like "We have a request...</think>Hello!"+ if let orphanRegex = try? NSRegularExpression(pattern: Self.orphanThinkingPattern, options: []) {+ let range = NSRange(workingText.startIndex..., in: workingText)+ let matches = orphanRegex.matches(in: workingText, options: [], range: range)++ for match in matches {+ if let thinkRange = Range(match.range(at: 1), in: workingText) {+ thinking += String(workingText[thinkRange])+ }+ }++ workingText = orphanRegex.stringByReplacingMatches(in: workingText, options: [], range: range, withTemplate: "")+ }++ // Also remove any stray </think> or </thinking> tags that might remain+ workingText = workingText.replacingOccurrences(of: "</think>", with: "")+ workingText = workingText.replacingOccurrences(of: "</thinking>", with: "")+ workingText = workingText.replacingOccurrences(of: "<think>", with: "")+ workingText = workingText.replacingOccurrences(of: "<thinking>", with: "")++ let cleaned = workingText.trimmingCharacters(in: .whitespacesAndNewlines)++ return (thinking, cleaned)+ }++ // MARK: - Helper Methods++ /// Check if an error is retryable (transient network issues)+ private func isRetryableError(_ error: URLError) -> Bool {+ switch error.code {+ case .notConnectedToInternet,+ .timedOut,+ .networkConnectionLost,+ .cannotFindHost,+ .cannotConnectToHost,+ .dnsLookupFailed:+ return true+ default:+ return false+ }+ }++ /// Check if a URL is a local/private endpoint+ private func isLocalEndpoint(_ urlString: String) -> Bool {+ guard let url = URL(string: urlString),+ let host = url.host else { return false }++ let hostLower = host.lowercased()++ // Localhost+ if hostLower == "localhost" || hostLower == "127.0.0.1" {+ return true+ }++ // 127.x.x.x+ if hostLower.hasPrefix("127.") {+ return true+ }++ // 10.x.x.x (Private Class A)+ if hostLower.hasPrefix("10.") {+ return true+ }++ // 192.168.x.x (Private Class C)+ if hostLower.hasPrefix("192.168.") {+ return true+ }++ // 172.16.x.x - 172.31.x.x (Private Class B)+ 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+ }+}diff --git a/Sources/Fluid/Services/RewriteModeService.swift b/Sources/Fluid/Services/RewriteModeService.swiftindex 48768901..1a0ce263 100644--- a/Sources/Fluid/Services/RewriteModeService.swift+++ b/Sources/Fluid/Services/RewriteModeService.swift@@ -6,13 +6,15 @@ import Foundationfinal class RewriteModeService: ObservableObject {@Published var originalText: String = ""@Published var rewrittenText: String = ""+ @Published var streamingThinkingText: String = "" // Real-time thinking tokens for UI@Published var isProcessing = false@Published var conversationHistory: [Message] = []@Published var isWriteMode: Bool = false // true = no text selected (write/improve), false = text selected (rewrite)private let textSelectionService = TextSelectionService.sharedprivate let typingService = TypingService()-+ private var thinkingBuffer: [String] = [] // Buffer thinking tokens+struct Message: Identifiable, Equatable {let id = UUID()let role: Role@@ -104,10 +106,12 @@ final class RewriteModeService: ObservableObject {}func clearState() {- self.originalText = ""- self.rewrittenText = ""- self.conversationHistory = []- self.isWriteMode = false+ originalText = ""+ rewrittenText = ""+ streamingThinkingText = ""+ conversationHistory = []+ isWriteMode = false+ thinkingBuffer = []}// MARK: - LLM Integration@@ -176,7 +180,8 @@ final class RewriteModeService: ObservableObject {Output ONLY the rewritten text. No explanations, no quotes around the text, no preamble."""}-++ // Build messages array for LLMClientvar apiMessages: [[String: Any]] = [["role": "system", "content": systemPrompt],]@@ -189,110 +194,75 @@ final class RewriteModeService: ObservableObject {let enableStreaming = settings.enableAIStreaming// Reasoning models (o1, o3, gpt-5) don't support temperature parameter at all- let isReasoningModel = model.hasPrefix("o1") || model.hasPrefix("o3") || model.hasPrefix("gpt-5")-- var body: [String: Any] = [- "model": model,- "messages": apiMessages,- ]-- // Only add temperature for non-reasoning models- if !isReasoningModel {- body["temperature"] = 0.7- }-- if enableStreaming {- // TODO: Streamed text is still buffered; add incremental UI updates so write mode visibly streams.- body["stream"] = true- }-- 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"])+ let isReasoningModel = settings.isReasoningModel(model)++ // Get reasoning config for this model (e.g., reasoning_effort, enable_thinking)+ let reasoningConfig = settings.getReasoningConfig(forModel: model, provider: providerID)+ var extraParams: [String: Any]? = nil+ if let rConfig = reasoningConfig, rConfig.isEnabled {+ if rConfig.parameterName == "enable_thinking" {+ extraParams = [rConfig.parameterName: rConfig.parameterValue == "true"]+ } else {+ extraParams = [rConfig.parameterName: rConfig.parameterValue]+ }+ DebugLogger.shared.debug("Added reasoning param: \(rConfig.parameterName)=\(rConfig.parameterValue)", source: "RewriteModeService")}-- 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)-++ // Build LLMClient configuration+ var config = LLMClient.Config(+ messages: apiMessages,+ model: model,+ baseURL: baseURL,+ apiKey: apiKey,+ streaming: enableStreaming,+ tools: nil,+ temperature: isReasoningModel ? nil : 0.7,+ extraParameters: extraParams+ )++ // Add real-time streaming callbacks for UI updatesif enableStreaming {- DebugLogger.shared.info("Using STREAMING mode for Write/Rewrite", source: "RewriteModeService")- return try await self.processStreamingResponse(request: request)- } else {- 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])+ // Thinking tokens callback+ config.onThinkingChunk = { [weak self] chunk in+ Task { @MainActor in+ self?.thinkingBuffer.append(chunk)+ self?.streamingThinkingText = self?.thinkingBuffer.joined() ?? ""+ }}-- 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"]- )++ // Content callback+ config.onContentChunk = { [weak self] chunk in+ Task { @MainActor in+ self?.rewrittenText += chunk+ }}-- return content}- }-- // MARK: - Streaming Response Handler-- private func processStreamingResponse(request: URLRequest) async throws -> String {- let (bytes, response) = try await URLSession.shared.bytes(for: request)-- if let http = response as? HTTPURLResponse, http.statusCode >= 400 {- var errorData = Data()- for try await byte in bytes {- errorData.append(byte)- }- let errText = String(data: errorData, encoding: .utf8) ?? "Unknown error"- throw NSError(domain: "RewriteMode", code: http.statusCode, userInfo: [NSLocalizedDescriptionKey: errText])++ DebugLogger.shared.info("Using LLMClient for Write/Rewrite (streaming=\(enableStreaming))", source: "RewriteModeService")++ // Clear streaming buffers before starting+ if enableStreaming {+ rewrittenText = ""+ streamingThinkingText = ""+ thinkingBuffer = []}-- var fullContent = ""-- // Use efficient line-based iteration instead of byte-by-byte- for try await rawLine in bytes.lines {- let line = rawLine.trimmingCharacters(in: .whitespaces)-- guard line.hasPrefix("data:") else { continue }-- var jsonString = String(line.dropFirst(5))- if jsonString.hasPrefix(" ") {- jsonString = String(jsonString.dropFirst(1))- }-- if jsonString.trimmingCharacters(in: .whitespaces) == "[DONE]" {- continue- }-- if let jsonData = jsonString.data(using: .utf8),- let json = try? JSONSerialization.jsonObject(with: jsonData) as? [String: Any],- let choices = json["choices"] as? [[String: Any]],- let firstChoice = choices.first,- let delta = firstChoice["delta"] as? [String: Any],- let content = delta["content"] as? String- {- fullContent += content- // Update UI in real-time for streaming feedback- self.rewrittenText = fullContent- }++ let response = try await LLMClient.shared.call(config)++ // Clear thinking display after response complete+ streamingThinkingText = ""+ thinkingBuffer = []++ // Log thinking if present (for debugging)+ if let thinking = response.thinking {+ DebugLogger.shared.debug("LLM thinking tokens extracted (\(thinking.count) chars)", source: "RewriteModeService")}-- DebugLogger.shared.debug(- "Streaming complete. Content length: \(fullContent.count)",- source: "RewriteModeService"- )- return fullContent.isEmpty ? "" : fullContent++ DebugLogger.shared.debug("Response complete. Content length: \(response.content.count)", source: "RewriteModeService")++ // For non-streaming, we return the content directly+ // For streaming, rewrittenText is already updated via callback,+ // but we return the final content for consistency+ return response.content}}diff --git a/Sources/Fluid/Services/ThinkingParsers.swift b/Sources/Fluid/Services/ThinkingParsers.swiftnew file mode 100644index 00000000..5d601e08--- /dev/null+++ b/Sources/Fluid/Services/ThinkingParsers.swift@@ -0,0 +1,293 @@+import Foundation++// MARK: - Thinking Parser Protocol++/// Protocol for parsing thinking tokens from LLM streaming responses.+/// Different model families have different patterns for thinking tokens.+protocol ThinkingParser {+ /// Process a content chunk during streaming.+ /// - Parameters:+ /// - chunk: The new content chunk from the stream+ /// - currentState: Current parsing state+ /// - tagBuffer: Buffer for incomplete tag detection (inout)+ /// - Returns: Tuple of (newState, thinkingChunk, contentChunk)+ mutating func processChunk(+ _ chunk: String,+ currentState: ThinkingParserState,+ tagBuffer: inout String+ ) -> (ThinkingParserState, String, String)++ /// Post-process the final buffers after streaming completes.+ /// Some parsers may need to do final cleanup.+ /// - Parameters:+ /// - thinkingBuffer: Accumulated thinking chunks+ /// - contentBuffer: Accumulated content chunks+ /// - finalState: The state at the end of streaming+ /// - Returns: Tuple of cleaned (thinking, content) strings+ func finalize(thinkingBuffer: [String], contentBuffer: [String], finalState: ThinkingParserState) -> (thinking: String, content: String)+}++// MARK: - Parser State++enum ThinkingParserState {+ case initial // Haven't determined if we're in thinking or content yet+ case inThinking // Currently inside thinking section+ case inContent // Currently in main content+}++// MARK: - Parser Factory++/// Factory to create the appropriate parser and extra parameters based on model name+enum ThinkingParserFactory {++ /// Create a parser appropriate for the given model+ static func createParser(for model: String) -> ThinkingParser {+ let modelLower = model.lowercased()++ // Nemotron/Nemo models: no opening <think>, just </think> as separator+ if modelLower.contains("nemotron") || modelLower.contains("nemo") {+ DebugLogger.shared.debug("ThinkingParser: Using NemoParser for model '\(model)'", source: "LLMClient")+ return NemoThinkingParser()+ }++ // Qwen models with thinking: use standard <think>...</think> pattern+ if modelLower.contains("qwen") && (modelLower.contains("think") || modelLower.contains("qwq")) {+ DebugLogger.shared.debug("ThinkingParser: Using StandardParser for Qwen model '\(model)'", source: "LLMClient")+ return StandardThinkingParser()+ }++ // DeepSeek models: use standard pattern (they also have reasoning_content field handled separately)+ if modelLower.contains("deepseek") {+ DebugLogger.shared.debug("ThinkingParser: Using StandardParser for DeepSeek model '\(model)'", source: "LLMClient")+ return StandardThinkingParser()+ }++ // Default: Standard parser with <think>...</think> pattern+ DebugLogger.shared.debug("ThinkingParser: Using StandardParser (default) for model '\(model)'", source: "LLMClient")+ return StandardThinkingParser()+ }++ /// Get model-specific extra parameters for the API request.+ /// These are parameters beyond the standard model/messages/temperature.+ static func getExtraParameters(for model: String) -> [String: Any]? {+ let modelLower = model.lowercased()++ // Nemotron/Nemo models: require enable_thinking flag+ if modelLower.contains("nemotron") || modelLower.contains("nemo") {+ DebugLogger.shared.debug("ThinkingParser: Adding enable_thinking=true for Nemotron model '\(model)'", source: "LLMClient")+ return [+ "enable_thinking": true+ // "truncate_history_thinking": false // Optional: could expose this in settings+ ]+ }++ // DeepSeek R1 models: may need reasoning parameters+ if modelLower.contains("deepseek") && modelLower.contains("r1") {+ DebugLogger.shared.debug("ThinkingParser: Adding reasoning params for DeepSeek R1 model '\(model)'", source: "LLMClient")+ return [+ "enable_reasoning": true+ ]+ }++ // Claude with thinking: requires thinking parameters (handled via Anthropic API differently)+ // OpenAI o1/o3 with reasoning: uses reasoning_effort parameter++ return nil+ }+}+++// MARK: - Standard Thinking Parser++/// Standard parser for models that use `<think>...</think>` or `<thinking>...</thinking>` tags.+/// Used by: DeepSeek, Qwen, Claude (when thinking enabled), most open models+struct StandardThinkingParser: ThinkingParser {++ mutating func processChunk(+ _ chunk: String,+ currentState: ThinkingParserState,+ tagBuffer: inout String+ ) -> (ThinkingParserState, String, String) {++ // Add chunk to buffer for tag detection+ tagBuffer += chunk++ var thinkingChunk = ""+ var contentChunk = ""+ var newState = currentState++ // Check for opening tag+ if newState != .inThinking {+ if let openRange = tagBuffer.range(of: "<think>") ?? tagBuffer.range(of: "<thinking>") {+ // Content before the tag goes to content+ let beforeTag = String(tagBuffer[..<openRange.lowerBound])+ if !beforeTag.isEmpty {+ contentChunk += beforeTag+ }+ // Remove processed part including open tag+ tagBuffer = String(tagBuffer[openRange.upperBound...])+ newState = .inThinking+ }+ }++ // Check for closing tag+ if newState == .inThinking {+ if let closeRange = tagBuffer.range(of: "</think>") ?? tagBuffer.range(of: "</thinking>") {+ // Content before the closing tag is thinking+ let beforeClose = String(tagBuffer[..<closeRange.lowerBound])+ if !beforeClose.isEmpty {+ thinkingChunk += beforeClose+ }+ // Content after closing tag goes to content+ tagBuffer = String(tagBuffer[closeRange.upperBound...])+ newState = .inContent++ // Any remaining buffer is content+ if !tagBuffer.isEmpty {+ contentChunk += tagBuffer+ tagBuffer = ""+ }+ } else {+ // Still in thinking, emit what we have (minus potential partial tag)+ // Keep last 15 chars in buffer to detect partial closing tags+ let safeLength = max(0, tagBuffer.count - 15)+ if safeLength > 0 {+ let safeIndex = tagBuffer.index(tagBuffer.startIndex, offsetBy: safeLength)+ thinkingChunk = String(tagBuffer[..<safeIndex])+ tagBuffer = String(tagBuffer[safeIndex...])+ }+ }+ } else if newState == .inContent || newState == .initial {+ // Not in thinking mode, emit content (minus potential partial open tag)+ let safeLength = max(0, tagBuffer.count - 15)+ if safeLength > 0 {+ let safeIndex = tagBuffer.index(tagBuffer.startIndex, offsetBy: safeLength)+ contentChunk = String(tagBuffer[..<safeIndex])+ tagBuffer = String(tagBuffer[safeIndex...])+ }+ }++ return (newState, thinkingChunk, contentChunk)+ }++ func finalize(thinkingBuffer: [String], contentBuffer: [String], finalState: ThinkingParserState) -> (thinking: String, content: String) {+ let thinking = thinkingBuffer.joined()+ var content = contentBuffer.joined()++ // Strip any remaining stray tags+ content = content.replacingOccurrences(of: "</think>", with: "")+ content = content.replacingOccurrences(of: "</thinking>", with: "")+ content = content.replacingOccurrences(of: "<think>", with: "")+ content = content.replacingOccurrences(of: "<thinking>", with: "")+ content = content.trimmingCharacters(in: .whitespacesAndNewlines)++ return (thinking, content)+ }+}++// MARK: - Nemo Thinking Parser++/// Parser for Nemotron/Nemo models that output thinking WITHOUT an opening <think> tag.+/// Pattern: `thinking content</think>actual response`+/// Everything before `</think>` is thinking, everything after is content.+struct NemoThinkingParser: ThinkingParser {++ mutating func processChunk(+ _ chunk: String,+ currentState: ThinkingParserState,+ tagBuffer: inout String+ ) -> (ThinkingParserState, String, String) {++ // Add chunk to buffer+ tagBuffer += chunk++ var thinkingChunk = ""+ var contentChunk = ""+ var newState = currentState++ // For Nemo: we're in thinking mode until we see </think>+ // Initial state = thinking (no opening tag needed)+ if newState == .initial {+ newState = .inThinking+ }++ if newState == .inThinking {+ // Look for closing tag+ if let closeRange = tagBuffer.range(of: "</think>") ?? tagBuffer.range(of: "</thinking>") {+ // Everything before the tag is thinking+ let beforeClose = String(tagBuffer[..<closeRange.lowerBound])+ if !beforeClose.isEmpty {+ thinkingChunk = beforeClose+ }++ // Everything after is content+ tagBuffer = String(tagBuffer[closeRange.upperBound...])+ newState = .inContent++ // Emit remaining buffer as content+ if !tagBuffer.isEmpty {+ contentChunk = tagBuffer+ tagBuffer = ""+ }++ DebugLogger.shared.debug("NemoParser: Found </think>. Thinking: \(thinkingChunk.count) chars, Content: \(contentChunk.count) chars", source: "LLMClient")+ } else {+ // Still waiting for </think>, emit thinking (minus potential partial tag)+ let safeLength = max(0, tagBuffer.count - 15)+ if safeLength > 0 {+ let safeIndex = tagBuffer.index(tagBuffer.startIndex, offsetBy: safeLength)+ thinkingChunk = String(tagBuffer[..<safeIndex])+ tagBuffer = String(tagBuffer[safeIndex...])+ }+ }+ } else if newState == .inContent {+ // Already past the </think>, everything is content+ contentChunk = tagBuffer+ tagBuffer = ""+ }++ return (newState, thinkingChunk, contentChunk)+ }++ func finalize(thinkingBuffer: [String], contentBuffer: [String], finalState: ThinkingParserState) -> (thinking: String, content: String) {+ var thinking = thinkingBuffer.joined()+ var content = contentBuffer.joined()++ // IMPORTANT: If we're still in .inThinking state at the end, it means+ // we NEVER saw a </think> tag. This indicates thinking mode was OFF+ // (server didn't use thinking). All "thinking" is actually content!+ if finalState == .inThinking {+ // Move all thinking to content+ content = thinking + content+ thinking = ""+ DebugLogger.shared.debug("NemoParser finalize: No </think> found - treating all as content (\(content.count) chars)", source: "LLMClient")+ }++ // Clean up any stray tags+ content = content.replacingOccurrences(of: "</think>", with: "")+ content = content.replacingOccurrences(of: "</thinking>", with: "")+ content = content.trimmingCharacters(in: .whitespacesAndNewlines)++ return (thinking, content)+ }+}++// MARK: - No Thinking Parser++/// Parser for models that don't use thinking tokens at all.+/// Everything is content.+struct NoThinkingParser: ThinkingParser {++ mutating func processChunk(+ _ chunk: String,+ currentState: ThinkingParserState,+ tagBuffer: inout String+ ) -> (ThinkingParserState, String, String) {+ // Everything is content+ return (.inContent, "", chunk)+ }++ func finalize(thinkingBuffer: [String], contentBuffer: [String], finalState: ThinkingParserState) -> (thinking: String, content: String) {+ return ("", contentBuffer.joined())+ }+}diff --git a/Sources/Fluid/UI/AISettingsView.swift b/Sources/Fluid/UI/AISettingsView.swiftindex dccc0dcd..c7910dc4 100644--- a/Sources/Fluid/UI/AISettingsView.swift+++ b/Sources/Fluid/UI/AISettingsView.swift@@ -116,14 +116,13 @@ struct AISettingsView: View {// MARK: - Load Settingsprivate func loadSettings() {- self.selectedProviderID = SettingsStore.shared.selectedProviderID- self.updateCurrentProvider()-- self.enableAIProcessing = SettingsStore.shared.enableAIProcessing- self.availableModelsByProvider = SettingsStore.shared.availableModelsByProvider- self.selectedModelByProvider = SettingsStore.shared.selectedModelByProvider- self.providerAPIKeys = SettingsStore.shared.providerAPIKeys- self.savedProviders = SettingsStore.shared.savedProviders+ selectedProviderID = SettingsStore.shared.selectedProviderID++ enableAIProcessing = SettingsStore.shared.enableAIProcessing+ availableModelsByProvider = SettingsStore.shared.availableModelsByProvider+ selectedModelByProvider = SettingsStore.shared.selectedModelByProvider+ providerAPIKeys = SettingsStore.shared.providerAPIKeys+ savedProviders = SettingsStore.shared.savedProviders// Normalize provider keysvar normalized: [String: [String]] = [:]@@ -151,23 +150,32 @@ struct AISettingsView: View {}self.selectedModelByProvider = normalizedSelSettingsStore.shared.selectedModelByProvider = normalizedSel-- // Determine initial model list++ // Determine initial model list AND set baseURL BEFORE calling updateCurrentProviderif let saved = savedProviders.first(where: { $0.id == selectedProviderID }) {- self.availableModels = saved.models- self.openAIBaseURL = saved.baseURL- } else if let stored = availableModelsByProvider[currentProvider], !stored.isEmpty {- self.availableModels = stored+ availableModels = saved.models+ openAIBaseURL = saved.baseURL // Set this FIRST+ } else if selectedProviderID == "openai" {+ openAIBaseURL = "https://api.openai.com/v1"+ availableModels = availableModelsByProvider["openai"] ?? defaultModels(for: "openai")+ } else if selectedProviderID == "groq" {+ openAIBaseURL = "https://api.groq.com/openai/v1"+ availableModels = availableModelsByProvider["groq"] ?? defaultModels(for: "groq")} else {self.availableModels = self.defaultModels(for: self.providerKey(for: self.selectedProviderID))}-- // Restore selected model++ // NOW update currentProvider after openAIBaseURL is set correctly+ updateCurrentProvider()++ // Restore selected model using the correct currentProviderif let sel = selectedModelByProvider[currentProvider], availableModels.contains(sel) {self.selectedModel = sel} else if let first = availableModels.first {self.selectedModel = first}++ DebugLogger.shared.debug("loadSettings complete: provider=\(selectedProviderID), currentProvider=\(currentProvider), model=\(selectedModel), baseURL=\(openAIBaseURL)", source: "AISettingsView")}// MARK: - Speech Recognition Card@@ -421,11 +429,7 @@ struct AISettingsView: View {return config.isEnabled}}- let modelLower = self.selectedModel.lowercased()- return modelLower.hasPrefix("gpt-5") || modelLower.contains("gpt-5.") ||- modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") ||- modelLower.contains("gpt-oss") || modelLower.hasPrefix("openai/") ||- (modelLower.contains("deepseek") && modelLower.contains("reasoner"))+ return SettingsStore.shared.isReasoningModel(selectedModel)}private func addNewModel() {@@ -598,7 +602,10 @@ struct AISettingsView: View {} else {fullURL = endpoint + "/chat/completions"}-++ // Debug logging to diagnose test failures+ DebugLogger.shared.debug("testAPIConnection: provider=\(selectedProviderID), model=\(selectedModel), baseURL=\(endpoint), fullURL=\(fullURL)", source: "AISettingsView")+guard let url = URL(string: fullURL) else {await MainActor.run {self.connectionStatus = .failed@@ -607,16 +614,11 @@ struct AISettingsView: View {return}- let provKey = self.providerKey(for: self.selectedProviderID)- let reasoningConfig = SettingsStore.shared.getReasoningConfig(- forModel: self.selectedModel,- provider: provKey- )-- let modelLower = self.selectedModel.lowercased()- let usesMaxCompletionTokens = modelLower.hasPrefix("gpt-5") || modelLower.contains("gpt-5.") ||- modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3")-+ let provKey = providerKey(for: selectedProviderID)+ let reasoningConfig = SettingsStore.shared.getReasoningConfig(forModel: selectedModel, provider: provKey)++ let usesMaxCompletionTokens = SettingsStore.shared.isReasoningModel(selectedModel)+var requestDict: [String: Any] = ["model": selectedModel,"messages": [["role": "user", "content": "test"]],@@ -737,8 +739,9 @@ struct AISettingsView: View {self.aiEnhancementToggle// Streaming Toggle- if self.enableAIProcessing && self.selectedProviderID != "apple-intelligence" {- self.streamingToggle+ if enableAIProcessing && selectedProviderID != "apple-intelligence" {+ streamingToggle+ showThinkingTokensToggle}// API Key Warning@@ -808,7 +811,31 @@ struct AISettingsView: View {.padding(.horizontal, 4)}}-++ private var showThinkingTokensToggle: some View {+ Group {+ Divider().padding(.vertical, 3)+ HStack(alignment: .top, spacing: 16) {+ VStack(alignment: .leading, spacing: 4) {+ Text("Show Thinking Tokens")+ .font(.system(size: 15, weight: .semibold))+ .foregroundStyle(theme.palette.primaryText)+ Text("Display AI reasoning in Command and Rewrite modes (when available)")+ .font(.system(size: 13))+ .foregroundStyle(theme.palette.secondaryText)+ }+ Spacer()+ Toggle("", isOn: Binding(+ get: { SettingsStore.shared.showThinkingTokens },+ set: { SettingsStore.shared.showThinkingTokens = $0 }+ ))+ .toggleStyle(.switch)+ .labelsHidden()+ }+ .padding(.horizontal, 4)+ }+ }+private var apiKeyWarningView: some View {HStack(spacing: 10) {Image(systemName: "exclamationmark.triangle.fill")@@ -1242,25 +1269,58 @@ struct AISettingsView: View {HStack(spacing: 12) {VStack(alignment: .leading, spacing: 4) {Text("Parameter Name").font(.caption2).foregroundStyle(.secondary)- Picker("", selection: self.$editingReasoningParamName) {+ Picker("", selection: Binding(+ get: {+ // Map current value to picker options+ if editingReasoningParamName == "reasoning_effort" { return "reasoning_effort" }+ else if editingReasoningParamName == "enable_thinking" { return "enable_thinking" }+ else { return "custom" }+ },+ set: { newValue in+ if newValue == "custom" {+ // Keep the current value for custom editing+ if editingReasoningParamName == "reasoning_effort" || editingReasoningParamName == "enable_thinking" {+ editingReasoningParamName = ""+ }+ } else {+ editingReasoningParamName = newValue+ }+ }+ )) {Text("reasoning_effort").tag("reasoning_effort")Text("enable_thinking").tag("enable_thinking")+ Text("Custom...").tag("custom")}.pickerStyle(.menu).labelsHidden().frame(width: 150)}++ // Show TextField for custom parameter name+ if editingReasoningParamName != "reasoning_effort" && editingReasoningParamName != "enable_thinking" {+ VStack(alignment: .leading, spacing: 4) {+ Text("Custom Name").font(.caption2).foregroundStyle(.secondary)+ TextField("e.g., thinking_budget", text: $editingReasoningParamName)+ .textFieldStyle(.roundedBorder)+ .frame(width: 150)+ }+ }+VStack(alignment: .leading, spacing: 4) {Text("Value").font(.caption2).foregroundStyle(.secondary)- if self.editingReasoningParamName == "reasoning_effort" {- Picker("", selection: self.$editingReasoningParamValue) {- Text("minimal").tag("minimal"); Text("low").tag("low"); Text("medium")- .tag("medium"); Text("high").tag("high")+ if editingReasoningParamName == "reasoning_effort" {+ Picker("", selection: $editingReasoningParamValue) {+ Text("none").tag("none"); Text("minimal").tag("minimal"); Text("low").tag("low"); Text("medium").tag("medium"); Text("high").tag("high")}.pickerStyle(.menu).labelsHidden().frame(width: 100)- } else {- Picker("", selection: self.$editingReasoningParamValue) {+ } else if editingReasoningParamName == "enable_thinking" {+ Picker("", selection: $editingReasoningParamValue) {Text("true").tag("true"); Text("false").tag("false")}.pickerStyle(.menu).labelsHidden().frame(width: 100)+ } else {+ // Free-form value for custom parameters+ TextField("value", text: $editingReasoningParamValue)+ .textFieldStyle(.roundedBorder)+ .frame(width: 100)}}}diff --git a/Sources/Fluid/UI/FeedbackView.swift b/Sources/Fluid/UI/FeedbackView.swiftindex 27c56ca9..25be4a0e 100644--- a/Sources/Fluid/UI/FeedbackView.swift+++ b/Sources/Fluid/UI/FeedbackView.swift@@ -82,9 +82,9 @@ struct FeedbackView: View {}Spacer()-- if let url = URL(string: "https://github.com/altic-dev/Fluid-oss") {- Link(destination: url) {++ if let githubURL = URL(string: "https://github.com/altic-dev/Fluid-oss") {+ Link(destination: githubURL) {HStack(spacing: 8) {Image(systemName: "star.fill")Text("Star on GitHub")@@ -94,11 +94,13 @@ struct FeedbackView: View {.foregroundStyle(.white).padding(.horizontal, 16).padding(.vertical, 10)- .background(LinearGradient(- colors: [.purple, .blue],- startPoint: .leading,- endPoint: .trailing- ))+ .background(+ LinearGradient(+ colors: [.purple, .blue],+ startPoint: .leading,+ endPoint: .trailing+ )+ ).cornerRadius(8)}.buttonStyle(.plain)diff --git a/Sources/Fluid/Views/CommandModeView.swift b/Sources/Fluid/Views/CommandModeView.swiftindex 967a4761..2afe4583 100644--- a/Sources/Fluid/Views/CommandModeView.swift+++ b/Sources/Fluid/Views/CommandModeView.swift@@ -270,7 +270,9 @@ struct CommandModeView: View {}// MARK: - Chat Area-++ @State private var isThinkingExpanded = false+private var chatArea: some View {ScrollViewReader { proxy inScrollView {@@ -282,8 +284,14 @@ struct CommandModeView: View {if self.service.isProcessing {VStack(alignment: .leading, spacing: 8) {- self.processingIndicator-+ processingIndicator++ // Show thinking tokens in collapsible section (real-time)+ // Only show if setting is enabled AND there are thinking tokens+ if settings.showThinkingTokens && !service.streamingThinkingText.isEmpty {+ thinkingView+ }+// Show streaming text in real-timeif !self.service.streamingText.isEmpty {self.streamingTextView@@ -302,7 +310,8 @@ struct CommandModeView: View {.onChange(of: self.service.isProcessing) { _, isProcessing in// Scroll when processing starts, not on every streaming updateif isProcessing {- self.scrollToBottom(proxy)+ scrollToBottom(proxy)+ isThinkingExpanded = false // Collapse thinking for new request}}.onChange(of: self.service.currentStep) { _, _ in@@ -311,7 +320,56 @@ struct CommandModeView: View {// Removed: .onChange(of: service.streamingText) - causes scroll on every token, too expensive}}-++ // MARK: - Thinking View (Cursor-style shimmer)++ private var thinkingView: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header with shimmer effect - tap to expand/collapse+ Button(action: { withAnimation(.easeInOut(duration: 0.2)) { isThinkingExpanded.toggle() } }) {+ HStack(spacing: 8) {+ ThinkingShimmerLabel()++ Spacer()++ Image(systemName: isThinkingExpanded ? "chevron.up" : "chevron.down")+ .font(.caption2)+ .foregroundStyle(.secondary.opacity(0.6))+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ }+ .buttonStyle(.plain)++ // Expanded content+ if isThinkingExpanded {+ ScrollView(.vertical, showsIndicators: true) {+ Text(service.streamingThinkingText)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 12)+ .padding(.bottom, 10)+ }+ .frame(maxHeight: 200)+ } else {+ // Preview - first 150 chars+ if service.streamingThinkingText.count > 0 {+ Text(String(service.streamingThinkingText.prefix(150)) + (service.streamingThinkingText.count > 150 ? "..." : ""))+ .font(.system(size: 11))+ .foregroundStyle(.secondary.opacity(0.7))+ .lineLimit(2)+ .padding(.horizontal, 12)+ .padding(.bottom, 8)+ }+ }+ }+ .background(Color(nsColor: .controlBackgroundColor).opacity(0.5))+ .cornerRadius(8)+ .frame(maxWidth: 520, alignment: .leading)+ }+// MARK: - Processing Indicator (Minimal with Shimmer)private var processingIndicator: some View {@@ -607,11 +665,71 @@ struct CommandShimmerText: View {}}+// MARK: - Thinking Shimmer Label (Cursor-style sparkle)++struct ThinkingShimmerLabel: View {+ @State private var shimmerPhase: CGFloat = -0.5+ @State private var sparkleOpacity: [Double] = [0.3, 0.5, 0.7, 0.4, 0.6]++ var body: some View {+ HStack(spacing: 6) {+ // Sparkle dots with staggered animation+ HStack(spacing: 2) {+ ForEach(0..<3, id: \.self) { index in+ Circle()+ .fill(Color.primary.opacity(sparkleOpacity[index]))+ .frame(width: 4, height: 4)+ }+ }++ // Shimmering "Think" text+ Text("Think")+ .font(.system(size: 12, weight: .medium))+ .foregroundStyle(+ LinearGradient(+ stops: [+ .init(color: Color.primary.opacity(0.35), location: 0),+ .init(color: Color.primary.opacity(0.35), location: max(0, shimmerPhase - 0.15)),+ .init(color: Color.primary.opacity(0.85), location: shimmerPhase),+ .init(color: Color.primary.opacity(0.35), location: min(1, shimmerPhase + 0.15)),+ .init(color: Color.primary.opacity(0.35), location: 1)+ ],+ startPoint: .leading,+ endPoint: .trailing+ )+ )+ }+ .onAppear {+ // Shimmer animation - smooth left to right+ withAnimation(.linear(duration: 1.5).repeatForever(autoreverses: false)) {+ shimmerPhase = 1.5+ }++ // Sparkle animation - staggered twinkling+ animateSparkles()+ }+ }++ private func animateSparkles() {+ // Create twinkling effect with staggered delays+ for i in 0..<3 {+ let delay = Double(i) * 0.15+ DispatchQueue.main.asyncAfter(deadline: .now() + delay) {+ withAnimation(.easeInOut(duration: 0.4).repeatForever(autoreverses: true)) {+ sparkleOpacity[i] = sparkleOpacity[i] > 0.5 ? 0.2 : 0.8+ }+ }+ }+ }+}++// MARK: - Message Bubble (Minimal Design)struct MessageBubble: View {let message: CommandModeService.Message-+ @State private var isThinkingExpanded: Bool = false+var body: some View {HStack(alignment: .top) {if self.message.role == .user {@@ -640,6 +758,11 @@ struct MessageBubble: View {private var agentMessageView: some View {VStack(alignment: .leading, spacing: 6) {+ // Thinking section (collapsible) - only if setting is enabled+ if let thinking = message.thinking, !thinking.isEmpty, SettingsStore.shared.showThinkingTokens {+ thinkingSection(thinking)+ }+// Purpose label (minimal, gray)if let tc = message.toolCall, let purpose = tc.purpose {Text(purpose)@@ -658,7 +781,66 @@ struct MessageBubble: View {}.frame(maxWidth: 520, alignment: .leading)}-++ // MARK: - Thinking Section (Persisted, Collapsible)++ private func thinkingSection(_ thinking: String) -> some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header - tap to expand/collapse+ Button(action: { withAnimation(.easeInOut(duration: 0.2)) { isThinkingExpanded.toggle() } }) {+ HStack(spacing: 6) {+ HStack(spacing: 2) {+ ForEach(0..<3, id: \.self) { _ in+ Circle()+ .fill(Color.primary.opacity(0.4))+ .frame(width: 3, height: 3)+ }+ }+ Text("Think")+ .font(.system(size: 11, weight: .medium))+ .foregroundStyle(.secondary)++ Spacer()++ Text("\(thinking.count) chars")+ .font(.system(size: 9))+ .foregroundStyle(.tertiary)++ Image(systemName: isThinkingExpanded ? "chevron.up" : "chevron.down")+ .font(.system(size: 9))+ .foregroundStyle(.tertiary)+ }+ .padding(.horizontal, 10)+ .padding(.vertical, 6)+ }+ .buttonStyle(.plain)++ // Expanded content+ if isThinkingExpanded {+ ScrollView(.vertical, showsIndicators: true) {+ Text(thinking)+ .font(.system(size: 10))+ .foregroundStyle(.secondary)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 10)+ .padding(.bottom, 8)+ }+ .frame(maxHeight: 150)+ } else {+ // Preview - first 80 chars+ Text(String(thinking.prefix(80)) + (thinking.count > 80 ? "..." : ""))+ .font(.system(size: 10))+ .foregroundStyle(.tertiary)+ .lineLimit(1)+ .padding(.horizontal, 10)+ .padding(.bottom, 6)+ }+ }+ .background(Color(nsColor: .controlBackgroundColor).opacity(0.4))+ .cornerRadius(6)+ }+// MARK: - Command Call View (Minimal)private func commandCallView(_ tc: CommandModeService.Message.ToolCall) -> some View {diff --git a/Sources/Fluid/Views/RewriteModeView.swift b/Sources/Fluid/Views/RewriteModeView.swiftindex c34b20cc..f13e5551 100644--- a/Sources/Fluid/Views/RewriteModeView.swift+++ b/Sources/Fluid/Views/RewriteModeView.swift@@ -12,7 +12,8 @@ struct RewriteModeView: View {@State private var showOriginal: Bool = true@State private var showHowTo: Bool = false@State private var isHoveringHowTo: Bool = false-+ @State private var isThinkingExpanded: Bool = false+// Local state for available models (derived from shared AI Settings pool)@State private var availableModels: [String] = []@@ -225,6 +226,13 @@ struct RewriteModeView: View {}.padding().background(Color(nsColor: .windowBackgroundColor))++ // Thinking view (real-time, during processing)+ if service.isProcessing && settings.showThinkingTokens && !service.streamingThinkingText.isEmpty {+ thinkingView+ .padding(.horizontal)+ .padding(.bottom, 8)+ }}.onChange(of: self.asr.finalText) { _, newText inif !newText.isEmpty {@@ -422,4 +430,52 @@ struct RewriteModeView: View {.foregroundStyle(.primary.opacity(0.8))}}++ // MARK: - Thinking View (Cursor-style shimmer)++ private var thinkingView: some View {+ VStack(alignment: .leading, spacing: 0) {+ // Header with shimmer effect - tap to expand/collapse+ Button(action: { withAnimation(.easeInOut(duration: 0.2)) { isThinkingExpanded.toggle() } }) {+ HStack(spacing: 8) {+ ThinkingShimmerLabel()++ Spacer()++ Image(systemName: isThinkingExpanded ? "chevron.up" : "chevron.down")+ .font(.caption2)+ .foregroundStyle(.secondary.opacity(0.6))+ }+ .padding(.horizontal, 12)+ .padding(.vertical, 8)+ }+ .buttonStyle(.plain)++ // Expanded content+ if isThinkingExpanded {+ ScrollView(.vertical, showsIndicators: true) {+ Text(service.streamingThinkingText)+ .font(.system(size: 11))+ .foregroundStyle(.secondary)+ .textSelection(.enabled)+ .frame(maxWidth: .infinity, alignment: .leading)+ .padding(.horizontal, 12)+ .padding(.bottom, 10)+ }+ .frame(maxHeight: 150)+ } else {+ // Preview - first 100 chars+ if service.streamingThinkingText.count > 0 {+ Text(String(service.streamingThinkingText.prefix(100)) + (service.streamingThinkingText.count > 100 ? "..." : ""))+ .font(.system(size: 11))+ .foregroundStyle(.secondary.opacity(0.7))+ .lineLimit(2)+ .padding(.horizontal, 12)+ .padding(.bottom, 8)+ }+ }+ }+ .background(Color(nsColor: .controlBackgroundColor).opacity(0.5))+ .cornerRadius(8)+ }}