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
feat: upgrade to Parakeet TDT v3 with 25-language support
altic-devab8f1efd15f8
diff --git a/.gitignore b/.gitignoreindex 8edcaefd..4e71e1b1 100644--- a/.gitignore+++ b/.gitignore@@ -161,3 +161,6 @@ SettingsStore.xcuserstate**/tmp/**/temp/++**/.vscode/+diff --git a/Fluid.xcodeproj/project.pbxproj b/Fluid.xcodeproj/project.pbxprojindex b51f8285..05e3d32e 100644--- a/Fluid.xcodeproj/project.pbxproj+++ b/Fluid.xcodeproj/project.pbxproj@@ -15,9 +15,9 @@/* End PBXFileReference section *//* Begin PBXFileSystemSynchronizedRootGroup section */- 7C078D912E3B339200FB7CAC /* Fluid */ = {+ 7C078D912E3B339200FB7CAC /* Sources/Fluid */ = {isa = PBXFileSystemSynchronizedRootGroup;- path = "Sources/Fluid";+ path = Sources/Fluid;sourceTree = "<group>";};/* End PBXFileSystemSynchronizedRootGroup section */@@ -37,7 +37,7 @@7C078D862E3B339200FB7CAC = {isa = PBXGroup;children = (- 7C078D912E3B339200FB7CAC /* Fluid */,+ 7C078D912E3B339200FB7CAC /* Sources/Fluid */,7C078D902E3B339200FB7CAC /* Products */,);sourceTree = "<group>";@@ -66,7 +66,7 @@dependencies = ();fileSystemSynchronizedGroups = (- 7C078D912E3B339200FB7CAC /* Fluid */,+ 7C078D912E3B339200FB7CAC /* Sources/Fluid */,);name = fluid;packageProductDependencies = (@@ -291,7 +291,7 @@ENABLE_USER_SELECTED_FILES = readwrite;EXCLUDED_ARCHS = x86_64;GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = "Info.plist";+ INFOPLIST_FILE = Info.plist;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";INFOPLIST_KEY_NSHumanReadableCopyright = "";INFOPLIST_KEY_NSMicrophoneUsageDescription = "Transcribe speech from microphone";@@ -345,7 +345,7 @@ENABLE_USER_SELECTED_FILES = readwrite;EXCLUDED_ARCHS = x86_64;GENERATE_INFOPLIST_FILE = NO;- INFOPLIST_FILE = "Info.plist";+ INFOPLIST_FILE = Info.plist;INFOPLIST_KEY_LSApplicationCategoryType = "public.app-category.productivity";INFOPLIST_KEY_NSHumanReadableCopyright = "";INFOPLIST_KEY_NSMicrophoneUsageDescription = "Transcribe speech from microphone";diff --git a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolvedindex eef45a3e..5c582b76 100644--- a/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved+++ b/Fluid.xcodeproj/project.xcworkspace/xcshareddata/swiftpm/Package.resolved@@ -7,7 +7,7 @@"location" : "https://github.com/FluidInference/FluidAudio.git","state" : {"branch" : "main",- "revision" : "2de87c32c320e2f28839c3a9682bc7bd0ea45be7"+ "revision" : "038c9229ac457fd9653741360c56bc2fa0917705"}}],diff --git a/Info.plist b/Info.plistindex 80eeda4f..d9b0d9a2 100644--- a/Info.plist+++ b/Info.plist@@ -11,7 +11,7 @@<key>CFBundleVersion</key><string>1</string><key>CFBundleShortVersionString</key>- <string>1.0</string>+ <string>1.1</string><key>LSMinimumSystemVersion</key><string>$(MACOSX_DEPLOYMENT_TARGET)</string><key>LSApplicationCategoryType</key>diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swiftindex a53c26ff..4879fc63 100644--- a/Sources/Fluid/ContentView.swift+++ b/Sources/Fluid/ContentView.swift@@ -1410,6 +1410,20 @@ struct ContentView: View {.stroke(.white.opacity(0.1), lineWidth: 1)))++ // Helpful link: Supported languages+ HStack(alignment: .firstTextBaseline, spacing: 8) {+ Image(systemName: "link")+ .foregroundStyle(.secondary)+ Link(+ "Supported languages",+ destination: URL(string: "https://huggingface.co/nvidia/parakeet-tdt-0.6b-v3")!+ )+ }+ .font(.caption)+ .foregroundStyle(.secondary)++}}.padding(24)@@ -3725,4 +3739,3 @@ struct CardAppearAnimation: ViewModifier {.animation(.spring(response: 0.8, dampingFraction: 0.75, blendDuration: 0.2).delay(delay), value: appear)}}-diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swiftindex e0fffbf7..109690fd 100644--- a/Sources/Fluid/Networking/ModelDownloader.swift+++ b/Sources/Fluid/Networking/ModelDownloader.swift@@ -31,8 +31,8 @@ final class HuggingFaceModelDownloader/// Initialize with default model repository settingsinit(){- self.owner = "BarathwajAnandan"- self.repo = "parakeet-tdt-0.6b-v2-coreml-optim"+ self.owner = "FluidInference"+ self.repo = "parakeet-tdt-0.6b-v3-coreml"self.revision = "main"self.baseApiURL = URL(string: "https://huggingface.co/api/models/")!.appendingPathComponent(owner)@@ -161,14 +161,11 @@ final class HuggingFaceModelDownloaderprivate func requiredItems() -> [ModelItem]{return [- // Loader expects this exact name (typo preserved in upstream API)- ModelItem(path: "Melspectogram.mlmodelc", isDirectory: true),- ModelItem(path: "ParakeetEncoder_v2.mlmodelc", isDirectory: true),- ModelItem(path: "ParakeetDecoder.mlmodelc", isDirectory: true),- ModelItem(path: "RNNTJoint.mlmodelc", isDirectory: true),- ModelItem(path: "TokenDurationPrediction.mlmodelc", isDirectory: true),- ModelItem(path: "parakeet_vocab.json", isDirectory: false),- ModelItem(path: "config.json", isDirectory: false)+ // Preferred v3 unified model file names used by FluidAudio 0.5++ ModelItem(path: "MelEncoder.mlmodelc", isDirectory: true),+ ModelItem(path: "Decoder.mlmodelc", isDirectory: true),+ ModelItem(path: "JointDecision.mlmodelc", isDirectory: true),+ ModelItem(path: "parakeet_v3_vocab.json", isDirectory: false)]}@@ -301,32 +298,52 @@ final class HuggingFaceModelDownloaderextension HuggingFaceModelDownloader{- /// Load ASR models directly from disk without invoking FluidAudio's DownloadUtils+ /// Load ASR models directly from disk using unified v3 model namesfunc loadLocalAsrModels(from repoDirectory: URL) async throws -> AsrModels{let config = AsrModels.defaultConfiguration()- let melUrl = repoDirectory.appendingPathComponent("Melspectogram.mlmodelc")- let encUrl = repoDirectory.appendingPathComponent("ParakeetEncoder_v2.mlmodelc")- let decUrl = repoDirectory.appendingPathComponent("ParakeetDecoder.mlmodelc")- let jointUrl = repoDirectory.appendingPathComponent("RNNTJoint.mlmodelc")- let tokenUrl = repoDirectory.appendingPathComponent("TokenDurationPrediction.mlmodelc")-- let mel = try MLModel(contentsOf: melUrl, configuration: config)- let enc = try MLModel(contentsOf: encUrl, configuration: config)- let dec = try MLModel(contentsOf: decUrl, configuration: config)+ // Unified v3 model paths+ let melEncUrl = repoDirectory.appendingPathComponent("MelEncoder.mlmodelc")+ let decUrl = repoDirectory.appendingPathComponent("Decoder.mlmodelc")+ let jointUrl = repoDirectory.appendingPathComponent("JointDecision.mlmodelc")++ print("[ModelDL] Loading v3 models from: \(repoDirectory.path)")+ print("[ModelDL] MelEncoder path: \(melEncUrl.path)")+ print("[ModelDL] Decoder path: \(decUrl.path)")+ print("[ModelDL] JointDecision path: \(jointUrl.path)")++ // Check existence+ let fm = FileManager.default+ print("[ModelDL] MelEncoder exists: \(fm.fileExists(atPath: melEncUrl.path))")+ print("[ModelDL] Decoder exists: \(fm.fileExists(atPath: decUrl.path))")+ print("[ModelDL] JointDecision exists: \(fm.fileExists(atPath: jointUrl.path))")++ // Load models with configuration+ let melEncoder = try MLModel(contentsOf: melEncUrl, configuration: config)+ let decoder = try MLModel(contentsOf: decUrl, configuration: config)let joint = try MLModel(contentsOf: jointUrl, configuration: config)- let token = try MLModel(contentsOf: tokenUrl, configuration: config)+ // Load vocabulary (JSON: {"0": "<pad>", ...}) from repo root+ let vocabPath = repoDirectory.deletingLastPathComponent().appendingPathComponent("parakeet-tdt-0.6b-v3-coreml").appendingPathComponent("parakeet_v3_vocab.json")+ guard fm.fileExists(atPath: vocabPath.path) else {+ throw NSError(domain: "ModelDL", code: -2, userInfo: [NSLocalizedDescriptionKey: "Vocabulary file not found at \(vocabPath.path)"])+ }+ let vocabData = try Data(contentsOf: vocabPath)+ let raw = try JSONSerialization.jsonObject(with: vocabData) as? [String: String] ?? [:]+ var vocabulary: [Int: String] = [:]+ vocabulary.reserveCapacity(raw.count)+ for (k, v) in raw {+ if let idx = Int(k) { vocabulary[idx] = v }+ }++ print("[ModelDL] Creating AsrModels (unified v3)")return AsrModels(- melspectrogram: mel,- encoder: enc,- decoder: dec,+ melEncoder: melEncoder,+ decoder: decoder,joint: joint,- tokenDuration: token,- configuration: config+ configuration: config,+ vocabulary: vocabulary)}}--diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swiftindex fd5fb0e1..3168d820 100644--- a/Sources/Fluid/Services/ASRService.swift+++ b/Sources/Fluid/Services/ASRService.swift@@ -26,6 +26,22 @@ import AppKit/// let transcribedText = await asrService.stop() // Stop and get transcription/// ```///+/// ## Language Support+/// The service supports 25 European languages with Parakeet TDT v3:+/// - Auto-detect (recommended): Automatically detects the language+/// - Specific languages: Bulgarian, Croatian, Czech, Danish, Dutch, English, Estonian,+/// Finnish, French, German, Greek, Hungarian, Italian, Latvian, Lithuanian, Maltese,+/// Polish, Portuguese, Romanian, Slovak, Slovenian, Spanish, Swedish, Russian, Ukrainian+///+/// ## Language Configuration+/// ```swift+/// // Set a specific language+/// try await asrService.setLanguage(.fr) // French+///+/// // Use auto-detection (default)+/// try await asrService.setLanguage(.auto)+/// ```+///Tak, jasne. Cześć, co słychać?/// ## Thread Safety/// All public methods are marked with @MainActor to ensure thread safety./// Audio processing happens on background threads for optimal performance.@@ -42,11 +58,46 @@ final class ASRService: ObservableObject@Published var isAsrReady: Bool = false@Published var isDownloadingModel: Bool = false@Published var modelDownloadProgress: Double = 0.0- @Published var selectedModel: ModelOption = .parakeetTdt06bV2+ @Published var selectedModel: ModelOption = .parakeetTdt06bV3+ @Published var selectedLanguage: LanguageOption = .auto+ @Published var availableLanguages: [LanguageOption] = []enum ModelOption: String, CaseIterable, Identifiable, Hashable{- case parakeetTdt06bV2 = "Parakeet TDT-0.6b v2"+ case parakeetTdt06bV3 = "Parakeet TDT-0.6b v3"+ var id: String { rawValue }+ var displayName: String { rawValue }+ }++ enum LanguageOption: String, CaseIterable, Identifiable, Hashable+ {+ case auto = "Auto-detect"+ case bg = "Bulgarian"+ case hr = "Croatian"+ case cs = "Czech"+ case da = "Danish"+ case nl = "Dutch"+ case en = "English"+ case et = "Estonian"+ case fi = "Finnish"+ case fr = "French"+ case de = "German"+ case el = "Greek"+ case hu = "Hungarian"+ case it = "Italian"+ case lv = "Latvian"+ case lt = "Lithuanian"+ case mt = "Maltese"+ case pl = "Polish"+ case pt = "Portuguese"+ case ro = "Romanian"+ case sk = "Slovak"+ case sl = "Slovenian"+ case es = "Spanish"+ case sv = "Swedish"+ case ru = "Russian"+ case uk = "Ukrainian"+var id: String { rawValue }var displayName: String { rawValue }}@@ -70,12 +121,18 @@ final class ASRService: ObservableObjectprivate let historySize = 2 // Reduced for faster responseprivate let silenceThreshold: CGFloat = 0.04 // Reasonable defaultprivate let noiseGateThreshold: CGFloat = 0.06-init(){self.micStatus = AVCaptureDevice.authorizationStatus(for: .audio)self.micPermissionGranted = (self.micStatus == .authorized)registerDefaultDeviceChangeListener()+ populateAvailableLanguages()+ }++ private func populateAvailableLanguages()+ {+ // All 25 European languages supported by Parakeet TDT v3+ availableLanguages = LanguageOption.allCases}func requestMicAccess()@@ -183,18 +240,32 @@ final class ASRService: ObservableObjectdo{try await self.ensureAsrReady()- guard let manager = self.asrManager else { return "" }+ guard let manager = self.asrManager else {+ DebugLogger.shared.error("ASR manager is nil", source: "ASRService")+ return ""+ }++ DebugLogger.shared.debug("Starting transcription with \(pcm.count) samples (\(Float(pcm.count)/16000.0) seconds)", source: "ASRService")let result = try await manager.transcribe(pcm, source: AudioSource.microphone)+ DebugLogger.shared.debug("Transcription completed: '\(result.text)' (confidence: \(result.confidence))", source: "ASRService")// Do not update self.finalText here to avoid instant binding insert in playgroundreturn result.text}catch{DebugLogger.shared.error("ASR transcription failed: \(error)", source: "ASRService")+ DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")+ let nsError = error as NSError+ DebugLogger.shared.error("Error domain: \(nsError.domain), code: \(nsError.code)", source: "ASRService")+ DebugLogger.shared.error("Error userInfo: \(nsError.userInfo)", source: "ASRService")return ""}}++++func stopWithoutTranscription(){guard isRunning else { return }@@ -442,15 +513,20 @@ final class ASRService: ObservableObject/// Manual calls are typically not needed unless you want to preload models.func ensureAsrReady() async throws{+ // Force reinitialization for v3 models by resetting state+ isAsrReady = false+ asrManager = nil+if isAsrReady == false{do{DebugLogger.shared.debug("Starting ASR initialization...", source: "ASRService")- // Check model cache directory- let cacheDir = AsrModels.defaultCacheDirectory()- DebugLogger.shared.debug("Model cache directory: \(cacheDir.path)", source: "ASRService")+ // Use separate cache directory for v3 models+ let 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 originalStderr = dup(STDERR_FILENO)@@ -458,23 +534,30 @@ final class ASRService: ObservableObjectdup2(devNull, STDERR_FILENO)close(devNull)- DebugLogger.shared.debug("Ensuring models exist via in-app downloader...", source: "ASRService")- let downloader = HuggingFaceModelDownloader()- try await downloader.ensureModelsPresent(at: cacheDir) { progress, item in- DispatchQueue.main.async {- self.isDownloadingModel = progress < 1.0- self.modelDownloadProgress = max(0.0, min(1.0, progress))- }- DebugLogger.shared.debug(String(format: "Download progress: %.0f%% (%@)", progress * 100.0, item), source: "ASRService")+ DebugLogger.shared.debug("Using FluidAudio's v3 loader (AsrModels.downloadAndLoad)", source: "ASRService")++ // Force v3: remove any v2 cache directory so no fallback occurs+ let 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("Models ensured in cache. Now loading from disk (local loader, no network)...", source: "ASRService")- let models = try await downloader.loadLocalAsrModels(from: cacheDir)- DebugLogger.shared.debug("Models loaded successfully from cache directory (local)", source: "ASRService")++ DispatchQueue.main.async {+ self.isDownloadingModel = true+ self.modelDownloadProgress = 0.0+ }+ let models = try await AsrModels.downloadAndLoad()+ DispatchQueue.main.async {+ self.isDownloadingModel = false+ self.modelDownloadProgress = 1.0+ }+ DebugLogger.shared.debug("FluidAudio models loaded successfully (v3)", source: "ASRService")if self.asrManager == nil{DebugLogger.shared.debug("Creating new AsrManager...", source: "ASRService")- self.asrManager = AsrManager(config: ASRConfig(realtimeMode: false))+ self.asrManager = AsrManager(config: ASRConfig.default)}if let manager = self.asrManager{@@ -537,9 +620,51 @@ final class ASRService: ObservableObjectawait MainActor.run { self.isDownloadingModel = false }}+ // MARK: - Language configuration+ func setLanguage(_ language: LanguageOption) async throws+ {+ selectedLanguage = language+ DebugLogger.shared.debug("Setting ASR language to: \(language.displayName)", source: "ASRService")++ // Force reinitialization with new language setting+ isAsrReady = false+ asrManager = nil++ // Reinitialize with new language configuration+ try await ensureAsrReady()+ }++ // MARK: - Cache management+ func clearModelCache() async throws+ {+ DebugLogger.shared.debug("Clearing all model caches to force fresh download", source: "ASRService")++ // Clear v2 cache+ let baseCacheDir = AsrModels.defaultCacheDirectory().deletingLastPathComponent()+ let 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", source: "ASRService")+ }++ // Clear v3 cache+ let v3CacheDir = baseCacheDir.appendingPathComponent("parakeet-tdt-0.6b-v3-coreml")+ if FileManager.default.fileExists(atPath: v3CacheDir.path) {+ try FileManager.default.removeItem(at: v3CacheDir)+ DebugLogger.shared.debug("Removed v3 cache directory", source: "ASRService")+ }++ // Force reinitialization+ isAsrReady = false+ asrManager = nil++ // Reinitialize to download fresh models+ try await ensureAsrReady()+ }+// MARK: - Typing convenience for compatibilityprivate let typingService = TypingService() // Reuse instance to avoid conflicts-+func typeTextToActiveField(_ text: String){DebugLogger.shared.debug("typeTextToActiveField called with: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"", source: "ASRService")@@ -548,5 +673,3 @@ final class ASRService: ObservableObjectDebugLogger.shared.debug("typingService.typeTextInstantly call completed", source: "ASRService")}}--diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swiftindex a67fdd48..052d5455 100644--- a/Sources/Fluid/Services/TypingService.swift+++ b/Sources/Fluid/Services/TypingService.swift@@ -3,139 +3,149 @@ import AppKitfinal class TypingService{+ // Logging toggle (off by default). Enable by setting env FLUID_TYPING_LOGS=1+ // or UserDefaults bool for key "enableTypingLogs".+ private static var isLoggingEnabled: Bool {+ if let env = ProcessInfo.processInfo.environment["FLUID_TYPING_LOGS"], env == "1" { return true }+ return UserDefaults.standard.bool(forKey: "enableTypingLogs")+ }+ private func log(_ message: @autoclosure () -> String) {+ if Self.isLoggingEnabled { print(message()) }+ }+private var isCurrentlyTyping = falsefunc typeTextInstantly(_ text: String){- print("[TypingService] ENTRY: typeTextInstantly called with text length: \(text.count)")- print("[TypingService] Text preview: \"\(String(text.prefix(100)))\"")+ log("[TypingService] ENTRY: typeTextInstantly called with text length: \(text.count)")+ log("[TypingService] Text preview: \"\(String(text.prefix(100)))\"")guard text.isEmpty == false else {- print("[TypingService] ERROR: Empty text provided, aborting")+ log("[TypingService] ERROR: Empty text provided, aborting")return}// Prevent concurrent typing operationsguard !isCurrentlyTyping else {- print("[TypingService] WARNING: Skipping text injection - already in progress")+ log("[TypingService] WARNING: Skipping text injection - already in progress")return}// Check accessibility permissions firstguard AXIsProcessTrusted() else {- print("[TypingService] ERROR: Accessibility permissions required for text injection")- print("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")+ log("[TypingService] ERROR: Accessibility permissions required for text injection")+ log("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")return}- print("[TypingService] Accessibility check passed, proceeding with text injection")+ log("[TypingService] Accessibility check passed, proceeding with text injection")isCurrentlyTyping = trueDispatchQueue.global(qos: .userInitiated).async{defer {self.isCurrentlyTyping = false- print("[TypingService] Typing operation completed, isCurrentlyTyping set to false")+ self.log("[TypingService] Typing operation completed, isCurrentlyTyping set to false")}- print("[TypingService] Starting async text insertion process")+ self.log("[TypingService] Starting async text insertion process")// Longer delay to ensure target app is ready and focusedusleep(200000) // 200ms delay - more reliable for app switching- print("[TypingService] Delay completed, calling insertTextInstantly")+ self.log("[TypingService] Delay completed, calling insertTextInstantly")self.insertTextInstantly(text)}}private func insertTextInstantly(_ text: String){- print("[TypingService] insertTextInstantly called with \(text.count) characters")- print("[TypingService] Attempting to type text: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"")+ log("[TypingService] insertTextInstantly called with \(text.count) characters")+ log("[TypingService] Attempting to type text: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"")// Get frontmost app infoif let frontApp = NSWorkspace.shared.frontmostApplication {- print("[TypingService] Target app: \(frontApp.localizedName ?? "Unknown") (\(frontApp.bundleIdentifier ?? "Unknown"))")+ log("[TypingService] Target app: \(frontApp.localizedName ?? "Unknown") (\(frontApp.bundleIdentifier ?? "Unknown"))")} else {- print("[TypingService] WARNING: Could not get frontmost application")+ log("[TypingService] WARNING: Could not get frontmost application")}// Check if we have permission to create events- print("[TypingService] Accessibility trusted: \(AXIsProcessTrusted())")+ log("[TypingService] Accessibility trusted: \(AXIsProcessTrusted())")// Try direct bulk CGEvent insertion (NO CLIPBOARD)- print("[TypingService] Trying INSTANT bulk CGEvent insertion (no clipboard)")+ log("[TypingService] Trying INSTANT bulk CGEvent insertion (no clipboard)")if insertTextBulkInstant(text) {- print("[TypingService] SUCCESS: Instant bulk CGEvent completed")+ log("[TypingService] SUCCESS: Instant bulk CGEvent completed")} else {- print("[TypingService] FAILED: Bulk CGEvent, trying character-by-character")+ log("[TypingService] FAILED: Bulk CGEvent, trying character-by-character")// Fallback to character-by-character if bulk failsfor (index, char) in text.enumerated() {if index % 10 == 0 { // Log every 10th character to avoid spam- print("[TypingService] Typing character \(index+1)/\(text.count): '\(char)'")+ log("[TypingService] Typing character \(index+1)/\(text.count): '\(char)'")}typeCharacter(char)usleep(1000) // Small delay between characters (1ms)}- print("[TypingService] Character-by-character typing completed")+ log("[TypingService] Character-by-character typing completed")}}private func insertTextBulkInstant(_ text: String) -> Bool {- print("[TypingService] Starting INSTANT bulk CGEvent insertion (NO CLIPBOARD)")+ log("[TypingService] Starting INSTANT bulk CGEvent insertion (NO CLIPBOARD)")// Create single CGEvent with entire text - truly instantguard let event = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true) else {- print("[TypingService] ERROR: Failed to create bulk CGEvent")+ log("[TypingService] ERROR: Failed to create bulk CGEvent")return false}// Convert entire text to UTF16let utf16Array = Array(text.utf16)- print("[TypingService] Converting \(text.count) characters to single CGEvent")+ log("[TypingService] Converting \(text.count) characters to single CGEvent")// Set the entire text as unicode stringevent.keyboardSetUnicodeString(stringLength: utf16Array.count, unicodeString: utf16Array)// Post single event - INSTANT insertionevent.post(tap: .cghidEventTap)- print("[TypingService] Posted single CGEvent with entire text - INSTANT!")+ log("[TypingService] Posted single CGEvent with entire text - INSTANT!")return true}private func insertTextViaAccessibility(_ text: String) -> Bool {- print("[TypingService] Starting Accessibility API insertion")+ log("[TypingService] Starting Accessibility API insertion")// Try multiple strategies to find text input element// Strategy 1: Get focused element directly- print("[TypingService] Strategy 1: Getting focused UI element...")+ log("[TypingService] Strategy 1: Getting focused UI element...")if let textElement = getFocusedTextElement() {- print("[TypingService] Found focused text element")+ log("[TypingService] Found focused text element")if tryAllTextInsertionMethods(textElement, text) {return true}}// Strategy 2: Traverse frontmost app UI hierarchy to find text elements- print("[TypingService] Strategy 2: Traversing app UI hierarchy...")+ log("[TypingService] Strategy 2: Traversing app UI hierarchy...")if let textElement = findTextElementInFrontmostApp() {- print("[TypingService] Found text element in app hierarchy")+ log("[TypingService] Found text element in app hierarchy")if tryAllTextInsertionMethods(textElement, text) {return true}}// Strategy 3: Find element with keyboard focus- print("[TypingService] Strategy 3: Looking for keyboard focus...")+ log("[TypingService] Strategy 3: Looking for keyboard focus...")if let textElement = findKeyboardFocusedElement() {- print("[TypingService] Found keyboard focused element")+ log("[TypingService] Found keyboard focused element")if tryAllTextInsertionMethods(textElement, text) {return true}}- print("[TypingService] All Accessibility API strategies failed")+ log("[TypingService] All Accessibility API strategies failed")return false}@@ -148,11 +158,11 @@ final class TypingServiceif result == .success, let element = focusedElement {let axElement = element as! AXUIElementif let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {- print("[TypingService] Found focused element with role: \(role)")+ log("[TypingService] Found focused element with role: \(role)")return axElement}} else {- print("[TypingService] Could not get focused UI element - result: \(result.rawValue)")+ log("[TypingService] Could not get focused UI element - result: \(result.rawValue)")}return nil@@ -160,7 +170,7 @@ final class TypingServiceprivate func findTextElementInFrontmostApp() -> AXUIElement? {guard let frontmostApp = NSWorkspace.shared.frontmostApplication else {- print("[TypingService] Could not get frontmost app")+ log("[TypingService] Could not get frontmost app")return nil}@@ -175,7 +185,7 @@ final class TypingServiceif let role = getElementAttribute(element, kAXRoleAttribute as CFString) {let textRoles = ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField", "AXStaticText"]if textRoles.contains(role) {- print("[TypingService] Found text element at depth \(depth) with role: \(role)")+ log("[TypingService] Found text element at depth \(depth) with role: \(role)")return element}}@@ -206,7 +216,7 @@ final class TypingServiceif result == .success, let element = focusedElement {let axElement = element as! AXUIElementif let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {- print("[TypingService] Found app-level focused element with role: \(role)")+ log("[TypingService] Found app-level focused element with role: \(role)")return axElement}}@@ -217,25 +227,25 @@ final class TypingServiceprivate func tryAllTextInsertionMethods(_ element: AXUIElement, _ text: String) -> Bool {// Get element info for debuggingif let role = getElementAttribute(element, kAXRoleAttribute as CFString) {- print("[TypingService] Trying insertion on element with role: \(role)")+ log("[TypingService] Trying insertion on element with role: \(role)")if let title = getElementAttribute(element, kAXTitleAttribute as CFString) {- print("[TypingService] Element title: \(title)")+ log("[TypingService] Element title: \(title)")}}// Try multiple approaches for text insertion- print("[TypingService] Trying approach 1: Direct kAXValueAttribute")+ log("[TypingService] Trying approach 1: Direct kAXValueAttribute")if setTextViaValue(element, text) {return true}- print("[TypingService] Trying approach 2: kAXSelectedTextAttribute (replace selection)")+ log("[TypingService] Trying approach 2: kAXSelectedTextAttribute (replace selection)")if setTextViaSelection(element, text) {return true}- print("[TypingService] Trying approach 3: Insert text at insertion point")+ log("[TypingService] Trying approach 3: Insert text at insertion point")if insertTextAtInsertionPoint(element, text) {return true}@@ -257,10 +267,10 @@ final class TypingServicelet result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, cfText)if result == .success {- print("[TypingService] SUCCESS: Set text via kAXValueAttribute")+ log("[TypingService] SUCCESS: Set text via kAXValueAttribute")return true} else {- print("[TypingService] FAILED: kAXValueAttribute - error: \(result.rawValue)")+ log("[TypingService] FAILED: kAXValueAttribute - error: \(result.rawValue)")return false}}@@ -268,17 +278,17 @@ final class TypingServiceprivate func setTextViaSelection(_ element: AXUIElement, _ text: String) -> Bool {// First, select all existing textlet selectAllResult = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, "" as CFString)- print("[TypingService] Select all result: \(selectAllResult.rawValue)")+ log("[TypingService] Select all result: \(selectAllResult.rawValue)")// Then replace the selection with our textlet cfText = text as CFStringlet result = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, cfText)if result == .success {- print("[TypingService] SUCCESS: Set text via kAXSelectedTextAttribute")+ log("[TypingService] SUCCESS: Set text via kAXSelectedTextAttribute")return true} else {- print("[TypingService] FAILED: kAXSelectedTextAttribute - error: \(result.rawValue)")+ log("[TypingService] FAILED: kAXSelectedTextAttribute - error: \(result.rawValue)")return false}}@@ -287,51 +297,51 @@ final class TypingService// Try to get the insertion pointvar insertionPoint: CFTypeRef?let getResult = AXUIElementCopyAttributeValue(element, kAXInsertionPointLineNumberAttribute as CFString, &insertionPoint)- print("[TypingService] Get insertion point result: \(getResult.rawValue)")+ log("[TypingService] Get insertion point result: \(getResult.rawValue)")// Try to insert text using parameterized attributelet cfText = text as CFStringlet result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, cfText)if result == .success {- print("[TypingService] SUCCESS: Inserted text at insertion point")+ log("[TypingService] SUCCESS: Inserted text at insertion point")return true} else {- print("[TypingService] FAILED: Insertion point method - error: \(result.rawValue)")+ log("[TypingService] FAILED: Insertion point method - error: \(result.rawValue)")return false}}private func insertTextBulk(_ text: String) -> Bool {- print("[TypingService] Starting bulk CGEvent insertion")+ log("[TypingService] Starting bulk CGEvent insertion")// Get the frontmost application's PID for targeted event postingguard let frontApp = NSWorkspace.shared.frontmostApplication else {- print("[TypingService] ERROR: Could not get frontmost application for bulk insertion")+ log("[TypingService] ERROR: Could not get frontmost application for bulk insertion")return false}let targetPID = frontApp.processIdentifier- print("[TypingService] Targeting PID \(targetPID) for bulk insertion")+ log("[TypingService] Targeting PID \(targetPID) for bulk insertion")// Try word-by-word insertion instead of entire text at once (faster than char-by-char but more reliable than bulk)let words = text.components(separatedBy: " ")- print("[TypingService] Splitting text into \(words.count) words for bulk insertion")+ log("[TypingService] Splitting text into \(words.count) words for bulk insertion")for (index, word) in words.enumerated() {let wordToType = word + (index < words.count - 1 ? " " : "") // Add space except for last wordif !insertWordViaCGEvent(wordToType, targetPID: targetPID) {- print("[TypingService] Failed to insert word \(index + 1): '\(word)', falling back to character method")+ log("[TypingService] Failed to insert word \(index + 1): '\(word)', falling back to character method")return false}if index % 5 == 0 && index > 0 {- print("[TypingService] Bulk insertion progress: \(index + 1)/\(words.count) words")+ log("[TypingService] Bulk insertion progress: \(index + 1)/\(words.count) words")}}- print("[TypingService] Successfully completed bulk word-by-word insertion")+ log("[TypingService] Successfully completed bulk word-by-word insertion")return true}@@ -342,7 +352,7 @@ final class TypingService// Create keyboard event for this wordguard let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false) else {- print("[TypingService] ERROR: Failed to create CGEvents for word: '\(word)'")+ log("[TypingService] ERROR: Failed to create CGEvents for word: '\(word)'")return false}@@ -365,9 +375,7 @@ final class TypingService// Create keyboard events for this characterguard let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false) else {- if UserDefaults.standard.bool(forKey: "enableDebugLogs") {- print("[TypingService] ERROR: Failed to create CGEvents for character: \(char)")- }+ log("[TypingService] ERROR: Failed to create CGEvents for character: \(char)")return}@@ -381,5 +389,3 @@ final class TypingServicekeyUpEvent.post(tap: .cghidEventTap)}}--