Skip to content

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

SwiftFormat: preserve explicit self qualifiers

grohith32731e1e3e4195e
diff --git a/.swiftformat b/.swiftformat
index 54434bd0..09e80eeb 100644
--- a/.swiftformat
+++ b/.swiftformat
@@ -19,7 +19,7 @@
--operatorfunc spaced
--patternlet hoist
--ranges nospace
---self remove
+--self insert
--semicolons inline
--stripunusedargs closure-only
--trimwhitespace always
diff --git a/Package.swift b/Package.swift
index 4148039b..747cceea 100644
--- a/Package.swift
+++ b/Package.swift
@@ -6,14 +6,14 @@ import PackageDescription
let package = Package(
name: "FluidVoice",
platforms: [
- .macOS(.v14)
+ .macOS(.v14),
],
dependencies: [
.package(url: "https://github.com/mxcl/AppUpdater.git", from: "1.0.0"),
.package(url: "https://github.com/FluidInference/FluidAudio", from: "0.7.4"),
.package(url: "https://github.com/mxcl/PromiseKit", from: "6.0.0"),
.package(url: "https://github.com/MrKai77/DynamicNotchKit", from: "1.0.0"),
- .package(url: "https://github.com/exPHAT/SwiftWhisper.git", branch: "master")
+ .package(url: "https://github.com/exPHAT/SwiftWhisper.git", branch: "master"),
],
targets: [
.executableTarget(
@@ -23,8 +23,8 @@ let package = Package(
"FluidAudio",
"PromiseKit",
"DynamicNotchKit",
- "SwiftWhisper"
+ "SwiftWhisper",
]
- )
+ ),
]
)
diff --git a/Sources/Fluid/AppDelegate.swift b/Sources/Fluid/AppDelegate.swift
index db76d95c..3f5a088d 100644
--- a/Sources/Fluid/AppDelegate.swift
+++ b/Sources/Fluid/AppDelegate.swift
@@ -9,16 +9,16 @@ class AppDelegate: NSObject, NSApplicationDelegate {
func applicationDidFinishLaunching(_ notification: Notification) {
// Initialize AppUpdater for automatic updates
// Repository: https://github.com/altic-dev/Fluid-oss
- updater = AppUpdater(owner: "altic-dev", repo: "Fluid-oss")
+ self.updater = AppUpdater(owner: "altic-dev", repo: "Fluid-oss")
// Request accessibility permissions for global hotkey monitoring
- requestAccessibilityPermissions()
+ self.requestAccessibilityPermissions()
// Initialize app settings (dock visibility, etc.)
SettingsStore.shared.initializeAppSettings()
// Check for updates automatically if enabled
- checkForUpdatesAutomatically()
+ self.checkForUpdatesAutomatically()
// Note: App UI is designed with dark color scheme in mind
// All gradients and effects are optimized for dark mode
@@ -136,7 +136,7 @@ class AppDelegate: NSObject, NSApplicationDelegate {
if response == .alertFirstButtonReturn {
DebugLogger.shared.info("User chose to install update now", source: "AppDelegate")
- checkForUpdatesManually()
+ self.checkForUpdatesManually()
} else {
DebugLogger.shared.info("User postponed update", source: "AppDelegate")
}
diff --git a/Sources/Fluid/ContentView.swift b/Sources/Fluid/ContentView.swift
index 9056df7c..7c6c7037 100644
--- a/Sources/Fluid/ContentView.swift
+++ b/Sources/Fluid/ContentView.swift
@@ -135,9 +135,9 @@ struct ContentView: View {
self.detailView
})
- let tracked = splitView.withMouseTracking(mouseTracker)
- let env = tracked.environmentObject(mouseTracker)
- let nav = env.onChange(of: menuBarManager.requestedNavigationDestination) { _, destination in
+ let tracked = splitView.withMouseTracking(self.mouseTracker)
+ let env = tracked.environmentObject(self.mouseTracker)
+ let nav = env.onChange(of: self.menuBarManager.requestedNavigationDestination) { _, destination in
self.handleMenuBarNavigation(destination)
}
@@ -507,22 +507,22 @@ struct ContentView: View {
return event
}
}
- .onChange(of: accessibilityEnabled) { _, enabled in
+ .onChange(of: self.accessibilityEnabled) { _, enabled in
if enabled && self.hotkeyManager != nil && !self.hotkeyManagerInitialized {
DebugLogger.shared.debug("Accessibility enabled, reinitializing hotkey manager", source: "ContentView")
self.hotkeyManager?.reinitialize()
}
}
- .onChange(of: selectedModel) { _, newValue in
+ .onChange(of: self.selectedModel) { _, newValue in
if newValue != "__ADD_MODEL__" {
self.selectedModelByProvider[self.currentProvider] = newValue
SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
}
}
- .onChange(of: selectedProviderID) { _, newValue in
+ .onChange(of: self.selectedProviderID) { _, newValue in
SettingsStore.shared.selectedProviderID = newValue
}
- .onChange(of: isCommandModeShortcutEnabled) { newValue in
+ .onChange(of: self.isCommandModeShortcutEnabled) { newValue in
SettingsStore.shared.commandModeShortcutEnabled = newValue
self.hotkeyManager?.updateCommandModeShortcutEnabled(newValue)
@@ -538,7 +538,7 @@ struct ContentView: View {
}
}
}
- .onChange(of: isRewriteModeShortcutEnabled) { newValue in
+ .onChange(of: self.isRewriteModeShortcutEnabled) { newValue in
SettingsStore.shared.rewriteModeShortcutEnabled = newValue
self.hotkeyManager?.updateRewriteModeShortcutEnabled(newValue)
@@ -562,12 +562,12 @@ struct ContentView: View {
}
}
.overlay(alignment: .center) {}
- .alert(asr.errorTitle, isPresented: $asr.showError) {
+ .alert(self.asr.errorTitle, isPresented: self.$asr.showError) {
Button("OK", role: .cancel) {}
} message: {
Text(self.asr.errorMessage)
}
- .onChange(of: audioObserver.changeTick) { _, _ in
+ .onChange(of: self.audioObserver.changeTick) { _, _ in
// Hardware change detected → refresh device lists only
// NOTE: We do NOT force system defaults here anymore.
// FluidVoice should not hijack system-wide audio routing.
@@ -590,7 +590,7 @@ struct ContentView: View {
self.accessibilityPollingTask?.cancel()
self.accessibilityPollingTask = nil
}
- .onChange(of: hotkeyShortcut) { _, newValue in
+ .onChange(of: self.hotkeyShortcut) { _, newValue in
DebugLogger.shared.debug("Hotkey shortcut changed to \(newValue.displayString)", source: "ContentView")
self.hotkeyManager?.updateShortcut(newValue)
@@ -603,7 +603,7 @@ struct ContentView: View {
)
}
}
- .onChange(of: selectedSidebarItem) { _, newValue in
+ .onChange(of: self.selectedSidebarItem) { _, newValue in
self.handleModeTransition(from: self.previousSidebarItem, to: newValue)
self.previousSidebarItem = newValue
}
@@ -631,7 +631,7 @@ struct ContentView: View {
case .rewriteMode:
// Clear rewrite state when leaving
- rewriteModeService.clearState()
+ self.rewriteModeService.clearState()
default:
break
@@ -642,23 +642,23 @@ struct ContentView: View {
if let new = newValue {
switch new {
case .commandMode:
- menuBarManager.setOverlayMode(.command)
+ self.menuBarManager.setOverlayMode(.command)
case .rewriteMode:
// Check if in write mode (no original text) vs rewrite mode
- if rewriteModeService.isWriteMode || rewriteModeService.originalText.isEmpty {
- menuBarManager.setOverlayMode(.write)
+ if self.rewriteModeService.isWriteMode || self.rewriteModeService.originalText.isEmpty {
+ self.menuBarManager.setOverlayMode(.write)
} else {
- menuBarManager.setOverlayMode(.rewrite)
+ self.menuBarManager.setOverlayMode(.rewrite)
}
default:
// For all other views, set to dictation mode
- menuBarManager.setOverlayMode(.dictation)
+ self.menuBarManager.setOverlayMode(.dictation)
}
} else {
// If newValue is nil, default to dictation
- menuBarManager.setOverlayMode(.dictation)
+ self.menuBarManager.setOverlayMode(.dictation)
}
}
@@ -669,18 +669,18 @@ struct ContentView: View {
switch destination {
case .preferences:
- selectedSidebarItem = .preferences
+ self.selectedSidebarItem = .preferences
}
}
private func resetPendingShortcutState() {
- pendingModifierFlags = []
- pendingModifierKeyCode = nil
- pendingModifierOnly = false
+ self.pendingModifierFlags = []
+ self.pendingModifierKeyCode = nil
+ self.pendingModifierOnly = false
}
private var sidebarView: some View {
- List(selection: $selectedSidebarItem) {
+ List(selection: self.$selectedSidebarItem) {
NavigationLink(value: SidebarItem.welcome) {
Label("Welcome", systemImage: "house.fill")
.font(.system(size: 15, weight: .medium))
@@ -736,7 +736,7 @@ struct ContentView: View {
}
.ignoresSafeArea()
}
- .tint(theme.palette.accent)
+ .tint(self.theme.palette.accent)
}
private var detailView: some View {
@@ -755,23 +755,23 @@ struct ContentView: View {
}
private var detailContent: AnyView {
- switch selectedSidebarItem ?? .welcome {
+ switch self.selectedSidebarItem ?? .welcome {
case .welcome:
- return AnyView(welcomeView)
+ return AnyView(self.welcomeView)
case .aiSettings:
return AnyView(AISettingsView())
case .preferences:
- return AnyView(preferencesView)
+ return AnyView(self.preferencesView)
case .meetingTools:
- return AnyView(meetingToolsView)
+ return AnyView(self.meetingToolsView)
case .stats:
- return AnyView(statsView)
+ return AnyView(self.statsView)
case .feedback:
return AnyView(FeedbackView())
case .commandMode:
- return AnyView(commandModeView)
+ return AnyView(self.commandModeView)
case .rewriteMode:
- return AnyView(rewriteModeView)
+ return AnyView(self.rewriteModeView)
case .history:
return AnyView(TranscriptionHistoryView())
}
@@ -781,19 +781,19 @@ struct ContentView: View {
private var welcomeView: some View {
WelcomeView(
- selectedSidebarItem: $selectedSidebarItem,
- playgroundUsed: $playgroundUsed,
- isTranscriptionFocused: $isTranscriptionFocused,
- accessibilityEnabled: accessibilityEnabled,
- providerAPIKeys: providerAPIKeys,
- currentProvider: currentProvider,
- openAIBaseURL: openAIBaseURL,
- availableModels: availableModels,
- selectedModel: selectedModel,
+ selectedSidebarItem: self.$selectedSidebarItem,
+ playgroundUsed: self.$playgroundUsed,
+ isTranscriptionFocused: self.$isTranscriptionFocused,
+ accessibilityEnabled: self.accessibilityEnabled,
+ providerAPIKeys: self.providerAPIKeys,
+ currentProvider: self.currentProvider,
+ openAIBaseURL: self.openAIBaseURL,
+ availableModels: self.availableModels,
+ selectedModel: self.selectedModel,
stopAndProcessTranscription: { await self.stopAndProcessTranscription() },
- startRecording: startRecording,
- isLocalEndpoint: isLocalEndpoint,
- openAccessibilitySettings: openAccessibilitySettings
+ startRecording: self.startRecording,
+ isLocalEndpoint: self.isLocalEndpoint,
+ openAccessibilitySettings: self.openAccessibilitySettings
)
}
@@ -886,7 +886,7 @@ struct ContentView: View {
.padding(.leading, 4)
}
.padding(12)
- .background(theme.palette.accent.opacity(0.12))
+ .background(self.theme.palette.accent.opacity(0.12))
.cornerRadius(8)
}
@@ -907,52 +907,52 @@ struct ContentView: View {
private var preferencesView: some View {
SettingsView(
- appear: $appear,
- visualizerNoiseThreshold: $visualizerNoiseThreshold,
- selectedInputUID: $selectedInputUID,
- selectedOutputUID: $selectedOutputUID,
- inputDevices: $inputDevices,
- outputDevices: $outputDevices,
- accessibilityEnabled: $accessibilityEnabled,
- hotkeyShortcut: $hotkeyShortcut,
- isRecordingShortcut: $isRecordingShortcut,
- commandModeShortcut: $commandModeHotkeyShortcut,
- isRecordingCommandModeShortcut: $isRecordingCommandModeShortcut,
- rewriteShortcut: $rewriteModeHotkeyShortcut,
- isRecordingRewriteShortcut: $isRecordingRewriteShortcut,
- commandModeShortcutEnabled: $isCommandModeShortcutEnabled,
- rewriteShortcutEnabled: $isRewriteModeShortcutEnabled,
- hotkeyManagerInitialized: $hotkeyManagerInitialized,
- pressAndHoldModeEnabled: $pressAndHoldModeEnabled,
- enableStreamingPreview: $enableStreamingPreview,
- copyToClipboard: $copyToClipboard,
- hotkeyManager: hotkeyManager,
- menuBarManager: menuBarManager,
- startRecording: startRecording,
- refreshDevices: refreshDevices,
- openAccessibilitySettings: openAccessibilitySettings,
- restartApp: restartApp,
- revealAppInFinder: revealAppInFinder,
- openApplicationsFolder: openApplicationsFolder
+ appear: self.$appear,
+ visualizerNoiseThreshold: self.$visualizerNoiseThreshold,
+ selectedInputUID: self.$selectedInputUID,
+ selectedOutputUID: self.$selectedOutputUID,
+ inputDevices: self.$inputDevices,
+ outputDevices: self.$outputDevices,
+ accessibilityEnabled: self.$accessibilityEnabled,
+ hotkeyShortcut: self.$hotkeyShortcut,
+ isRecordingShortcut: self.$isRecordingShortcut,
+ commandModeShortcut: self.$commandModeHotkeyShortcut,
+ isRecordingCommandModeShortcut: self.$isRecordingCommandModeShortcut,
+ rewriteShortcut: self.$rewriteModeHotkeyShortcut,
+ isRecordingRewriteShortcut: self.$isRecordingRewriteShortcut,
+ commandModeShortcutEnabled: self.$isCommandModeShortcutEnabled,
+ rewriteShortcutEnabled: self.$isRewriteModeShortcutEnabled,
+ hotkeyManagerInitialized: self.$hotkeyManagerInitialized,
+ pressAndHoldModeEnabled: self.$pressAndHoldModeEnabled,
+ enableStreamingPreview: self.$enableStreamingPreview,
+ copyToClipboard: self.$copyToClipboard,
+ hotkeyManager: self.hotkeyManager,
+ menuBarManager: self.menuBarManager,
+ startRecording: self.startRecording,
+ refreshDevices: self.refreshDevices,
+ openAccessibilitySettings: self.openAccessibilitySettings,
+ restartApp: self.restartApp,
+ revealAppInFinder: self.revealAppInFinder,
+ openApplicationsFolder: self.openApplicationsFolder
)
}
private var recordingView: some View {
RecordingView(
- appear: $appear,
+ appear: self.$appear,
stopAndProcessTranscription: { await self.stopAndProcessTranscription() },
- startRecording: startRecording
+ startRecording: self.startRecording
)
}
private var commandModeView: some View {
- CommandModeView(service: commandModeService, onClose: {
+ CommandModeView(service: self.commandModeService, onClose: {
self.selectedSidebarItem = .welcome
})
}
private var rewriteModeView: some View {
- RewriteModeView(service: rewriteModeService, onClose: {
+ RewriteModeView(service: self.rewriteModeService, onClose: {
self.selectedSidebarItem = .welcome
})
}
@@ -960,7 +960,7 @@ struct ContentView: View {
// MARK: - Meeting Transcription (Coming Soon)
private var meetingToolsView: some View {
- MeetingTranscriptionView(asrService: asr)
+ MeetingTranscriptionView(asrService: self.asr)
}
// MARK: - Stats View
@@ -972,20 +972,20 @@ struct ContentView: View {
// Audio settings merged into SettingsView
private func refreshDevices() {
- inputDevices = AudioDevice.listInputDevices()
- outputDevices = AudioDevice.listOutputDevices()
+ self.inputDevices = AudioDevice.listInputDevices()
+ self.outputDevices = AudioDevice.listOutputDevices()
}
// MARK: - Model Management Functions
- private func saveModels() { SettingsStore.shared.availableModels = availableModels }
+ private func saveModels() { SettingsStore.shared.availableModels = self.availableModels }
// MARK: - Provider Management Functions
private func providerKey(for providerID: String) -> String {
if providerID == "openai" || providerID == "groq" { return providerID }
// Saved providers use their stable id
- return providerID.isEmpty ? currentProvider : "custom:\(providerID)"
+ return providerID.isEmpty ? self.currentProvider : "custom:\(providerID)"
}
private func defaultModels(for providerKey: String) -> [String] {
@@ -998,15 +998,15 @@ struct ContentView: View {
private func updateCurrentProvider() {
// Map baseURL to canonical key for built-ins; else keep existing
- let url = openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
- if url.contains("openai.com") { currentProvider = "openai"; return }
- if url.contains("groq.com") { currentProvider = "groq"; return }
+ let url = self.openAIBaseURL.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
+ if url.contains("openai.com") { self.currentProvider = "openai"; return }
+ if url.contains("groq.com") { self.currentProvider = "groq"; return }
// For saved/custom, keep current or derive from selectedProviderID
- currentProvider = providerKey(for: selectedProviderID)
+ self.currentProvider = self.providerKey(for: self.selectedProviderID)
}
private func saveSavedProviders() {
- SettingsStore.shared.savedProviders = savedProviders
+ SettingsStore.shared.savedProviders = self.savedProviders
}
// MARK: - App Detection and Context-Aware Prompts
@@ -1015,7 +1015,7 @@ struct ContentView: View {
if let frontmostApp = NSWorkspace.shared.frontmostApplication {
let name = frontmostApp.localizedName ?? "Unknown"
let bundleId = frontmostApp.bundleIdentifier ?? "unknown"
- let title = getFrontmostWindowTitle(ownerPid: frontmostApp.processIdentifier) ?? ""
+ let title = self.getFrontmostWindowTitle(ownerPid: frontmostApp.processIdentifier) ?? ""
return (name: name, bundleId: bundleId, windowTitle: title)
}
return (name: "Unknown", bundleId: "unknown", windowTitle: "")
@@ -1271,8 +1271,8 @@ struct ContentView: View {
#if canImport(FoundationModels)
if #available(macOS 26.0, *) {
let provider = AppleIntelligenceProvider()
- let appInfo = recordingAppInfo ?? getCurrentAppInfo()
- let systemPrompt = buildSystemPrompt(appInfo: appInfo)
+ let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()
+ let systemPrompt = self.buildSystemPrompt(appInfo: appInfo)
DebugLogger.shared.debug("Using Apple Intelligence for transcription cleanup", source: "ContentView")
return await provider.process(systemPrompt: systemPrompt, userText: inputText)
}
@@ -1301,7 +1301,7 @@ struct ContentView: View {
return "Error: Invalid Base URL"
}
- let isLocal = isLocalEndpoint(endpoint)
+ let isLocal = self.isLocalEndpoint(endpoint)
let apiKey = storedProviderAPIKeys[derivedCurrentProvider] ?? ""
// Skip API key validation for local endpoints
@@ -1312,8 +1312,8 @@ struct ContentView: View {
}
// Get app context captured at start of recording if available
- let appInfo = recordingAppInfo ?? getCurrentAppInfo()
- let systemPrompt = buildSystemPrompt(appInfo: appInfo)
+ 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)",
@@ -1403,7 +1403,7 @@ struct ContentView: View {
if enableStreaming {
// Streaming mode - parse SSE response
DebugLogger.shared.info("Using STREAMING mode for AI request", source: "ContentView")
- return try await processStreamingResponse(request: request)
+ 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")
@@ -1498,14 +1498,14 @@ struct ContentView: View {
DebugLogger.shared.debug("stopAndProcessTranscription called", source: "ContentView")
// Check if we're in rewrite or command mode
- let wasRewriteMode = isRecordingForRewrite
- let wasCommandMode = isRecordingForCommand
+ let wasRewriteMode = self.isRecordingForRewrite
+ let wasCommandMode = self.isRecordingForCommand
if wasRewriteMode {
- isRecordingForRewrite = false
+ self.isRecordingForRewrite = false
// Don't reset overlay mode here - let it stay colored until it hides
}
if wasCommandMode {
- isRecordingForCommand = false
+ self.isRecordingForCommand = false
// Don't reset overlay mode here - let it stay colored until it hides
}
@@ -1522,14 +1522,14 @@ struct ContentView: View {
// If this was a rewrite recording, process the rewrite instead of typing
if wasRewriteMode {
DebugLogger.shared.info("Processing rewrite with instruction: \(transcribedText)", source: "ContentView")
- await processRewriteWithVoiceInstruction(transcribedText)
+ await self.processRewriteWithVoiceInstruction(transcribedText)
return
}
// If this was a command recording, process the command
if wasCommandMode {
DebugLogger.shared.info("Processing command: \(transcribedText)", source: "ContentView")
- await processCommandWithVoice(transcribedText)
+ await self.processCommandWithVoice(transcribedText)
return
}
@@ -1547,7 +1547,7 @@ struct ContentView: View {
baseURL = "https://api.openai.com/v1"
}
let trimmedBaseURL = baseURL.trimmingCharacters(in: .whitespacesAndNewlines)
- let isLocal = isLocalEndpoint(trimmedBaseURL)
+ let isLocal = self.isLocalEndpoint(trimmedBaseURL)
let apiKey = (SettingsStore.shared.getAPIKey(for: currentProviderID) ?? "")
.trimmingCharacters(in: .whitespacesAndNewlines)
let shouldUseAI = SettingsStore.shared.enableAIProcessing && (isLocal || !apiKey.isEmpty)
@@ -1556,12 +1556,12 @@ struct ContentView: View {
DebugLogger.shared.debug("Routing transcription through AI post-processing", source: "ContentView")
// Show processing animation in notch
- menuBarManager.setProcessing(true)
+ self.menuBarManager.setProcessing(true)
- finalText = await processTextWithAI(transcribedText)
+ finalText = await self.processTextWithAI(transcribedText)
// Hide processing animation
- menuBarManager.setProcessing(false)
+ self.menuBarManager.setProcessing(false)
} else {
finalText = transcribedText
}
@@ -1569,7 +1569,7 @@ struct ContentView: View {
DebugLogger.shared.info("Transcription finalized (chars: \(finalText.count))", source: "ContentView")
// Save to transcription history (transcription mode only)
- let appInfo = recordingAppInfo ?? getCurrentAppInfo()
+ let appInfo = self.recordingAppInfo ?? self.getCurrentAppInfo()
TranscriptionHistoryStore.shared.addEntry(
rawText: transcribedText,
processedText: finalText,
@@ -1603,42 +1603,42 @@ struct ContentView: View {
// MARK: - Rewrite Mode Voice Processing
private func processRewriteWithVoiceInstruction(_ instruction: String) async {
- let hasOriginalText = !rewriteModeService.originalText.isEmpty
+ let hasOriginalText = !self.rewriteModeService.originalText.isEmpty
DebugLogger.shared
.info(
- "Processing \(hasOriginalText ? "rewrite" : "write/improve") - instruction: '\(instruction)', originalText length: \(rewriteModeService.originalText.count)",
+ "Processing \(hasOriginalText ? "rewrite" : "write/improve") - instruction: '\(instruction)', originalText length: \(self.rewriteModeService.originalText.count)",
source: "ContentView"
)
// Show processing animation
- menuBarManager.setProcessing(true)
+ self.menuBarManager.setProcessing(true)
// Process the request - service handles both cases:
// - With originalText: rewrites existing text based on instruction
// - Without originalText: improves/refines the spoken text
- await rewriteModeService.processRewriteRequest(instruction)
+ await self.rewriteModeService.processRewriteRequest(instruction)
// Hide processing animation
- menuBarManager.setProcessing(false)
+ self.menuBarManager.setProcessing(false)
// If rewrite was successful, type the result
- if !rewriteModeService.rewrittenText.isEmpty {
+ if !self.rewriteModeService.rewrittenText.isEmpty {
DebugLogger.shared
.info(
- "Rewrite successful, typing result (chars: \(rewriteModeService.rewrittenText.count))",
+ "Rewrite successful, typing result (chars: \(self.rewriteModeService.rewrittenText.count))",
source: "ContentView"
)
// Copy to clipboard as backup
if SettingsStore.shared.copyTranscriptionToClipboard {
- ClipboardService.copyToClipboard(rewriteModeService.rewrittenText)
+ ClipboardService.copyToClipboard(self.rewriteModeService.rewrittenText)
}
// Type the rewritten text
- asr.typeTextToActiveField(rewriteModeService.rewrittenText)
+ self.asr.typeTextToActiveField(self.rewriteModeService.rewrittenText)
// Clear the rewrite service state for next use
- rewriteModeService.clearState()
+ self.rewriteModeService.clearState()
} else {
DebugLogger.shared.error("Rewrite failed - no result", source: "ContentView")
}
@@ -1650,14 +1650,14 @@ struct ContentView: View {
DebugLogger.shared.info("Processing voice command: '\(command)'", source: "ContentView")
// Show processing animation
- menuBarManager.setProcessing(true)
+ self.menuBarManager.setProcessing(true)
// Process the command through CommandModeService
// This stores the conversation history and executes any terminal commands
- await commandModeService.processUserCommand(command)
+ await self.commandModeService.processUserCommand(command)
// Hide processing animation
- menuBarManager.setProcessing(false)
+ self.menuBarManager.setProcessing(false)
DebugLogger.shared.info("Command processed, conversation stored in Command Mode", source: "ContentView")
}
@@ -1665,18 +1665,18 @@ struct ContentView: View {
// Capture app context at start to avoid mismatches if the user switches apps mid-session
private func startRecording() {
// Ensure normal dictation mode is set (command/rewrite modes set their own)
- if !isRecordingForCommand, !isRecordingForRewrite {
- menuBarManager.setOverlayMode(.dictation)
+ if !self.isRecordingForCommand, !self.isRecordingForRewrite {
+ self.menuBarManager.setOverlayMode(.dictation)
}
- let info = getCurrentAppInfo()
- recordingAppInfo = info
+ let info = self.getCurrentAppInfo()
+ self.recordingAppInfo = info
DebugLogger.shared
.debug(
"Captured recording app context: app=\(info.name), bundleId=\(info.bundleId), title=\(info.windowTitle)",
source: "ContentView"
)
- asr.start()
+ self.asr.start()
// Pre-load model in background while recording (avoids 10s freeze on stop)
Task {
@@ -1696,7 +1696,7 @@ struct ContentView: View {
DebugLogger.shared.debug("User initiated model download", source: "ContentView")
do {
- try await asr.ensureAsrReady()
+ try await self.asr.ensureAsrReady()
DebugLogger.shared.info("Model download completed successfully", source: "ContentView")
} catch {
DebugLogger.shared.error("Failed to download models: \(error)", source: "ContentView")
@@ -1708,7 +1708,7 @@ struct ContentView: View {
DebugLogger.shared.debug("User initiated model deletion", source: "ContentView")
do {
- try await asr.clearModelCache()
+ try await self.asr.clearModelCache()
DebugLogger.shared.info("Models deleted successfully", source: "ContentView")
} catch {
DebugLogger.shared.error("Failed to delete models: \(error)", source: "ContentView")
@@ -1725,13 +1725,13 @@ struct ContentView: View {
// MARK: - Model Management
private func addNewModel() {
- guard !newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else { return }
+ guard !self.newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines).isEmpty else { return }
- let modelName = newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
- let key = providerKey(for: selectedProviderID)
+ let modelName = self.newModelName.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines)
+ let key = self.providerKey(for: self.selectedProviderID)
// Get current list or start fresh if empty
- var list = availableModelsByProvider[key] ?? availableModels
+ var list = self.availableModelsByProvider[key] ?? self.availableModels
if list.isEmpty {
list = []
}
@@ -1742,36 +1742,36 @@ struct ContentView: View {
}
// Update state
- availableModelsByProvider[key] = list
- SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
+ self.availableModelsByProvider[key] = list
+ SettingsStore.shared.availableModelsByProvider = self.availableModelsByProvider
// Update saved provider if exists
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
let updatedProvider = SettingsStore.SavedProvider(
- id: savedProviders[providerIndex].id,
- name: savedProviders[providerIndex].name,
- baseURL: savedProviders[providerIndex].baseURL,
+ id: self.savedProviders[providerIndex].id,
+ name: self.savedProviders[providerIndex].name,
+ baseURL: self.savedProviders[providerIndex].baseURL,
models: list
)
- savedProviders[providerIndex] = updatedProvider
- saveSavedProviders()
+ self.savedProviders[providerIndex] = updatedProvider
+ self.saveSavedProviders()
}
// Update UI state
- availableModels = list
- selectedModel = modelName
- selectedModelByProvider[key] = modelName
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
+ self.availableModels = list
+ self.selectedModel = modelName
+ self.selectedModelByProvider[key] = modelName
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
// Close the add model UI
- showingAddModel = false
- newModelName = ""
+ self.showingAddModel = false
+ self.newModelName = ""
}
// MARK: - OpenAI-compatible call for playground
private func callOpenAIChat() async {
- guard !isCallingAI else { return }
+ guard !self.isCallingAI else { return }
await MainActor.run { self.isCallingAI = true }
defer { Task { await MainActor.run { isCallingAI = false } } }
@@ -1780,13 +1780,13 @@ struct ContentView: View {
}
private func getModelStatusText() -> String {
- if asr.isLoadingModel {
+ if self.asr.isLoadingModel {
return "Loading model into memory... (30-60 sec)"
- } else if asr.isDownloadingModel {
+ } else if self.asr.isDownloadingModel {
return "Downloading model... Please wait."
- } else if asr.isAsrReady {
+ } else if self.asr.isAsrReady {
return "Model is ready to use!"
- } else if asr.modelsExistOnDisk {
+ } else if self.asr.modelsExistOnDisk {
return "Model cached. Will load on first use."
} else {
return "Model will download when needed."
@@ -1810,8 +1810,8 @@ struct ContentView: View {
private func openAccessibilitySettings() {
let options = [kAXTrustedCheckOptionPrompt.takeUnretainedValue() as String: true] as CFDictionary
AXIsProcessTrustedWithOptions(options)
- didOpenAccessibilityPane = true
- UserDefaults.standard.set(true, forKey: accessibilityRestartFlagKey)
+ self.didOpenAccessibilityPane = true
+ UserDefaults.standard.set(true, forKey: self.accessibilityRestartFlagKey)
}
private func restartApp() {
@@ -1820,8 +1820,8 @@ struct ContentView: View {
process.launchPath = "/usr/bin/open"
process.arguments = ["-n", appPath]
// Clear pending flag and hide prompt before restarting
- UserDefaults.standard.set(false, forKey: accessibilityRestartFlagKey)
- showRestartPrompt = false
+ UserDefaults.standard.set(false, forKey: self.accessibilityRestartFlagKey)
+ self.showRestartPrompt = false
try? process.run()
DispatchQueue.main.asyncAfter(deadline: .now() + 0.2) {
NSApp.terminate(nil)
@@ -1830,14 +1830,14 @@ struct ContentView: View {
private func startAccessibilityPolling() {
// Don't poll if already enabled or if we've already auto-restarted once
- guard !accessibilityEnabled else { return }
- guard !UserDefaults.standard.bool(forKey: hasAutoRestartedForAccessibilityKey) else { return }
+ guard !self.accessibilityEnabled else { return }
+ guard !UserDefaults.standard.bool(forKey: self.hasAutoRestartedForAccessibilityKey) else { return }
// Cancel any existing polling task
- accessibilityPollingTask?.cancel()
+ self.accessibilityPollingTask?.cancel()
// Start background polling
- accessibilityPollingTask = Task {
+ self.accessibilityPollingTask = Task {
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: 2_000_000_000) // Poll every 2 seconds
@@ -1874,15 +1874,15 @@ struct ContentView: View {
}
private func initializeHotkeyManagerIfNeeded() {
- guard hotkeyManager == nil else { return }
-
- hotkeyManager = GlobalHotkeyManager(
- asrService: asr,
- shortcut: hotkeyShortcut,
- commandModeShortcut: commandModeHotkeyShortcut,
- rewriteModeShortcut: rewriteModeHotkeyShortcut,
- commandModeShortcutEnabled: isCommandModeShortcutEnabled,
- rewriteModeShortcutEnabled: isRewriteModeShortcutEnabled,
+ guard self.hotkeyManager == nil else { return }
+
+ self.hotkeyManager = GlobalHotkeyManager(
+ asrService: self.asr,
+ shortcut: self.hotkeyShortcut,
+ commandModeShortcut: self.commandModeHotkeyShortcut,
+ rewriteModeShortcut: self.rewriteModeHotkeyShortcut,
+ commandModeShortcutEnabled: self.isCommandModeShortcutEnabled,
+ rewriteModeShortcutEnabled: self.isRewriteModeShortcutEnabled,
startRecordingCallback: {
self.startRecording()
},
@@ -1949,13 +1949,13 @@ struct ContentView: View {
}
)
- hotkeyManagerInitialized = hotkeyManager?.validateEventTapHealth() ?? false
+ self.hotkeyManagerInitialized = self.hotkeyManager?.validateEventTapHealth() ?? false
- hotkeyManager?.enablePressAndHoldMode(pressAndHoldModeEnabled)
+ self.hotkeyManager?.enablePressAndHoldMode(self.pressAndHoldModeEnabled)
// Set cancel callback for Escape key handling (closes mode views, resets recording state)
// Returns true if it handled something (so GlobalHotkeyManager knows to consume the event)
- hotkeyManager?.setCancelCallback {
+ self.hotkeyManager?.setCancelCallback {
var handled = false
// Close expanded command notch if visible (highest priority)
@@ -2023,22 +2023,22 @@ struct ContentView: View {
private func isCustomModel(_ model: String) -> Bool {
// Non-removable defaults are the provider's default models
- return !defaultModels(for: currentProvider).contains(model)
+ return !self.defaultModels(for: self.currentProvider).contains(model)
}
/// Check if the current model has a reasoning config (either custom or auto-detected)
private func hasReasoningConfigForCurrentModel() -> Bool {
- let providerKey = self.providerKey(for: selectedProviderID)
+ let providerKey = self.providerKey(for: self.selectedProviderID)
// Check for custom config first
- if SettingsStore.shared.hasCustomReasoningConfig(forModel: selectedModel, provider: providerKey) {
+ if SettingsStore.shared.hasCustomReasoningConfig(forModel: self.selectedModel, provider: providerKey) {
if let config = SettingsStore.shared.getReasoningConfig(forModel: selectedModel, provider: providerKey) {
return config.isEnabled
}
}
// Check for auto-detected models
- let modelLower = selectedModel.lowercased()
+ 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/") ||
@@ -2047,36 +2047,36 @@ struct ContentView: View {
private func removeModel(_ model: String) {
// Don't remove if it's currently selected
- if selectedModel == model {
+ if self.selectedModel == model {
// Switch to first available model that's not the one being removed
if let firstOther = availableModels.first(where: { $0 != model }) {
- selectedModel = firstOther
+ self.selectedModel = firstOther
}
}
// Remove from current provider's model list
- availableModels.removeAll { $0 == model }
+ self.availableModels.removeAll { $0 == model }
// Update the stored models for this provider
- let key = providerKey(for: selectedProviderID)
- availableModelsByProvider[key] = availableModels
- SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
+ let key = self.providerKey(for: self.selectedProviderID)
+ self.availableModelsByProvider[key] = self.availableModels
+ SettingsStore.shared.availableModelsByProvider = self.availableModelsByProvider
// If this is a saved custom provider, update its models array too
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
let updatedProvider = SettingsStore.SavedProvider(
- id: savedProviders[providerIndex].id,
- name: savedProviders[providerIndex].name,
- baseURL: savedProviders[providerIndex].baseURL,
- models: availableModels
+ id: self.savedProviders[providerIndex].id,
+ name: self.savedProviders[providerIndex].name,
+ baseURL: self.savedProviders[providerIndex].baseURL,
+ models: self.availableModels
)
- savedProviders[providerIndex] = updatedProvider
- saveSavedProviders()
+ self.savedProviders[providerIndex] = updatedProvider
+ self.saveSavedProviders()
}
// Update selected model mapping for this provider
- selectedModelByProvider[key] = selectedModel
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
+ self.selectedModelByProvider[key] = self.selectedModel
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
}
// Deprecated: hotkey persistence is handled via SettingsStore
@@ -2094,11 +2094,11 @@ struct CardAppearAnimation: ViewModifier {
func body(content: Content) -> some View {
content
- .scaleEffect(appear ? 1.0 : 0.96)
- .opacity(appear ? 1.0 : 0)
+ .scaleEffect(self.appear ? 1.0 : 0.96)
+ .opacity(self.appear ? 1.0 : 0)
.animation(
- .spring(response: 0.8, dampingFraction: 0.75, blendDuration: 0.2).delay(delay),
- value: appear
+ .spring(response: 0.8, dampingFraction: 0.75, blendDuration: 0.2).delay(self.delay),
+ value: self.appear
)
}
}
diff --git a/Sources/Fluid/CustomAnimations.swift b/Sources/Fluid/CustomAnimations.swift
index 161ac28c..d99b2123 100644
--- a/Sources/Fluid/CustomAnimations.swift
+++ b/Sources/Fluid/CustomAnimations.swift
@@ -55,7 +55,7 @@ struct PulseAudioVisualizationView: View {
.frame(width: 12, height: 12)
}
.frame(width: 100, height: 100)
- .onChange(of: data.audioLevel) { _, newLevel in
+ .onChange(of: self.data.audioLevel) { _, newLevel in
// Only trigger animation update for significant changes to prevent cycles
if abs(newLevel - (self.data.audioLevel)) > 0.1 {
self.animationId = UUID()
@@ -90,7 +90,7 @@ struct WaveAudioVisualizationView: View {
}
}
.frame(width: 60, height: 40)
- .onChange(of: data.audioLevel) { _, newLevel in
+ .onChange(of: self.data.audioLevel) { _, newLevel in
// Only trigger animation update for significant changes to prevent cycles
if abs(newLevel - (self.data.audioLevel)) > 0.1 {
self.animationId = UUID()
diff --git a/Sources/Fluid/Models/HotkeyShortcut.swift b/Sources/Fluid/Models/HotkeyShortcut.swift
index 77c73c5f..861968a9 100644
--- a/Sources/Fluid/Models/HotkeyShortcut.swift
+++ b/Sources/Fluid/Models/HotkeyShortcut.swift
@@ -8,18 +8,18 @@ struct HotkeyShortcut: Codable, Equatable {
var displayString: String {
var parts: [String] = []
- if modifierFlags.contains(.function) { parts.append("🌐") }
- if modifierFlags.contains(.command) { parts.append("⌘") }
- if modifierFlags.contains(.option) { parts.append("⌥") }
- if modifierFlags.contains(.control) { parts.append("⌃") }
- if modifierFlags.contains(.shift) { parts.append("⇧") }
+ if self.modifierFlags.contains(.function) { parts.append("🌐") }
+ if self.modifierFlags.contains(.command) { parts.append("⌘") }
+ if self.modifierFlags.contains(.option) { parts.append("⌥") }
+ if self.modifierFlags.contains(.control) { parts.append("⌃") }
+ if self.modifierFlags.contains(.shift) { parts.append("⇧") }
if let key = Self.keyCodeToString(keyCode) {
parts.append(key)
} else {
- parts.append(String(Character(UnicodeScalar(keyCode) ?? "?")))
+ parts.append(String(Character(UnicodeScalar(self.keyCode) ?? "?")))
}
- if modifierFlags.isEmpty {
+ if self.modifierFlags.isEmpty {
return parts.last ?? "Unknown"
}
@@ -101,14 +101,14 @@ struct HotkeyShortcut: Codable, Equatable {
extension HotkeyShortcut {
init(from decoder: Decoder) throws {
let c = try decoder.container(keyedBy: CodingKeys.self)
- keyCode = try c.decode(UInt16.self, forKey: .keyCode)
+ self.keyCode = try c.decode(UInt16.self, forKey: .keyCode)
let raw = try c.decode(UInt.self, forKey: .modifierFlagsRawValue)
- modifierFlags = NSEvent.ModifierFlags(rawValue: raw)
+ self.modifierFlags = NSEvent.ModifierFlags(rawValue: raw)
}
func encode(to encoder: Encoder) throws {
var c = encoder.container(keyedBy: CodingKeys.self)
- try c.encode(keyCode, forKey: .keyCode)
- try c.encode(modifierFlags.rawValue, forKey: .modifierFlagsRawValue)
+ try c.encode(self.keyCode, forKey: .keyCode)
+ try c.encode(self.modifierFlags.rawValue, forKey: .modifierFlagsRawValue)
}
}
diff --git a/Sources/Fluid/Networking/AIProvider.swift b/Sources/Fluid/Networking/AIProvider.swift
index fa7804fe..2503851e 100644
--- a/Sources/Fluid/Networking/AIProvider.swift
+++ b/Sources/Fluid/Networking/AIProvider.swift
@@ -101,10 +101,10 @@ final class OpenAICompatibleProvider: AIProvider {
guard let url = URL(string: fullEndpoint) else { return "Error: Invalid Base URL" }
- let isLocal = isLocalEndpoint(endpoint)
+ let isLocal = self.isLocalEndpoint(endpoint)
// Check if model is gpt-oss and add reasoning_effort parameter
- let shouldAddReasoningEffort = isGptOssModel(model)
+ let shouldAddReasoningEffort = self.isGptOssModel(model)
// Check if this is a reasoning model that doesn't support temperature parameter
let modelLower = model.lowercased()
diff --git a/Sources/Fluid/Networking/FunctionCallingProvider.swift b/Sources/Fluid/Networking/FunctionCallingProvider.swift
index 0a96bec7..dd25a175 100644
--- a/Sources/Fluid/Networking/FunctionCallingProvider.swift
+++ b/Sources/Fluid/Networking/FunctionCallingProvider.swift
@@ -44,22 +44,22 @@ final class FunctionCallingProvider {
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
- role = try container.decode(String.self, forKey: .role)
- content = try container.decodeIfPresent(String.self, forKey: .content)
- tool_calls = try container.decodeIfPresent([ToolCall].self, forKey: .tool_calls) ?? []
- tool_call_id = try container.decodeIfPresent(String.self, forKey: .tool_call_id)
- name = try container.decodeIfPresent(String.self, forKey: .name)
+ self.role = try container.decode(String.self, forKey: .role)
+ self.content = try container.decodeIfPresent(String.self, forKey: .content)
+ self.tool_calls = try container.decodeIfPresent([ToolCall].self, forKey: .tool_calls) ?? []
+ self.tool_call_id = try container.decodeIfPresent(String.self, forKey: .tool_call_id)
+ self.name = try container.decodeIfPresent(String.self, forKey: .name)
}
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
- try container.encode(role, forKey: .role)
- try container.encodeIfPresent(content, forKey: .content)
- if tool_calls.isEmpty == false {
- try container.encode(tool_calls, forKey: .tool_calls)
+ try container.encode(self.role, forKey: .role)
+ try container.encodeIfPresent(self.content, forKey: .content)
+ if self.tool_calls.isEmpty == false {
+ try container.encode(self.tool_calls, forKey: .tool_calls)
}
- try container.encodeIfPresent(tool_call_id, forKey: .tool_call_id)
- try container.encodeIfPresent(name, forKey: .name)
+ try container.encodeIfPresent(self.tool_call_id, forKey: .tool_call_id)
+ try container.encodeIfPresent(self.name, forKey: .name)
}
}
@@ -76,13 +76,13 @@ final class FunctionCallingProvider {
func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
- try container.encode(model, forKey: .model)
- try container.encode(messages, forKey: .messages)
- try container.encodeIfPresent(temperature, forKey: .temperature)
- try container.encodeIfPresent(tool_choice, forKey: .tool_choice)
+ try container.encode(self.model, forKey: .model)
+ try container.encode(self.messages, forKey: .messages)
+ try container.encodeIfPresent(self.temperature, forKey: .temperature)
+ try container.encodeIfPresent(self.tool_choice, forKey: .tool_choice)
- if tools.isEmpty == false {
- let toolsData = try JSONSerialization.data(withJSONObject: tools)
+ if self.tools.isEmpty == false {
+ let toolsData = try JSONSerialization.data(withJSONObject: self.tools)
let toolsArray = try JSONDecoder().decode([AnyCodable].self, from: toolsData)
try container.encode(toolsArray, forKey: .tools)
}
@@ -110,19 +110,19 @@ final class FunctionCallingProvider {
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
if let dict = try? container.decode([String: AnyCodable].self) {
- value = dict.mapValues { $0.value }
+ self.value = dict.mapValues { $0.value }
} else if let array = try? container.decode([AnyCodable].self) {
- value = array.map { $0.value }
+ self.value = array.map { $0.value }
} else if let string = try? container.decode(String.self) {
- value = string
+ self.value = string
} else if let int = try? container.decode(Int.self) {
- value = int
+ self.value = int
} else if let double = try? container.decode(Double.self) {
- value = double
+ self.value = double
} else if let bool = try? container.decode(Bool.self) {
- value = bool
+ self.value = bool
} else {
- value = NSNull()
+ self.value = NSNull()
}
}
@@ -213,7 +213,7 @@ final class FunctionCallingProvider {
return .error("Invalid Base URL")
}
- let isLocal = isLocalEndpoint(endpoint)
+ let isLocal = self.isLocalEndpoint(endpoint)
// Build messages array
var messages = conversationHistory
@@ -356,7 +356,7 @@ final class FunctionCallingProvider {
return .error("Invalid Base URL")
}
- let isLocal = isLocalEndpoint(endpoint)
+ let isLocal = self.isLocalEndpoint(endpoint)
// Use conversation history as-is (tool messages should already be added by caller)
let messages = conversationHistory
diff --git a/Sources/Fluid/Networking/ModelDownloader.swift b/Sources/Fluid/Networking/ModelDownloader.swift
index 826fba4d..9870566c 100644
--- a/Sources/Fluid/Networking/ModelDownloader.swift
+++ b/Sources/Fluid/Networking/ModelDownloader.swift
@@ -29,26 +29,26 @@ final class HuggingFaceModelDownloader {
/// Initialize with default model repository settings
init() {
- owner = "FluidInference"
- repo = "parakeet-tdt-0.6b-v3-coreml"
- revision = "main"
+ self.owner = "FluidInference"
+ self.repo = "parakeet-tdt-0.6b-v3-coreml"
+ self.revision = "main"
guard var apiBase = URL(string: "https://huggingface.co/api/models/") else {
preconditionFailure("Invalid base Hugging Face API URL")
}
- apiBase.appendPathComponent(owner)
- apiBase.appendPathComponent(repo)
+ apiBase.appendPathComponent(self.owner)
+ apiBase.appendPathComponent(self.repo)
apiBase.appendPathComponent("tree")
- apiBase.appendPathComponent(revision)
- baseApiURL = apiBase
+ apiBase.appendPathComponent(self.revision)
+ self.baseApiURL = apiBase
guard var resolveBase = URL(string: "https://huggingface.co/") else {
preconditionFailure("Invalid base Hugging Face resolve URL")
}
- resolveBase.appendPathComponent(owner)
- resolveBase.appendPathComponent(repo)
+ resolveBase.appendPathComponent(self.owner)
+ resolveBase.appendPathComponent(self.repo)
resolveBase.appendPathComponent("resolve")
- resolveBase.appendPathComponent(revision)
- baseResolveURL = resolveBase
+ resolveBase.appendPathComponent(self.revision)
+ self.baseResolveURL = resolveBase
}
/// Initialize with custom model repository settings
@@ -67,7 +67,7 @@ final class HuggingFaceModelDownloader {
apiBase.appendPathComponent(repo)
apiBase.appendPathComponent("tree")
apiBase.appendPathComponent(revision)
- baseApiURL = apiBase
+ self.baseApiURL = apiBase
guard var resolveBase = URL(string: "https://huggingface.co/") else {
preconditionFailure("Invalid base Hugging Face resolve URL")
@@ -76,7 +76,7 @@ final class HuggingFaceModelDownloader {
resolveBase.appendPathComponent(repo)
resolveBase.appendPathComponent("resolve")
resolveBase.appendPathComponent(revision)
- baseResolveURL = resolveBase
+ self.baseResolveURL = resolveBase
}
func ensureModelsPresent(at targetRoot: URL, onProgress: ((Double, String) -> Void)? = nil) async throws {
@@ -84,7 +84,7 @@ final class HuggingFaceModelDownloader {
// Build list of files to download (flatten directories via HF API tree)
var pendingFiles: [String] = []
- for item in requiredItems() {
+ for item in self.requiredItems() {
if item.isDirectory {
let files = try await listFilesRecursively(relativePath: item.path)
for rel in files {
@@ -126,7 +126,7 @@ final class HuggingFaceModelDownloader {
for (idx, rel) in pendingFiles.enumerated() {
print("[ModelDL] (\(idx + 1)/\(pendingFiles.count)) Downloading: \(rel)")
- try await downloadFile(relativePath: rel, to: targetRoot.appendingPathComponent(rel)) { perFilePct in
+ try await self.downloadFile(relativePath: rel, to: targetRoot.appendingPathComponent(rel)) { perFilePct in
if totalBytes > 0 {
let expected = sizeByPath[rel] ?? 0
if expected > 0 {
@@ -175,7 +175,7 @@ final class HuggingFaceModelDownloader {
at: dest.deletingLastPathComponent(),
withIntermediateDirectories: true
)
- try await downloadFile(relativePath: rel, to: dest)
+ try await self.downloadFile(relativePath: rel, to: dest)
}
}
@@ -184,7 +184,7 @@ final class HuggingFaceModelDownloader {
to destination: URL,
perFileProgress: ((Double) -> Void)? = nil
) async throws {
- let fileURL = baseResolveURL.appendingPathComponent(relativePath)
+ let fileURL = self.baseResolveURL.appendingPathComponent(relativePath)
let delegate = DownloadProgressDelegate(onProgress: perFileProgress)
let session = URLSession(configuration: .default, delegate: delegate, delegateQueue: nil)
@@ -232,11 +232,11 @@ final class HuggingFaceModelDownloader {
didFinishDownloadingTo location: URL
) {
guard let response = downloadTask.response else { return }
- onFinish?(location, response)
+ self.onFinish?(location, response)
}
func urlSession(_ session: URLSession, task: URLSessionTask, didCompleteWithError error: Error?) {
- if let error = error { onError?(error) }
+ if let error = error { self.onError?(error) }
}
func urlSession(
@@ -248,12 +248,12 @@ final class HuggingFaceModelDownloader {
) {
guard totalBytesExpectedToWrite > 0 else { return }
let pct = Double(totalBytesWritten) / Double(totalBytesExpectedToWrite)
- onProgress?(pct)
+ self.onProgress?(pct)
}
}
private func headExpectedLength(relativePath: String) async throws -> Int64 {
- let fileURL = baseResolveURL.appendingPathComponent(relativePath)
+ let fileURL = self.baseResolveURL.appendingPathComponent(relativePath)
var req = URLRequest(url: fileURL)
req.httpMethod = "HEAD"
let (_, resp) = try await URLSession.shared.data(for: req)
@@ -264,7 +264,7 @@ final class HuggingFaceModelDownloader {
}
private func listFilesRecursively(relativePath: String) async throws -> [String] {
- let listingURL = baseApiURL
+ let listingURL = self.baseApiURL
.appendingPathComponent(relativePath)
guard var comps = URLComponents(url: listingURL, resolvingAgainstBaseURL: false) else {
throw NSError(domain: "HF", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid listing URL components"])
diff --git a/Sources/Fluid/Persistence/ChatHistoryStore.swift b/Sources/Fluid/Persistence/ChatHistoryStore.swift
index edf8f86e..aef02a87 100644
--- a/Sources/Fluid/Persistence/ChatHistoryStore.swift
+++ b/Sources/Fluid/Persistence/ChatHistoryStore.swift
@@ -79,9 +79,9 @@ struct ChatSession: Codable, Identifiable, Equatable {
guard let firstUserMessage = messages.first(where: { $0.role == .user }) else { return }
let content = firstUserMessage.content.trimmingCharacters(in: .whitespacesAndNewlines)
if content.count > 50 {
- title = String(content.prefix(47)) + "..."
+ self.title = String(content.prefix(47)) + "..."
} else {
- title = content.isEmpty ? "New Chat" : content
+ self.title = content.isEmpty ? "New Chat" : content
}
}
@@ -89,7 +89,7 @@ struct ChatSession: Codable, Identifiable, Equatable {
var relativeTimeString: String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .abbreviated
- return formatter.localizedString(for: updatedAt, relativeTo: Date())
+ return formatter.localizedString(for: self.updatedAt, relativeTo: Date())
}
}
@@ -111,18 +111,18 @@ final class ChatHistoryStore: ObservableObject {
@Published var currentChatID: String?
private init() {
- loadSessions()
+ self.loadSessions()
// Ensure there's always a current chat
- if currentChatID == nil || sessions.first(where: { $0.id == currentChatID }) == nil {
+ if self.currentChatID == nil || self.sessions.first(where: { $0.id == currentChatID }) == nil {
if let first = sessions.first {
- currentChatID = first.id
+ self.currentChatID = first.id
} else {
// Create initial chat
let newChat = ChatSession()
- sessions = [newChat]
- currentChatID = newChat.id
- saveSessions()
+ self.sessions = [newChat]
+ self.currentChatID = newChat.id
+ self.saveSessions()
}
}
}
@@ -132,12 +132,12 @@ final class ChatHistoryStore: ObservableObject {
/// Get the current active chat session
var currentSession: ChatSession? {
guard let id = currentChatID else { return nil }
- return sessions.first(where: { $0.id == id })
+ return self.sessions.first(where: { $0.id == id })
}
/// Get recent chats for dropdown (excluding current, sorted by updatedAt)
func getRecentChats(excludingCurrent: Bool = true) -> [ChatSession] {
- var result = sessions.sorted { $0.updatedAt > $1.updatedAt }
+ var result = self.sessions.sorted { $0.updatedAt > $1.updatedAt }
if excludingCurrent, let currentID = currentChatID {
result = result.filter { $0.id != currentID }
}
@@ -148,12 +148,12 @@ final class ChatHistoryStore: ObservableObject {
@discardableResult
func createNewChat() -> ChatSession {
let newChat = ChatSession()
- sessions.insert(newChat, at: 0)
- currentChatID = newChat.id
+ self.sessions.insert(newChat, at: 0)
+ self.currentChatID = newChat.id
// Trim old chats if over limit
- trimOldChats()
- saveSessions()
+ self.trimOldChats()
+ self.saveSessions()
return newChat
}
@@ -163,15 +163,15 @@ final class ChatHistoryStore: ObservableObject {
if let index = sessions.firstIndex(where: { $0.id == session.id }) {
var updated = session
updated.updatedAt = Date()
- sessions[index] = updated
+ self.sessions[index] = updated
} else {
var updated = session
updated.updatedAt = Date()
- sessions.insert(updated, at: 0)
+ self.sessions.insert(updated, at: 0)
}
- trimOldChats()
- saveSessions()
+ self.trimOldChats()
+ self.saveSessions()
}
/// Update current chat with messages
@@ -179,50 +179,50 @@ final class ChatHistoryStore: ObservableObject {
guard let id = currentChatID,
let index = sessions.firstIndex(where: { $0.id == id }) else { return }
- var session = sessions[index]
+ var session = self.sessions[index]
session.messages = messages
session.updatedAt = Date()
session.updateTitleFromFirstMessage()
- sessions[index] = session
+ self.sessions[index] = session
- saveSessions()
+ self.saveSessions()
}
/// Load a chat by ID and set as current
func loadChat(id: String) -> ChatSession? {
guard let session = sessions.first(where: { $0.id == id }) else { return nil }
- currentChatID = id
- saveCurrentChatID()
+ self.currentChatID = id
+ self.saveCurrentChatID()
return session
}
/// Switch to a different chat
func switchToChat(id: String) -> ChatSession? {
- return loadChat(id: id)
+ return self.loadChat(id: id)
}
/// Delete a chat by ID
func deleteChat(id: String) {
- sessions.removeAll { $0.id == id }
+ self.sessions.removeAll { $0.id == id }
// If deleted current chat, switch to most recent or create new
- if currentChatID == id {
+ if self.currentChatID == id {
if let first = sessions.sorted(by: { $0.updatedAt > $1.updatedAt }).first {
- currentChatID = first.id
+ self.currentChatID = first.id
} else {
// No chats left, create new
- let newChat = createNewChat()
- currentChatID = newChat.id
+ let newChat = self.createNewChat()
+ self.currentChatID = newChat.id
}
}
- saveSessions()
+ self.saveSessions()
}
/// Delete current chat and switch to next
func deleteCurrentChat() {
guard let id = currentChatID else { return }
- deleteChat(id: id)
+ self.deleteChat(id: id)
}
/// Clear current chat (delete messages but keep session)
@@ -230,11 +230,11 @@ final class ChatHistoryStore: ObservableObject {
guard let id = currentChatID,
let index = sessions.firstIndex(where: { $0.id == id }) else { return }
- sessions[index].messages = []
- sessions[index].title = "New Chat"
- sessions[index].updatedAt = Date()
+ self.sessions[index].messages = []
+ self.sessions[index].title = "New Chat"
+ self.sessions[index].updatedAt = Date()
- saveSessions()
+ self.saveSessions()
}
// MARK: - Private Methods
@@ -243,32 +243,32 @@ final class ChatHistoryStore: ObservableObject {
guard let data = defaults.data(forKey: Keys.chatSessions),
let decoded = try? JSONDecoder().decode([ChatSession].self, from: data)
else {
- sessions = []
+ self.sessions = []
return
}
- sessions = decoded
+ self.sessions = decoded
// Load current chat ID
- currentChatID = defaults.string(forKey: Keys.currentChatID)
+ self.currentChatID = self.defaults.string(forKey: Keys.currentChatID)
}
private func saveSessions() {
if let encoded = try? JSONEncoder().encode(sessions) {
- defaults.set(encoded, forKey: Keys.chatSessions)
+ self.defaults.set(encoded, forKey: Keys.chatSessions)
}
- saveCurrentChatID()
+ self.saveCurrentChatID()
objectWillChange.send()
}
private func saveCurrentChatID() {
- defaults.set(currentChatID, forKey: Keys.currentChatID)
+ self.defaults.set(self.currentChatID, forKey: Keys.currentChatID)
}
private func trimOldChats() {
- if sessions.count > maxChats {
+ if self.sessions.count > self.maxChats {
// Sort by updatedAt and keep most recent
- let sorted = sessions.sorted { $0.updatedAt > $1.updatedAt }
- sessions = Array(sorted.prefix(maxChats))
+ let sorted = self.sessions.sorted { $0.updatedAt > $1.updatedAt }
+ self.sessions = Array(sorted.prefix(self.maxChats))
}
}
}
diff --git a/Sources/Fluid/Persistence/KeychainService.swift b/Sources/Fluid/Persistence/KeychainService.swift
index 3b5efeed..3b028552 100644
--- a/Sources/Fluid/Persistence/KeychainService.swift
+++ b/Sources/Fluid/Persistence/KeychainService.swift
@@ -34,7 +34,7 @@ final class KeychainService {
let trimmed = key.trimmingCharacters(in: .whitespacesAndNewlines)
var keys = try loadStoredKeys()
keys[providerID] = trimmed
- try saveStoredKeys(keys)
+ try self.saveStoredKeys(keys)
}
func fetchKey(for providerID: String) throws -> String? {
@@ -45,7 +45,7 @@ final class KeychainService {
func deleteKey(for providerID: String) throws {
var keys = try loadStoredKeys()
guard keys.removeValue(forKey: providerID) != nil else { return }
- try saveStoredKeys(keys)
+ try self.saveStoredKeys(keys)
}
func containsKey(for providerID: String) -> Bool {
@@ -54,22 +54,22 @@ final class KeychainService {
}
func allProviderIDs() throws -> [String] {
- return try loadStoredKeys().keys.sorted()
+ return try self.loadStoredKeys().keys.sorted()
}
func fetchAllKeys() throws -> [String: String] {
- try loadStoredKeys()
+ try self.loadStoredKeys()
}
func storeAllKeys(_ values: [String: String]) throws {
- try saveStoredKeys(values)
+ try self.saveStoredKeys(values)
}
func legacyProviderEntries() throws -> [String: String] {
var result: [String: String] = [:]
let query: [String: Any] = [
kSecClass as String: kSecClassGenericPassword,
- kSecAttrService as String: service,
+ kSecAttrService as String: self.service,
kSecReturnAttributes as String: true,
kSecReturnData as String: true,
kSecMatchLimit as String: kSecMatchLimitAll,
@@ -102,7 +102,7 @@ final class KeychainService {
func removeLegacyEntries(providerIDs: [String] = []) throws {
let targets: [String]
if providerIDs.isEmpty {
- targets = try Array(legacyProviderEntries().keys)
+ targets = try Array(self.legacyProviderEntries().keys)
} else {
targets = providerIDs
}
@@ -118,7 +118,7 @@ final class KeychainService {
// MARK: - Private helpers
private func loadStoredKeys() throws -> [String: String] {
- var query = aggregatedQuery()
+ var query = self.aggregatedQuery()
query[kSecReturnData as String] = kCFBooleanTrue
query[kSecMatchLimit as String] = kSecMatchLimitOne
@@ -148,7 +148,7 @@ final class KeychainService {
private func saveStoredKeys(_ keys: [String: String]) throws {
let data = try JSONEncoder().encode(keys)
- var attributes = aggregatedQuery()
+ var attributes = self.aggregatedQuery()
attributes[kSecAttrAccessible as String] = kSecAttrAccessibleAfterFirstUnlock
attributes[kSecValueData as String] = data
@@ -156,7 +156,7 @@ final class KeychainService {
switch status {
case errSecSuccess:
- try removeLegacyEntries()
+ try self.removeLegacyEntries()
return
case errSecDuplicateItem:
let updateStatus = SecItemUpdate(
@@ -166,7 +166,7 @@ final class KeychainService {
guard updateStatus == errSecSuccess else {
throw KeychainServiceError.unhandled(updateStatus)
}
- try removeLegacyEntries()
+ try self.removeLegacyEntries()
default:
throw KeychainServiceError.unhandled(status)
}
@@ -175,15 +175,15 @@ final class KeychainService {
private func aggregatedQuery() -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword,
- kSecAttrService as String: service,
- kSecAttrAccount as String: account,
+ kSecAttrService as String: self.service,
+ kSecAttrAccount as String: self.account,
]
}
private func legacyQuery(for providerID: String) -> [String: Any] {
[
kSecClass as String: kSecClassGenericPassword,
- kSecAttrService as String: service,
+ kSecAttrService as String: self.service,
kSecAttrAccount as String: providerID,
]
}
diff --git a/Sources/Fluid/Persistence/SettingsStore.swift b/Sources/Fluid/Persistence/SettingsStore.swift
index 1efee881..696d5fb0 100644
--- a/Sources/Fluid/Persistence/SettingsStore.swift
+++ b/Sources/Fluid/Persistence/SettingsStore.swift
@@ -10,8 +10,8 @@ final class SettingsStore: ObservableObject {
private let keychain = KeychainService.shared
private init() {
- migrateProviderAPIKeysIfNeeded()
- scrubSavedProviderAPIKeys()
+ self.migrateProviderAPIKeysIfNeeded()
+ self.scrubSavedProviderAPIKeys()
}
// Keys
@@ -133,77 +133,77 @@ final class SettingsStore: ObservableObject {
}
var enableAIProcessing: Bool {
- get { defaults.bool(forKey: Keys.enableAIProcessing) }
+ get { self.defaults.bool(forKey: Keys.enableAIProcessing) }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.enableAIProcessing)
+ self.defaults.set(newValue, forKey: Keys.enableAIProcessing)
}
}
var availableModels: [String] {
- get { (defaults.array(forKey: Keys.availableAIModels) as? [String]) ?? [] }
+ get { (self.defaults.array(forKey: Keys.availableAIModels) as? [String]) ?? [] }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.availableAIModels)
+ self.defaults.set(newValue, forKey: Keys.availableAIModels)
}
}
var availableModelsByProvider: [String: [String]] {
- get { (defaults.dictionary(forKey: Keys.availableModelsByProvider) as? [String: [String]]) ?? [:] }
+ get { (self.defaults.dictionary(forKey: Keys.availableModelsByProvider) as? [String: [String]]) ?? [:] }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.availableModelsByProvider)
+ self.defaults.set(newValue, forKey: Keys.availableModelsByProvider)
}
}
var enableDebugLogs: Bool {
- get { defaults.bool(forKey: Keys.enableDebugLogs) }
+ get { self.defaults.bool(forKey: Keys.enableDebugLogs) }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.enableDebugLogs)
+ self.defaults.set(newValue, forKey: Keys.enableDebugLogs)
}
}
var selectedModel: String? {
- get { defaults.string(forKey: Keys.selectedAIModel) }
+ get { self.defaults.string(forKey: Keys.selectedAIModel) }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.selectedAIModel)
+ self.defaults.set(newValue, forKey: Keys.selectedAIModel)
}
}
var selectedModelByProvider: [String: String] {
- get { (defaults.dictionary(forKey: Keys.selectedModelByProvider) as? [String: String]) ?? [:] }
+ get { (self.defaults.dictionary(forKey: Keys.selectedModelByProvider) as? [String: String]) ?? [:] }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.selectedModelByProvider)
+ self.defaults.set(newValue, forKey: Keys.selectedModelByProvider)
}
}
var providerAPIKeys: [String: String] {
- get { (try? keychain.fetchAllKeys()) ?? [:] }
+ get { (try? self.keychain.fetchAllKeys()) ?? [:] }
set {
objectWillChange.send()
- persistProviderAPIKeys(newValue)
+ self.persistProviderAPIKeys(newValue)
}
}
/// Securely retrieve API key for a provider, handling custom prefix logic
func getAPIKey(for providerID: String) -> String? {
- let keys = providerAPIKeys
+ let keys = self.providerAPIKeys
// Try exact match first
if let key = keys[providerID] { return key }
// Try canonical key format (custom:ID)
- let canonical = canonicalProviderKey(for: providerID)
+ let canonical = self.canonicalProviderKey(for: providerID)
return keys[canonical]
}
var selectedProviderID: String {
- get { defaults.string(forKey: Keys.selectedProviderID) ?? "openai" }
+ get { self.defaults.string(forKey: Keys.selectedProviderID) ?? "openai" }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.selectedProviderID)
+ self.defaults.set(newValue, forKey: Keys.selectedProviderID)
}
}
@@ -226,7 +226,7 @@ final class SettingsStore: ObservableObject {
)
}
if let encoded = try? JSONEncoder().encode(sanitized) {
- defaults.set(encoded, forKey: Keys.savedProviders)
+ self.defaults.set(encoded, forKey: Keys.savedProviders)
}
}
}
@@ -243,66 +243,66 @@ final class SettingsStore: ObservableObject {
set {
objectWillChange.send()
if let data = try? JSONEncoder().encode(newValue) {
- defaults.set(data, forKey: Keys.hotkeyShortcutKey)
+ self.defaults.set(data, forKey: Keys.hotkeyShortcutKey)
}
}
}
var pressAndHoldMode: Bool {
- get { defaults.bool(forKey: Keys.pressAndHoldMode) }
- set { defaults.set(newValue, forKey: Keys.pressAndHoldMode) }
+ get { self.defaults.bool(forKey: Keys.pressAndHoldMode) }
+ set { self.defaults.set(newValue, forKey: Keys.pressAndHoldMode) }
}
var enableStreamingPreview: Bool {
get {
- let value = defaults.object(forKey: Keys.enableStreamingPreview)
+ let value = self.defaults.object(forKey: Keys.enableStreamingPreview)
return value as? Bool ?? true // Default to true (enabled)
}
- set { defaults.set(newValue, forKey: Keys.enableStreamingPreview) }
+ set { self.defaults.set(newValue, forKey: Keys.enableStreamingPreview) }
}
var enableAIStreaming: Bool {
get {
- let value = defaults.object(forKey: Keys.enableAIStreaming)
+ let value = self.defaults.object(forKey: Keys.enableAIStreaming)
return value as? Bool ?? false // Default to false (disabled)
}
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.enableAIStreaming)
+ self.defaults.set(newValue, forKey: Keys.enableAIStreaming)
}
}
var copyTranscriptionToClipboard: Bool {
- get { defaults.bool(forKey: Keys.copyTranscriptionToClipboard) }
- set { defaults.set(newValue, forKey: Keys.copyTranscriptionToClipboard) }
+ get { self.defaults.bool(forKey: Keys.copyTranscriptionToClipboard) }
+ set { self.defaults.set(newValue, forKey: Keys.copyTranscriptionToClipboard) }
}
var preferredInputDeviceUID: String? {
- get { defaults.string(forKey: Keys.preferredInputDeviceUID) }
- set { defaults.set(newValue, forKey: Keys.preferredInputDeviceUID) }
+ get { self.defaults.string(forKey: Keys.preferredInputDeviceUID) }
+ set { self.defaults.set(newValue, forKey: Keys.preferredInputDeviceUID) }
}
var preferredOutputDeviceUID: String? {
- get { defaults.string(forKey: Keys.preferredOutputDeviceUID) }
- set { defaults.set(newValue, forKey: Keys.preferredOutputDeviceUID) }
+ get { self.defaults.string(forKey: Keys.preferredOutputDeviceUID) }
+ set { self.defaults.set(newValue, forKey: Keys.preferredOutputDeviceUID) }
}
var visualizerNoiseThreshold: Double {
get {
- let value = defaults.double(forKey: Keys.visualizerNoiseThreshold)
+ let value = self.defaults.double(forKey: Keys.visualizerNoiseThreshold)
return value == 0.0 ? 0.4 : value // Default to 0.4 if not set
}
- set { defaults.set(newValue, forKey: Keys.visualizerNoiseThreshold) }
+ set { self.defaults.set(newValue, forKey: Keys.visualizerNoiseThreshold) }
}
// MARK: - Preferences Settings
var launchAtStartup: Bool {
- get { defaults.bool(forKey: Keys.launchAtStartup) }
+ get { self.defaults.bool(forKey: Keys.launchAtStartup) }
set {
- defaults.set(newValue, forKey: Keys.launchAtStartup)
+ self.defaults.set(newValue, forKey: Keys.launchAtStartup)
// Update launch agent registration
- updateLaunchAtStartup(newValue)
+ self.updateLaunchAtStartup(newValue)
}
}
@@ -311,7 +311,7 @@ final class SettingsStore: ObservableObject {
func initializeAppSettings() {
#if os(macOS)
// Apply dock visibility setting on app launch
- let dockVisible = showInDock
+ let dockVisible = self.showInDock
DebugLogger.shared.info("Initializing app with dock visibility: \(dockVisible)", source: "SettingsStore")
// Set activation policy based on saved preference
@@ -323,39 +323,39 @@ final class SettingsStore: ObservableObject {
var showInDock: Bool {
get {
- let value = defaults.object(forKey: Keys.showInDock)
+ let value = self.defaults.object(forKey: Keys.showInDock)
return value as? Bool ?? true // Default to true if not set
}
set {
- defaults.set(newValue, forKey: Keys.showInDock)
+ self.defaults.set(newValue, forKey: Keys.showInDock)
// Update dock visibility
- updateDockVisibility(newValue)
+ self.updateDockVisibility(newValue)
}
}
var autoUpdateCheckEnabled: Bool {
get {
- let value = defaults.object(forKey: Keys.autoUpdateCheckEnabled)
+ let value = self.defaults.object(forKey: Keys.autoUpdateCheckEnabled)
return value as? Bool ?? true // Default to enabled
}
set {
- defaults.set(newValue, forKey: Keys.autoUpdateCheckEnabled)
+ self.defaults.set(newValue, forKey: Keys.autoUpdateCheckEnabled)
}
}
var lastUpdateCheckDate: Date? {
get {
- return defaults.object(forKey: Keys.lastUpdateCheckDate) as? Date
+ return self.defaults.object(forKey: Keys.lastUpdateCheckDate) as? Date
}
set {
- defaults.set(newValue, forKey: Keys.lastUpdateCheckDate)
+ self.defaults.set(newValue, forKey: Keys.lastUpdateCheckDate)
}
}
// MARK: - Update Check Helper
func shouldCheckForUpdates() -> Bool {
- guard autoUpdateCheckEnabled else { return false }
+ guard self.autoUpdateCheckEnabled else { return false }
guard let lastCheck = lastUpdateCheckDate else {
// Never checked before, should check
@@ -368,52 +368,52 @@ final class SettingsStore: ObservableObject {
}
func updateLastCheckDate() {
- lastUpdateCheckDate = Date()
+ self.lastUpdateCheckDate = Date()
}
var playgroundUsed: Bool {
- get { defaults.bool(forKey: Keys.playgroundUsed) }
- set { defaults.set(newValue, forKey: Keys.playgroundUsed) }
+ get { self.defaults.bool(forKey: Keys.playgroundUsed) }
+ set { self.defaults.set(newValue, forKey: Keys.playgroundUsed) }
}
// MARK: - Command Mode Settings
var commandModeSelectedModel: String? {
- get { defaults.string(forKey: Keys.commandModeSelectedModel) }
+ get { self.defaults.string(forKey: Keys.commandModeSelectedModel) }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.commandModeSelectedModel)
+ self.defaults.set(newValue, forKey: Keys.commandModeSelectedModel)
}
}
var commandModeSelectedProviderID: String {
- get { defaults.string(forKey: Keys.commandModeSelectedProviderID) ?? "openai" }
+ get { self.defaults.string(forKey: Keys.commandModeSelectedProviderID) ?? "openai" }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.commandModeSelectedProviderID)
+ self.defaults.set(newValue, forKey: Keys.commandModeSelectedProviderID)
}
}
var commandModeLinkedToGlobal: Bool {
get {
- defaults
+ self.defaults
.bool(forKey: Keys.commandModeLinkedToGlobal)
} // Default to false (let user opt-in, or true if
// preferred)
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.commandModeLinkedToGlobal)
+ self.defaults.set(newValue, forKey: Keys.commandModeLinkedToGlobal)
}
}
var commandModeShortcutEnabled: Bool {
get {
- let value = defaults.object(forKey: Keys.commandModeShortcutEnabled)
+ let value = self.defaults.object(forKey: Keys.commandModeShortcutEnabled)
return value as? Bool ?? true
}
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.commandModeShortcutEnabled)
+ self.defaults.set(newValue, forKey: Keys.commandModeShortcutEnabled)
}
}
@@ -430,7 +430,7 @@ final class SettingsStore: ObservableObject {
set {
objectWillChange.send()
if let data = try? JSONEncoder().encode(newValue) {
- defaults.set(data, forKey: Keys.commandModeHotkeyShortcut)
+ self.defaults.set(data, forKey: Keys.commandModeHotkeyShortcut)
}
}
}
@@ -438,12 +438,12 @@ final class SettingsStore: ObservableObject {
var commandModeConfirmBeforeExecute: Bool {
get {
// Default to true (safer - ask before running commands)
- let value = defaults.object(forKey: Keys.commandModeConfirmBeforeExecute)
+ let value = self.defaults.object(forKey: Keys.commandModeConfirmBeforeExecute)
return value as? Bool ?? true
}
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.commandModeConfirmBeforeExecute)
+ self.defaults.set(newValue, forKey: Keys.commandModeConfirmBeforeExecute)
}
}
@@ -462,36 +462,36 @@ final class SettingsStore: ObservableObject {
set {
objectWillChange.send()
if let data = try? JSONEncoder().encode(newValue) {
- defaults.set(data, forKey: Keys.rewriteModeHotkeyShortcut)
+ self.defaults.set(data, forKey: Keys.rewriteModeHotkeyShortcut)
}
}
}
var rewriteModeSelectedModel: String? {
- get { defaults.string(forKey: Keys.rewriteModeSelectedModel) }
+ get { self.defaults.string(forKey: Keys.rewriteModeSelectedModel) }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.rewriteModeSelectedModel)
+ self.defaults.set(newValue, forKey: Keys.rewriteModeSelectedModel)
}
}
var rewriteModeSelectedProviderID: String {
- get { defaults.string(forKey: Keys.rewriteModeSelectedProviderID) ?? "openai" }
+ get { self.defaults.string(forKey: Keys.rewriteModeSelectedProviderID) ?? "openai" }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.rewriteModeSelectedProviderID)
+ self.defaults.set(newValue, forKey: Keys.rewriteModeSelectedProviderID)
}
}
var rewriteModeLinkedToGlobal: Bool {
get {
// Default to true - sync with global settings by default
- let value = defaults.object(forKey: Keys.rewriteModeLinkedToGlobal)
+ let value = self.defaults.object(forKey: Keys.rewriteModeLinkedToGlobal)
return value as? Bool ?? true
}
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.rewriteModeLinkedToGlobal)
+ self.defaults.set(newValue, forKey: Keys.rewriteModeLinkedToGlobal)
}
}
@@ -511,7 +511,7 @@ final class SettingsStore: ObservableObject {
set {
objectWillChange.send()
if let encoded = try? JSONEncoder().encode(newValue) {
- defaults.set(encoded, forKey: Keys.modelReasoningConfigs)
+ self.defaults.set(encoded, forKey: Keys.modelReasoningConfigs)
}
}
}
@@ -555,7 +555,7 @@ final class SettingsStore: ObservableObject {
/// Set reasoning config for a specific model
func setReasoningConfig(_ config: ModelReasoningConfig?, forModel model: String, provider: String) {
let key = "\(provider):\(model)"
- var configs = modelReasoningConfigs
+ var configs = self.modelReasoningConfigs
if let config = config {
configs[key] = config
@@ -563,23 +563,23 @@ final class SettingsStore: ObservableObject {
configs.removeValue(forKey: key)
}
- modelReasoningConfigs = configs
+ self.modelReasoningConfigs = configs
}
/// Check if a model has a custom (user-defined) reasoning config
func hasCustomReasoningConfig(forModel model: String, provider: String) -> Bool {
let key = "\(provider):\(model)"
- return modelReasoningConfigs[key] != nil
+ return self.modelReasoningConfigs[key] != nil
}
var rewriteModeShortcutEnabled: Bool {
get {
- let value = defaults.object(forKey: Keys.rewriteModeShortcutEnabled)
+ let value = self.defaults.object(forKey: Keys.rewriteModeShortcutEnabled)
return value as? Bool ?? true
}
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.rewriteModeShortcutEnabled)
+ self.defaults.set(newValue, forKey: Keys.rewriteModeShortcutEnabled)
}
}
@@ -588,21 +588,21 @@ final class SettingsStore: ObservableObject {
/// User's typing speed in words per minute (for time saved calculation)
var userTypingWPM: Int {
get {
- let value = defaults.integer(forKey: Keys.userTypingWPM)
+ let value = self.defaults.integer(forKey: Keys.userTypingWPM)
return value > 0 ? value : 40 // Default to 40 WPM
}
set {
objectWillChange.send()
- defaults.set(max(1, min(200, newValue)), forKey: Keys.userTypingWPM) // Clamp 1-200
+ self.defaults.set(max(1, min(200, newValue)), forKey: Keys.userTypingWPM) // Clamp 1-200
}
}
// MARK: - Private Methods
private func persistProviderAPIKeys(_ values: [String: String]) {
- let trimmed = sanitizeAPIKeys(values)
+ let trimmed = self.sanitizeAPIKeys(values)
do {
- try keychain.storeAllKeys(trimmed)
+ try self.keychain.storeAllKeys(trimmed)
} catch {
DebugLogger.shared.error(
"Failed to persist provider API keys: \(error.localizedDescription)",
@@ -612,29 +612,29 @@ final class SettingsStore: ObservableObject {
}
private func migrateProviderAPIKeysIfNeeded() {
- defaults.removeObject(forKey: Keys.providerAPIKeyIdentifiers)
+ self.defaults.removeObject(forKey: Keys.providerAPIKeyIdentifiers)
- var merged = (try? keychain.fetchAllKeys()) ?? [:]
+ var merged = (try? self.keychain.fetchAllKeys()) ?? [:]
var didMutate = false
if let legacyDefaults = defaults.dictionary(forKey: Keys.providerAPIKeys) as? [String: String],
legacyDefaults.isEmpty == false
{
- merged.merge(sanitizeAPIKeys(legacyDefaults)) { _, new in new }
+ merged.merge(self.sanitizeAPIKeys(legacyDefaults)) { _, new in new }
didMutate = true
}
- defaults.removeObject(forKey: Keys.providerAPIKeys)
+ self.defaults.removeObject(forKey: Keys.providerAPIKeys)
if let legacyKeychain = try? keychain.legacyProviderEntries(),
legacyKeychain.isEmpty == false
{
- merged.merge(sanitizeAPIKeys(legacyKeychain)) { _, new in new }
+ merged.merge(self.sanitizeAPIKeys(legacyKeychain)) { _, new in new }
didMutate = true
- try? keychain.removeLegacyEntries(providerIDs: Array(legacyKeychain.keys))
+ try? self.keychain.removeLegacyEntries(providerIDs: Array(legacyKeychain.keys))
}
if didMutate {
- persistProviderAPIKeys(merged)
+ self.persistProviderAPIKeys(merged)
}
}
@@ -648,9 +648,9 @@ final class SettingsStore: ObservableObject {
let trimmed = provider.apiKey.trimmingCharacters(in: .whitespacesAndNewlines)
guard trimmed.isEmpty == false else { continue }
- let keyID = canonicalProviderKey(for: provider.id)
+ let keyID = self.canonicalProviderKey(for: provider.id)
do {
- try keychain.storeKey(trimmed, for: keyID)
+ try self.keychain.storeKey(trimmed, for: keyID)
didModify = true
} catch {
DebugLogger.shared
@@ -672,7 +672,7 @@ final class SettingsStore: ObservableObject {
if didModify,
let encoded = try? JSONEncoder().encode(decoded)
{
- defaults.set(encoded, forKey: Keys.savedProviders)
+ self.defaults.set(encoded, forKey: Keys.savedProviders)
}
// No need to track migrated IDs; consolidated storage keeps them together.
@@ -801,15 +801,15 @@ final class SettingsStore: ObservableObject {
}
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.fillerWords)
+ self.defaults.set(newValue, forKey: Keys.fillerWords)
}
}
var removeFillerWordsEnabled: Bool {
- get { defaults.object(forKey: Keys.removeFillerWordsEnabled) as? Bool ?? true }
+ get { self.defaults.object(forKey: Keys.removeFillerWordsEnabled) as? Bool ?? true }
set {
objectWillChange.send()
- defaults.set(newValue, forKey: Keys.removeFillerWordsEnabled)
+ self.defaults.set(newValue, forKey: Keys.removeFillerWordsEnabled)
}
}
@@ -992,7 +992,7 @@ final class SettingsStore: ObservableObject {
}
set {
objectWillChange.send()
- defaults.set(newValue.rawValue, forKey: Keys.selectedTranscriptionProvider)
+ self.defaults.set(newValue.rawValue, forKey: Keys.selectedTranscriptionProvider)
}
}
@@ -1008,7 +1008,7 @@ final class SettingsStore: ObservableObject {
}
set {
objectWillChange.send()
- defaults.set(newValue.rawValue, forKey: Keys.whisperModelSize)
+ self.defaults.set(newValue.rawValue, forKey: Keys.whisperModelSize)
}
}
@@ -1030,18 +1030,18 @@ final class SettingsStore: ObservableObject {
}
// Migration: Convert old settings to new SpeechModel
- return migrateToSpeechModel()
+ return self.migrateToSpeechModel()
}
set {
objectWillChange.send()
- defaults.set(newValue.rawValue, forKey: Keys.selectedSpeechModel)
+ self.defaults.set(newValue.rawValue, forKey: Keys.selectedSpeechModel)
}
}
/// Migrates old TranscriptionProviderOption + WhisperModelSize settings to new SpeechModel
private func migrateToSpeechModel() -> SpeechModel {
- let oldProvider = defaults.string(forKey: Keys.selectedTranscriptionProvider) ?? "auto"
- let oldWhisperSize = defaults.string(forKey: Keys.whisperModelSize) ?? "ggml-base.bin"
+ let oldProvider = self.defaults.string(forKey: Keys.selectedTranscriptionProvider) ?? "auto"
+ let oldWhisperSize = self.defaults.string(forKey: Keys.whisperModelSize) ?? "ggml-base.bin"
let newModel: SpeechModel
@@ -1063,7 +1063,7 @@ final class SettingsStore: ObservableObject {
}
// Persist the migrated value
- defaults.set(newModel.rawValue, forKey: Keys.selectedSpeechModel)
+ self.defaults.set(newModel.rawValue, forKey: Keys.selectedSpeechModel)
DebugLogger.shared
.info(
"Migrated speech model settings: \(oldProvider)/\(oldWhisperSize) -> \(newModel.rawValue)",
diff --git a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
index 16636380..8553bf04 100644
--- a/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
+++ b/Sources/Fluid/Persistence/TranscriptionHistoryStore.swift
@@ -27,13 +27,13 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {
self.processedText = processedText
self.appName = appName
self.windowTitle = windowTitle
- characterCount = processedText.count
- wasAIProcessed = rawText != processedText
+ self.characterCount = processedText.count
+ self.wasAIProcessed = rawText != processedText
}
/// Preview text for list display (first 80 chars)
var previewText: String {
- let text = processedText.trimmingCharacters(in: .whitespacesAndNewlines)
+ let text = self.processedText.trimmingCharacters(in: .whitespacesAndNewlines)
if text.count > 80 {
return String(text.prefix(77)) + "..."
}
@@ -44,7 +44,7 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {
var relativeTimeString: String {
let formatter = RelativeDateTimeFormatter()
formatter.unitsStyle = .abbreviated
- return formatter.localizedString(for: timestamp, relativeTo: Date())
+ return formatter.localizedString(for: self.timestamp, relativeTo: Date())
}
/// Full formatted date string
@@ -52,7 +52,7 @@ struct TranscriptionHistoryEntry: Codable, Identifiable, Equatable {
let formatter = DateFormatter()
formatter.dateStyle = .medium
formatter.timeStyle = .short
- return formatter.string(from: timestamp)
+ return formatter.string(from: self.timestamp)
}
}
@@ -73,7 +73,7 @@ final class TranscriptionHistoryStore: ObservableObject {
@Published var selectedEntryID: UUID?
private init() {
- loadEntries()
+ self.loadEntries()
}
// MARK: - Public Methods
@@ -81,7 +81,7 @@ final class TranscriptionHistoryStore: ObservableObject {
/// Get selected entry
var selectedEntry: TranscriptionHistoryEntry? {
guard let id = selectedEntryID else { return nil }
- return entries.first(where: { $0.id == id })
+ return self.entries.first(where: { $0.id == id })
}
/// Add a new transcription entry
@@ -102,46 +102,46 @@ final class TranscriptionHistoryStore: ObservableObject {
)
// Insert at beginning (newest first)
- entries.insert(entry, at: 0)
+ self.entries.insert(entry, at: 0)
// Trim old entries if over limit
- trimOldEntries()
- saveEntries()
+ self.trimOldEntries()
+ self.saveEntries()
DebugLogger.shared.debug(
- "Added transcription to history (total: \(entries.count))",
+ "Added transcription to history (total: \(self.entries.count))",
source: "TranscriptionHistoryStore"
)
}
/// Delete a specific entry
func deleteEntry(id: UUID) {
- entries.removeAll { $0.id == id }
+ self.entries.removeAll { $0.id == id }
// Clear selection if deleted
- if selectedEntryID == id {
- selectedEntryID = entries.first?.id
+ if self.selectedEntryID == id {
+ self.selectedEntryID = self.entries.first?.id
}
- saveEntries()
+ self.saveEntries()
}
/// Delete multiple entries
func deleteEntries(ids: Set<UUID>) {
- entries.removeAll { ids.contains($0.id) }
+ self.entries.removeAll { ids.contains($0.id) }
if let selected = selectedEntryID, ids.contains(selected) {
- selectedEntryID = entries.first?.id
+ self.selectedEntryID = self.entries.first?.id
}
- saveEntries()
+ self.saveEntries()
}
/// Clear all history
func clearAllHistory() {
- entries.removeAll()
- selectedEntryID = nil
- saveEntries()
+ self.entries.removeAll()
+ self.selectedEntryID = nil
+ self.saveEntries()
DebugLogger.shared.info("Cleared all transcription history", source: "TranscriptionHistoryStore")
}
@@ -149,11 +149,11 @@ final class TranscriptionHistoryStore: ObservableObject {
/// Search entries by text content
func search(query: String) -> [TranscriptionHistoryEntry] {
guard !query.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else {
- return entries
+ return self.entries
}
let lowercased = query.lowercased()
- return entries.filter { entry in
+ return self.entries.filter { entry in
entry.rawText.lowercased().contains(lowercased) ||
entry.processedText.lowercased().contains(lowercased) ||
entry.appName.lowercased().contains(lowercased) ||
@@ -163,17 +163,17 @@ final class TranscriptionHistoryStore: ObservableObject {
/// Get entries filtered by date range
func entriesInRange(from startDate: Date, to endDate: Date) -> [TranscriptionHistoryEntry] {
- entries.filter { $0.timestamp >= startDate && $0.timestamp <= endDate }
+ self.entries.filter { $0.timestamp >= startDate && $0.timestamp <= endDate }
}
/// Get total character count across all entries
var totalCharacterCount: Int {
- entries.reduce(0) { $0 + $1.characterCount }
+ self.entries.reduce(0) { $0 + $1.characterCount }
}
/// Get count of AI-processed entries
var aiProcessedCount: Int {
- entries.filter { $0.wasAIProcessed }.count
+ self.entries.filter { $0.wasAIProcessed }.count
}
// MARK: - Private Methods
@@ -182,23 +182,23 @@ final class TranscriptionHistoryStore: ObservableObject {
guard let data = defaults.data(forKey: Keys.transcriptionHistory),
let decoded = try? JSONDecoder().decode([TranscriptionHistoryEntry].self, from: data)
else {
- entries = []
+ self.entries = []
return
}
- entries = decoded
+ self.entries = decoded
}
private func saveEntries() {
if let encoded = try? JSONEncoder().encode(entries) {
- defaults.set(encoded, forKey: Keys.transcriptionHistory)
+ self.defaults.set(encoded, forKey: Keys.transcriptionHistory)
}
objectWillChange.send()
}
private func trimOldEntries() {
- if entries.count > maxEntries {
+ if self.entries.count > self.maxEntries {
// Keep most recent entries
- entries = Array(entries.prefix(maxEntries))
+ self.entries = Array(self.entries.prefix(self.maxEntries))
}
}
}
@@ -220,22 +220,22 @@ extension TranscriptionHistoryStore {
/// Total words across all transcriptions
var totalWords: Int {
- entries.reduce(0) { $0 + self.wordCount(in: $1.processedText) }
+ self.entries.reduce(0) { $0 + self.wordCount(in: $1.processedText) }
}
/// Words transcribed today
var wordsToday: Int {
let calendar = Calendar.current
let today = calendar.startOfDay(for: Date())
- return entries
+ return self.entries
.filter { calendar.isDate($0.timestamp, inSameDayAs: today) }
.reduce(0) { $0 + self.wordCount(in: $1.processedText) }
}
/// Average words per transcription
var averageWordsPerTranscription: Int {
- guard !entries.isEmpty else { return 0 }
- return totalWords / entries.count
+ guard !self.entries.isEmpty else { return 0 }
+ return self.totalWords / self.entries.count
}
// MARK: - Time Saved Calculation
@@ -256,7 +256,7 @@ extension TranscriptionHistoryStore {
/// Formatted time saved string (e.g., "2h 45m" or "45m")
func formattedTimeSaved(typingWPM: Int = 40) -> String {
- let minutes = timeSavedMinutes(typingWPM: typingWPM)
+ let minutes = self.timeSavedMinutes(typingWPM: typingWPM)
if minutes < 1 {
return "< 1m"
@@ -279,7 +279,7 @@ extension TranscriptionHistoryStore {
let calendar = Calendar.current
var uniqueDays = Set<Date>()
- for entry in entries {
+ for entry in self.entries {
let day = calendar.startOfDay(for: entry.timestamp)
uniqueDays.insert(day)
}
@@ -290,7 +290,7 @@ extension TranscriptionHistoryStore {
/// Current streak (consecutive days including today or yesterday)
var currentStreak: Int {
let calendar = Calendar.current
- let days = activeDays
+ let days = self.activeDays
guard !days.isEmpty else { return 0 }
@@ -328,7 +328,7 @@ extension TranscriptionHistoryStore {
/// Best streak ever achieved
var bestStreak: Int {
let calendar = Calendar.current
- let days = activeDays.sorted() // oldest first for this calculation
+ let days = self.activeDays.sorted() // oldest first for this calculation
guard !days.isEmpty else { return 0 }
@@ -365,7 +365,7 @@ extension TranscriptionHistoryStore {
for dayOffset in 0..<days {
guard let date = calendar.date(byAdding: .day, value: -dayOffset, to: today) else { continue }
- let dayEntries = entries.filter { calendar.isDate($0.timestamp, inSameDayAs: date) }
+ let dayEntries = self.entries.filter { calendar.isDate($0.timestamp, inSameDayAs: date) }
let words = dayEntries.reduce(0) { $0 + self.wordCount(in: $1.processedText) }
result.append((date: date, words: words))
@@ -384,7 +384,7 @@ extension TranscriptionHistoryStore {
for dayOffset in 0..<days {
guard let date = calendar.date(byAdding: .day, value: -dayOffset, to: today) else { continue }
- let count = entries.filter { calendar.isDate($0.timestamp, inSameDayAs: date) }.count
+ let count = self.entries.filter { calendar.isDate($0.timestamp, inSameDayAs: date) }.count
result.append((date: date, count: count))
}
@@ -397,7 +397,7 @@ extension TranscriptionHistoryStore {
var topApps: [(app: String, count: Int)] {
var appCounts: [String: Int] = [:]
- for entry in entries {
+ for entry in self.entries {
let app = entry.appName.isEmpty ? "Unknown" : entry.appName
appCounts[app, default: 0] += 1
}
@@ -409,27 +409,27 @@ extension TranscriptionHistoryStore {
/// Top N apps formatted for display
func topAppsFormatted(limit: Int = 5) -> [String] {
- topApps.prefix(limit).map { $0.app }
+ self.topApps.prefix(limit).map { $0.app }
}
// MARK: - AI Enhancement Rate
/// Percentage of transcriptions that were AI-enhanced (0-100)
var aiEnhancementRate: Int {
- guard !entries.isEmpty else { return 0 }
- return (aiProcessedCount * 100) / entries.count
+ guard !self.entries.isEmpty else { return 0 }
+ return (self.aiProcessedCount * 100) / self.entries.count
}
// MARK: - Peak Usage Hours
/// Hour of day with most transcriptions (0-23)
var peakHour: Int? {
- guard !entries.isEmpty else { return nil }
+ guard !self.entries.isEmpty else { return nil }
let calendar = Calendar.current
var hourCounts: [Int: Int] = [:]
- for entry in entries {
+ for entry in self.entries {
let hour = calendar.component(.hour, from: entry.timestamp)
hourCounts[hour, default: 0] += 1
}
@@ -464,7 +464,7 @@ extension TranscriptionHistoryStore {
/// Longest single transcription (word count)
var longestTranscriptionWords: Int {
- entries.map { self.wordCount(in: $0.processedText) }.max() ?? 0
+ self.entries.map { self.wordCount(in: $0.processedText) }.max() ?? 0
}
/// Most words in a single day
@@ -472,9 +472,9 @@ extension TranscriptionHistoryStore {
let calendar = Calendar.current
var dayTotals: [Date: Int] = [:]
- for entry in entries {
+ for entry in self.entries {
let day = calendar.startOfDay(for: entry.timestamp)
- dayTotals[day, default: 0] += wordCount(in: entry.processedText)
+ dayTotals[day, default: 0] += self.wordCount(in: entry.processedText)
}
return dayTotals.values.max() ?? 0
@@ -485,7 +485,7 @@ extension TranscriptionHistoryStore {
let calendar = Calendar.current
var dayCounts: [Date: Int] = [:]
- for entry in entries {
+ for entry in self.entries {
let day = calendar.startOfDay(for: entry.timestamp)
dayCounts[day, default: 0] += 1
}
@@ -506,7 +506,7 @@ extension TranscriptionHistoryStore {
(1_000_000, "1M"),
]
- let total = totalWords
+ let total = self.totalWords
return milestones.map { (target: $0.0, achieved: total >= $0.0, label: $0.1) }
}
@@ -521,7 +521,7 @@ extension TranscriptionHistoryStore {
(10_000, "10K"),
]
- let total = entries.count
+ let total = self.entries.count
return milestones.map { (target: $0.0, achieved: total >= $0.0, label: $0.1) }
}
@@ -536,19 +536,19 @@ extension TranscriptionHistoryStore {
(365, "1 year"),
]
- let best = bestStreak
+ let best = self.bestStreak
return milestones.map { (target: $0.0, achieved: best >= $0.0, label: $0.1) }
}
/// Total milestones achieved
var totalMilestonesAchieved: Int {
- wordMilestones.filter { $0.achieved }.count +
- transcriptionMilestones.filter { $0.achieved }.count +
- streakMilestones.filter { $0.achieved }.count
+ self.wordMilestones.filter { $0.achieved }.count +
+ self.transcriptionMilestones.filter { $0.achieved }.count +
+ self.streakMilestones.filter { $0.achieved }.count
}
/// Total possible milestones
var totalMilestonesPossible: Int {
- wordMilestones.count + transcriptionMilestones.count + streakMilestones.count
+ self.wordMilestones.count + self.transcriptionMilestones.count + self.streakMilestones.count
}
}
diff --git a/Sources/Fluid/Services/ASRService.swift b/Sources/Fluid/Services/ASRService.swift
index 58e5572c..0bef1693 100644
--- a/Sources/Fluid/Services/ASRService.swift
+++ b/Sources/Fluid/Services/ASRService.swift
@@ -16,12 +16,12 @@ private actor TranscriptionExecutor {
private var lastTask: Task<Void, Never>?
func run<T>(_ operation: @escaping () async throws -> T) async throws -> T {
- let previous = lastTask
+ let previous = self.lastTask
let task = Task<T, Error> {
_ = await previous?.result
return try await operation()
}
- lastTask = Task { _ = try? await task.value }
+ self.lastTask = Task { _ = try? await task.value }
return try await task.value
}
}
@@ -79,10 +79,10 @@ final class ASRService: ObservableObject {
/// Returns a user-friendly status message for model loading state
var modelStatusMessage: String {
- if isAsrReady { return "Model ready" }
- if isDownloadingModel { return "Downloading model..." }
- if isLoadingModel { return "Loading model into memory..." }
- if modelsExistOnDisk { return "Model cached, needs loading" }
+ if self.isAsrReady { return "Model ready" }
+ if self.isDownloadingModel { return "Downloading model..." }
+ if self.isLoadingModel { return "Loading model into memory..." }
+ if self.modelsExistOnDisk { return "Model cached, needs loading" }
return "Model not downloaded"
}
@@ -103,9 +103,9 @@ final class ASRService: ObservableObject {
let model = SettingsStore.shared.selectedSpeechModel
if model.isWhisperModel {
- return getWhisperProvider()
+ return self.getWhisperProvider()
} else {
- return getFluidAudioProvider()
+ return self.getFluidAudioProvider()
}
}
@@ -114,7 +114,7 @@ final class ASRService: ObservableObject {
return existing
}
let provider = FluidAudioProvider()
- fluidAudioProvider = provider
+ self.fluidAudioProvider = provider
DebugLogger.shared.info("ASRService: Created FluidAudio provider", source: "ASRService")
return provider
}
@@ -124,7 +124,7 @@ final class ASRService: ObservableObject {
return existing
}
let provider = WhisperProvider()
- whisperProvider = provider
+ self.whisperProvider = provider
DebugLogger.shared.info("ASRService: Created Whisper provider", source: "ASRService")
return provider
}
@@ -136,16 +136,16 @@ final class ASRService: ObservableObject {
/// Call this when the transcription provider setting changes to reset state
func resetTranscriptionProvider() {
- isAsrReady = false
- modelsExistOnDisk = false
- ensureReadyTask?.cancel()
- ensureReadyTask = nil
- ensureReadyProviderKey = nil
+ self.isAsrReady = false
+ self.modelsExistOnDisk = false
+ self.ensureReadyTask?.cancel()
+ self.ensureReadyTask = nil
+ self.ensureReadyProviderKey = nil
DebugLogger.shared.info("ASRService: Provider reset, will re-initialize on next use", source: "ASRService")
// CRITICAL FIX: Immediately check if the NEW model's files exist on disk
// This prevents UI from showing "Download" when model is already downloaded
- checkIfModelsExist()
+ self.checkIfModelsExist()
}
// CRITICAL FIX (launch-time crash mitigation):
@@ -165,7 +165,7 @@ final class ASRService: ObservableObject {
return existing
}
let created = AVAudioEngine()
- engineStorage = created
+ self.engineStorage = created
return created
}
@@ -176,7 +176,7 @@ final class ASRService: ObservableObject {
// Note: Only available when using FluidAudioProvider (Apple Silicon)
#if arch(arm64)
var asrManager: AsrManager? {
- (transcriptionProvider as? FluidAudioProvider)?.underlyingManager
+ (self.transcriptionProvider as? FluidAudioProvider)?.underlyingManager
}
#else
var asrManager: Any? { nil }
@@ -198,7 +198,7 @@ final class ASRService: ObservableObject {
private let transcriptionExecutor = TranscriptionExecutor() // Serializes all CoreML access
private var audioLevelSubject = PassthroughSubject<CGFloat, Never>()
- var audioLevelPublisher: AnyPublisher<CGFloat, Never> { audioLevelSubject.eraseToAnyPublisher() }
+ var audioLevelPublisher: AnyPublisher<CGFloat, Never> { self.audioLevelSubject.eraseToAnyPublisher() }
private var lastAudioLevelSentAt: TimeInterval = 0
// Audio smoothing properties - lighter smoothing for real-time response
@@ -226,16 +226,16 @@ final class ASRService: ObservableObject {
/// This must be called from onAppear or later, never during init.
func initialize() {
// Check microphone permission (deferred from init to avoid AVFCapture race condition)
- micStatus = AVCaptureDevice.authorizationStatus(for: .audio)
- micPermissionGranted = (micStatus == .authorized)
+ self.micStatus = AVCaptureDevice.authorizationStatus(for: .audio)
+ self.micPermissionGranted = (self.micStatus == .authorized)
- registerDefaultDeviceChangeListener()
+ self.registerDefaultDeviceChangeListener()
// Check if models exist on disk (deferred from init to avoid FluidAudio/CoreML race)
- checkIfModelsExist()
+ self.checkIfModelsExist()
// Auto-load models if they exist on disk to avoid "Downloaded but not loaded" state
- if modelsExistOnDisk {
+ if self.modelsExistOnDisk {
DebugLogger.shared.info("Models found on disk, auto-loading...", source: "ASRService")
Task { [weak self] in
guard let self = self else { return }
@@ -251,8 +251,8 @@ final class ASRService: ObservableObject {
/// Check if models exist on disk without loading them
func checkIfModelsExist() {
- modelsExistOnDisk = transcriptionProvider.modelsExistOnDisk()
- DebugLogger.shared.debug("Models exist on disk: \(modelsExistOnDisk)", source: "ASRService")
+ self.modelsExistOnDisk = self.transcriptionProvider.modelsExistOnDisk()
+ DebugLogger.shared.debug("Models exist on disk: \(self.modelsExistOnDisk)", source: "ASRService")
}
func requestMicAccess() {
@@ -292,24 +292,24 @@ final class ASRService: ObservableObject {
/// If audio session configuration fails, the method will silently fail
/// and `isRunning` will remain `false`. Check the debug logs for details.
func start() {
- guard micStatus == .authorized else { return }
- guard isRunning == false else { return }
-
- finalText.removeAll()
- audioBuffer.clear(keepingCapacity: true) // specific optimization for restart
- partialTranscription.removeAll()
- previousFullTranscription.removeAll()
- lastProcessedSampleCount = 0
- isProcessingChunk = false
- skipNextChunk = false
- isRecordingWholeSession = true
+ guard self.micStatus == .authorized else { return }
+ guard self.isRunning == false else { return }
+
+ self.finalText.removeAll()
+ self.audioBuffer.clear(keepingCapacity: true) // specific optimization for restart
+ self.partialTranscription.removeAll()
+ self.previousFullTranscription.removeAll()
+ self.lastProcessedSampleCount = 0
+ self.isProcessingChunk = false
+ self.skipNextChunk = false
+ self.isRecordingWholeSession = true
do {
- try configureSession()
- try startEngine()
- setupEngineTap()
- isRunning = true
- startStreamingTranscription()
+ try self.configureSession()
+ try self.startEngine()
+ self.setupEngineTap()
+ self.isRunning = true
+ self.startStreamingTranscription()
} catch {
// TODO: Add proper error handling and user notification
// For now, errors are logged but the UI doesn't show them
@@ -345,28 +345,28 @@ final class ASRService: ObservableObject {
/// - Transcription process fails
/// Check debug logs for detailed error information.
func stop() async -> String {
- guard isRunning else { return "" }
+ guard self.isRunning else { return "" }
DebugLogger.shared.debug("stop(): cancelling streaming and preparing final transcription", source: "ASRService")
- stopStreamingTimer()
- removeEngineTap()
- engine.stop()
- engine.reset() // Reset engine state to fully release Bluetooth mic
- isRunning = false
+ self.stopStreamingTimer()
+ self.removeEngineTap()
+ self.engine.stop()
+ self.engine.reset() // Reset engine state to fully release Bluetooth mic
+ self.isRunning = false
- isProcessingChunk = false
- skipNextChunk = false
- previousFullTranscription.removeAll()
+ self.isProcessingChunk = false
+ self.skipNextChunk = false
+ self.previousFullTranscription.removeAll()
// Thread-safe copy of recorded audio
- let pcm = audioBuffer.getAll()
- audioBuffer.clear()
- isRecordingWholeSession = false
+ let pcm = self.audioBuffer.getAll()
+ self.audioBuffer.clear()
+ self.isRecordingWholeSession = false
do {
- try await ensureAsrReady()
- guard transcriptionProvider.isReady else {
+ try await self.ensureAsrReady()
+ guard self.transcriptionProvider.isReady else {
DebugLogger.shared.error("Transcription provider is not ready", source: "ASRService")
return ""
}
@@ -378,7 +378,7 @@ final class ASRService: ObservableObject {
)
DebugLogger.shared
.debug(
- "stop(): starting full transcription (samples: \(pcm.count)) using \(transcriptionProvider.name)",
+ "stop(): starting full transcription (samples: \(pcm.count)) using \(self.transcriptionProvider.name)",
source: "ASRService"
)
let result = try await transcriptionExecutor.run { [provider = self.transcriptionProvider] in
@@ -410,54 +410,54 @@ final class ASRService: ObservableObject {
}
func stopWithoutTranscription() {
- guard isRunning else { return }
-
- stopStreamingTimer()
- removeEngineTap()
- engine.stop()
- engine.reset() // Reset engine state to fully release Bluetooth mic
- isRunning = false
- audioBuffer.clear()
- isRecordingWholeSession = false
- partialTranscription.removeAll()
- previousFullTranscription.removeAll()
- lastProcessedSampleCount = 0
- isProcessingChunk = false
- skipNextChunk = false
+ guard self.isRunning else { return }
+
+ self.stopStreamingTimer()
+ self.removeEngineTap()
+ self.engine.stop()
+ self.engine.reset() // Reset engine state to fully release Bluetooth mic
+ self.isRunning = false
+ self.audioBuffer.clear()
+ self.isRecordingWholeSession = false
+ self.partialTranscription.removeAll()
+ self.previousFullTranscription.removeAll()
+ self.lastProcessedSampleCount = 0
+ self.isProcessingChunk = false
+ self.skipNextChunk = false
}
private func configureSession() throws {
- if engine.isRunning {
- engine.stop()
+ if self.engine.isRunning {
+ self.engine.stop()
}
- engine.reset()
- _ = engine.inputNode
+ self.engine.reset()
+ _ = self.engine.inputNode
}
private func startEngine() throws {
- engine.reset()
+ self.engine.reset()
var attempts = 0
while attempts < 3 {
do {
- try engine.start()
+ try self.engine.start()
return
} catch {
attempts += 1
Thread.sleep(forTimeInterval: 0.1)
- engine.reset()
+ self.engine.reset()
}
}
throw NSError(domain: "ASRService", code: -1)
}
private func removeEngineTap() {
- engine.inputNode.removeTap(onBus: 0)
+ self.engine.inputNode.removeTap(onBus: 0)
}
private func setupEngineTap() {
- let input = engine.inputNode
+ let input = self.engine.inputNode
let inFormat = input.inputFormat(forBus: 0)
- inputFormat = inFormat
+ self.inputFormat = inFormat
input.installTap(onBus: 0, bufferSize: 4096, format: inFormat) { [weak self] buffer, _ in
self?.processInputBuffer(buffer: buffer)
}
@@ -465,13 +465,13 @@ final class ASRService: ObservableObject {
private func handleDefaultInputChanged() {
// Restart engine to bind to the new default input and resume level publishing
- if isRunning {
- removeEngineTap()
- engine.stop()
+ if self.isRunning {
+ self.removeEngineTap()
+ self.engine.stop()
do {
- try configureSession()
- try startEngine()
- setupEngineTap()
+ try self.configureSession()
+ try self.startEngine()
+ self.setupEngineTap()
} catch {}
}
// Nudge visualizer
@@ -480,7 +480,7 @@ final class ASRService: ObservableObject {
private var defaultInputListenerInstalled = false
private func registerDefaultDeviceChangeListener() {
- guard defaultInputListenerInstalled == false else { return }
+ guard self.defaultInputListenerInstalled == false else { return }
var address = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDefaultInputDevice,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -493,22 +493,22 @@ final class ASRService: ObservableObject {
) { [weak self] _, _ in
self?.handleDefaultInputChanged()
}
- if status == noErr { defaultInputListenerInstalled = true }
+ if status == noErr { self.defaultInputListenerInstalled = true }
}
private func processInputBuffer(buffer: AVAudioPCMBuffer) {
- guard isRecordingWholeSession else {
+ guard self.isRecordingWholeSession else {
DispatchQueue.main.async { self.audioLevelSubject.send(0.0) }
return
}
- let mono16k = toMono16k(floatBuffer: buffer)
+ let mono16k = self.toMono16k(floatBuffer: buffer)
if mono16k.isEmpty == false {
// Thread-safe append
- audioBuffer.append(mono16k)
+ self.audioBuffer.append(mono16k)
// Publish audio level for visualization
- let audioLevel = calculateAudioLevel(mono16k)
+ let audioLevel = self.calculateAudioLevel(mono16k)
DispatchQueue.main.async { self.audioLevelSubject.send(audioLevel) }
}
}
@@ -523,34 +523,34 @@ final class ASRService: ObservableObject {
// Apply noise gate at RMS level
if rms < 0.002 {
- return applySmoothingAndThreshold(0.0)
+ return self.applySmoothingAndThreshold(0.0)
}
// Convert to dB with better scaling
let dbLevel = 20 * log10(max(rms, 1e-10))
let normalizedLevel = max(0, min(1, (dbLevel + 55) / 55))
- return applySmoothingAndThreshold(CGFloat(normalizedLevel))
+ return self.applySmoothingAndThreshold(CGFloat(normalizedLevel))
}
private func applySmoothingAndThreshold(_ newLevel: CGFloat) -> CGFloat {
// Minimal smoothing for real-time response
- audioLevelHistory.append(newLevel)
- if audioLevelHistory.count > historySize {
- audioLevelHistory.removeFirst()
+ self.audioLevelHistory.append(newLevel)
+ if self.audioLevelHistory.count > self.historySize {
+ self.audioLevelHistory.removeFirst()
}
// Light smoothing - mostly use current value
- let average = audioLevelHistory.reduce(0, +) / CGFloat(audioLevelHistory.count)
+ let average = self.audioLevelHistory.reduce(0, +) / CGFloat(self.audioLevelHistory.count)
let smoothingFactor: CGFloat = 0.7 // Much more responsive
- smoothedLevel = (smoothingFactor * newLevel) + ((1 - smoothingFactor) * average)
+ self.smoothedLevel = (smoothingFactor * newLevel) + ((1 - smoothingFactor) * average)
// Simple threshold - just cut off below silence level
- if smoothedLevel < silenceThreshold {
+ if self.smoothedLevel < self.silenceThreshold {
return 0.0
}
- return smoothedLevel
+ return self.smoothedLevel
}
private func toMono16k(floatBuffer: AVAudioPCMBuffer) -> [Float] {
@@ -564,8 +564,8 @@ final class ASRService: ObservableObject {
let ptr = channelData[0]
return Array(UnsafeBufferPointer(start: ptr, count: frameCount))
}
- let mono = downmixToMono(floatBuffer)
- return resampleTo16k(mono, sourceSampleRate: floatBuffer.format.sampleRate)
+ let mono = self.downmixToMono(floatBuffer)
+ return self.resampleTo16k(mono, sourceSampleRate: floatBuffer.format.sampleRate)
}
private func downmixToMono(_ buffer: AVAudioPCMBuffer) -> [Float] {
@@ -624,7 +624,7 @@ final class ASRService: ObservableObject {
/// - Network connectivity issues
/// - Insufficient disk space
func ensureAsrReady() async throws {
- let provider = transcriptionProvider
+ let provider = self.transcriptionProvider
let providerKey = "\(type(of: provider)):\(provider.name)"
// Single-flight: if a prepare is already running for this provider, await it.
@@ -636,8 +636,8 @@ final class ASRService: ObservableObject {
let task = Task { @MainActor in
try await self.performEnsureAsrReady(provider: provider)
}
- ensureReadyTask = task
- ensureReadyProviderKey = providerKey
+ self.ensureReadyTask = task
+ self.ensureReadyProviderKey = providerKey
defer {
if ensureReadyProviderKey == providerKey {
@@ -651,7 +651,7 @@ final class ASRService: ObservableObject {
private func performEnsureAsrReady(provider: TranscriptionProvider) async throws {
// Check if already ready
- if isAsrReady, provider.isReady {
+ if self.isAsrReady, provider.isReady {
DebugLogger.shared.debug(
"ASR already ready with loaded models, skipping initialization",
source: "ASRService"
@@ -660,11 +660,11 @@ final class ASRService: ObservableObject {
}
// If the flag is set but provider isn't ready (e.g., provider switch without reset), re-init.
- if isAsrReady, !provider.isReady {
+ if self.isAsrReady, !provider.isReady {
DebugLogger.shared.debug("ASR marked ready but provider not ready; re-initializing", source: "ASRService")
}
- isAsrReady = false
+ self.isAsrReady = false
let totalStartTime = Date()
do {
@@ -733,7 +733,7 @@ final class ASRService: ObservableObject {
source: "ASRService"
)
- isAsrReady = true
+ self.isAsrReady = true
} catch {
DebugLogger.shared.error("ASR initialization failed with error: \(error)", source: "ASRService")
DebugLogger.shared.error("Error details: \(error.localizedDescription)", source: "ASRService")
@@ -767,7 +767,7 @@ final class ASRService: ObservableObject {
func preloadModelAfterSelection() async {
// ensureAsrReady handles setting the correct loading/downloading state
do {
- try await ensureAsrReady()
+ try await self.ensureAsrReady()
} catch {
DebugLogger.shared.error("Model preload failed: \(error)", source: "ASRService")
}
@@ -777,43 +777,43 @@ final class ASRService: ObservableObject {
func clearModelCache() async throws {
DebugLogger.shared.debug("Clearing model cache via transcription provider", source: "ASRService")
- try await transcriptionProvider.clearCache()
- isAsrReady = false
- modelsExistOnDisk = false
+ try await self.transcriptionProvider.clearCache()
+ self.isAsrReady = false
+ self.modelsExistOnDisk = false
}
// MARK: - Timer-based Streaming Transcription (No VAD)
private func startStreamingTranscription() {
- streamingTask?.cancel()
- guard isAsrReady else { return }
+ self.streamingTask?.cancel()
+ guard self.isAsrReady else { return }
DebugLogger.shared.debug(
- "Starting streaming transcription task (interval: \(chunkDurationSeconds)s)",
+ "Starting streaming transcription task (interval: \(self.chunkDurationSeconds)s)",
source: "ASRService"
)
- streamingTask = Task { [weak self] in
+ self.streamingTask = Task { [weak self] in
await self?.runStreamingLoop()
}
}
private func stopStreamingTimer() {
- streamingTask?.cancel()
- streamingTask = nil
+ self.streamingTask?.cancel()
+ self.streamingTask = nil
}
@MainActor
private func runStreamingLoop() async {
while !Task.isCancelled {
- await processStreamingChunk()
+ await self.processStreamingChunk()
- if Task.isCancelled || isRunning == false {
+ if Task.isCancelled || self.isRunning == false {
break
}
do {
- try await Task.sleep(nanoseconds: UInt64(chunkDurationSeconds * 1_000_000_000))
+ try await Task.sleep(nanoseconds: UInt64(self.chunkDurationSeconds * 1_000_000_000))
} catch {
DebugLogger.shared.debug("Streaming transcription task cancelled", source: "ASRService")
break
@@ -823,35 +823,35 @@ final class ASRService: ObservableObject {
@MainActor
private func processStreamingChunk() async {
- guard isRunning else { return }
+ guard self.isRunning else { return }
// Skip if already processing to prevent queue buildup
- guard !isProcessingChunk else {
+ guard !self.isProcessingChunk else {
DebugLogger.shared.debug(
"⚠️ Skipping chunk - previous transcription still in progress",
source: "ASRService"
)
- skipNextChunk = true
+ self.skipNextChunk = true
return
}
- if skipNextChunk {
+ if self.skipNextChunk {
DebugLogger.shared.debug("⚠️ Skipping chunk for ANE recovery", source: "ASRService")
- skipNextChunk = false
+ self.skipNextChunk = false
return
}
- guard isAsrReady, transcriptionProvider.isReady else { return }
+ guard self.isAsrReady, self.transcriptionProvider.isReady else { return }
// Thread-safe count check
- let currentSampleCount = audioBuffer.count
+ let currentSampleCount = self.audioBuffer.count
let minSamples = 8000 // 0.5 second minimum for faster initial feedback
guard currentSampleCount >= minSamples else { return }
// Thread-safe copy of the data
- let chunk = audioBuffer.getPrefix(currentSampleCount)
+ let chunk = self.audioBuffer.getPrefix(currentSampleCount)
- isProcessingChunk = true
+ self.isProcessingChunk = true
defer { isProcessingChunk = false }
let startTime = Date()
@@ -859,7 +859,7 @@ final class ASRService: ObservableObject {
do {
DebugLogger.shared
.debug(
- "Streaming chunk starting transcription (samples: \(chunk.count)) using \(transcriptionProvider.name)",
+ "Streaming chunk starting transcription (samples: \(chunk.count)) using \(self.transcriptionProvider.name)",
source: "ASRService"
)
let result = try await transcriptionExecutor.run { [provider = self.transcriptionProvider] in
@@ -876,9 +876,9 @@ final class ASRService: ObservableObject {
if !newText.isEmpty {
// Smart diff: only show truly new words
- let updatedText = smartDiffUpdate(previous: previousFullTranscription, current: newText)
- partialTranscription = updatedText
- previousFullTranscription = newText
+ let updatedText = self.smartDiffUpdate(previous: self.previousFullTranscription, current: newText)
+ self.partialTranscription = updatedText
+ self.previousFullTranscription = newText
DebugLogger.shared.debug(
"✅ Streaming: '\(updatedText)' (\(String(format: "%.2f", duration))s)",
@@ -888,17 +888,17 @@ final class ASRService: ObservableObject {
// If transcription takes longer than the interval, skip next to prevent queue buildup
// This allows slower machines to still work without overwhelming the system
- if duration > chunkDurationSeconds {
+ if duration > self.chunkDurationSeconds {
DebugLogger.shared
.debug(
- "⚠️ Transcription slow (\(String(format: "%.2f", duration))s > \(chunkDurationSeconds)s), skipping next chunk",
+ "⚠️ Transcription slow (\(String(format: "%.2f", duration))s > \(self.chunkDurationSeconds)s), skipping next chunk",
source: "ASRService"
)
- skipNextChunk = true
+ self.skipNextChunk = true
}
} catch {
DebugLogger.shared.error("❌ Streaming failed: \(error)", source: "ASRService")
- skipNextChunk = true
+ self.skipNextChunk = true
}
}
@@ -937,7 +937,7 @@ final class ASRService: ObservableObject {
private let typingService = TypingService() // Reuse instance to avoid conflicts
func typeTextToActiveField(_ text: String) {
- typingService.typeTextInstantly(text)
+ self.typingService.typeTextInstantly(text)
}
/// Removes filler sounds from transcribed text
diff --git a/Sources/Fluid/Services/AppServices.swift b/Sources/Fluid/Services/AppServices.swift
index 7ca7fa34..18d41409 100644
--- a/Sources/Fluid/Services/AppServices.swift
+++ b/Sources/Fluid/Services/AppServices.swift
@@ -28,12 +28,12 @@ final class AppServices: ObservableObject {
// instead of observing 'ASRService' directly (which causes metadata crashes),
// while still triggering UI updates when transcription or audio state changes.
- audioObserver.objectWillChange
+ self.audioObserver.objectWillChange
.sink { [weak self] _ in self?.objectWillChange.send() }
- .store(in: &cancellables)
+ .store(in: &self.cancellables)
- asr.objectWillChange
+ self.asr.objectWillChange
.sink { [weak self] _ in self?.objectWillChange.send() }
- .store(in: &cancellables)
+ .store(in: &self.cancellables)
}
}
diff --git a/Sources/Fluid/Services/AudioDeviceService.swift b/Sources/Fluid/Services/AudioDeviceService.swift
index aaf09760..21c706e1 100644
--- a/Sources/Fluid/Services/AudioDeviceService.swift
+++ b/Sources/Fluid/Services/AudioDeviceService.swift
@@ -50,18 +50,18 @@ enum AudioDevice {
devices.reserveCapacity(deviceIDs.count)
for devId in deviceIDs {
- let name = getStringProperty(
+ let name = self.getStringProperty(
devId,
selector: kAudioObjectPropertyName,
scope: kAudioObjectPropertyScopeGlobal
) ?? "Unknown"
- let uid = getStringProperty(
+ let uid = self.getStringProperty(
devId,
selector: kAudioDevicePropertyDeviceUID,
scope: kAudioObjectPropertyScopeGlobal
) ?? ""
- let hasIn = hasChannels(devId, scope: kAudioObjectPropertyScopeInput)
- let hasOut = hasChannels(devId, scope: kAudioObjectPropertyScopeOutput)
+ let hasIn = self.hasChannels(devId, scope: kAudioObjectPropertyScopeInput)
+ let hasOut = self.hasChannels(devId, scope: kAudioObjectPropertyScopeOutput)
devices.append(Device(id: devId, uid: uid, name: name, hasInput: hasIn, hasOutput: hasOut))
}
@@ -69,35 +69,35 @@ enum AudioDevice {
}
static func listInputDevices() -> [Device] {
- return listAllDevices().filter { $0.hasInput }
+ return self.listAllDevices().filter { $0.hasInput }
}
static func listOutputDevices() -> [Device] {
- return listAllDevices().filter { $0.hasOutput }
+ return self.listAllDevices().filter { $0.hasOutput }
}
static func getDefaultInputDevice() -> Device? {
guard let devId: AudioObjectID = getDefaultDeviceId(selector: kAudioHardwarePropertyDefaultInputDevice)
else { return nil }
- return listAllDevices().first { $0.id == devId }
+ return self.listAllDevices().first { $0.id == devId }
}
static func getDefaultOutputDevice() -> Device? {
guard let devId: AudioObjectID = getDefaultDeviceId(selector: kAudioHardwarePropertyDefaultOutputDevice)
else { return nil }
- return listAllDevices().first { $0.id == devId }
+ return self.listAllDevices().first { $0.id == devId }
}
@discardableResult
static func setDefaultInputDevice(uid: String) -> Bool {
guard let device = listInputDevices().first(where: { $0.uid == uid }) else { return false }
- return setDefaultDeviceId(device.id, selector: kAudioHardwarePropertyDefaultInputDevice)
+ return self.setDefaultDeviceId(device.id, selector: kAudioHardwarePropertyDefaultInputDevice)
}
@discardableResult
static func setDefaultOutputDevice(uid: String) -> Bool {
guard let device = listOutputDevices().first(where: { $0.uid == uid }) else { return false }
- return setDefaultDeviceId(device.id, selector: kAudioHardwarePropertyDefaultOutputDevice)
+ return self.setDefaultDeviceId(device.id, selector: kAudioHardwarePropertyDefaultOutputDevice)
}
private static func getDefaultDeviceId(selector: AudioObjectPropertySelector) -> AudioObjectID? {
@@ -218,7 +218,7 @@ final class AudioHardwareObserver: ObservableObject {
/// Call this AFTER the app has finished launching to start observing audio hardware changes.
/// This must be called from onAppear or later, never during init.
func startObserving() {
- register()
+ self.register()
}
deinit {
@@ -226,7 +226,7 @@ final class AudioHardwareObserver: ObservableObject {
}
private func register() {
- guard installed == false else { return }
+ guard self.installed == false else { return }
var addrDevices = AudioObjectPropertyAddress(
mSelector: kAudioHardwarePropertyDevices,
mScope: kAudioObjectPropertyScopeGlobal,
@@ -256,12 +256,12 @@ final class AudioHardwareObserver: ObservableObject {
self?.changeTick &+= 1
}
- installed = true
+ self.installed = true
}
private func unregister() {
- guard installed else { return }
+ guard self.installed else { return }
// Intentionally omitted: removing blocks is optional; listeners end with object lifetime.
- installed = false
+ self.installed = false
}
}
diff --git a/Sources/Fluid/Services/AudioStartupGate.swift b/Sources/Fluid/Services/AudioStartupGate.swift
index 29df8f2f..3b86f1eb 100644
--- a/Sources/Fluid/Services/AudioStartupGate.swift
+++ b/Sources/Fluid/Services/AudioStartupGate.swift
@@ -16,9 +16,9 @@ actor AudioStartupGate {
/// Schedule opening the gate once. Safe to call multiple times.
func scheduleOpenAfterInitialUISettled(delayNanoseconds: UInt64 = 2_000_000_000) {
- guard isOpen == false, openTask == nil else { return }
+ guard self.isOpen == false, self.openTask == nil else { return }
- openTask = Task { @MainActor [weak self] in
+ self.openTask = Task { @MainActor [weak self] in
guard let self else { return }
// Give SwiftUI a couple runloop turns to finish initial layout/metadata passes.
@@ -34,7 +34,7 @@ actor AudioStartupGate {
/// Await until the gate is open. Returns immediately if already open.
func waitUntilOpen() async {
- if isOpen { return }
+ if self.isOpen { return }
await withCheckedContinuation { cont in
self.waiters.append(cont)
@@ -42,11 +42,11 @@ actor AudioStartupGate {
}
private func open() {
- guard isOpen == false else { return }
- isOpen = true
+ guard self.isOpen == false else { return }
+ self.isOpen = true
- let pending = waiters
- waiters.removeAll(keepingCapacity: false)
+ let pending = self.waiters
+ self.waiters.removeAll(keepingCapacity: false)
pending.forEach { $0.resume() }
}
}
diff --git a/Sources/Fluid/Services/CommandModeService.swift b/Sources/Fluid/Services/CommandModeService.swift
index aea6ed59..6bc422e0 100644
--- a/Sources/Fluid/Services/CommandModeService.swift
+++ b/Sources/Fluid/Services/CommandModeService.swift
@@ -26,19 +26,19 @@ final class CommandModeService: ObservableObject {
init() {
// Load current chat from store
- loadCurrentChatFromStore()
+ self.loadCurrentChatFromStore()
}
private func loadCurrentChatFromStore() {
if let session = chatStore.currentSession {
- currentChatID = session.id
- conversationHistory = session.messages.map { self.chatMessageToMessage($0) }
- syncToNotchState()
+ self.currentChatID = session.id
+ self.conversationHistory = session.messages.map { self.chatMessageToMessage($0) }
+ self.syncToNotchState()
} else {
// Create new chat if none exists
- let newSession = chatStore.createNewChat()
- currentChatID = newSession.id
- conversationHistory = []
+ let newSession = self.chatStore.createNewChat()
+ self.currentChatID = newSession.id
+ self.conversationHistory = []
}
}
@@ -90,7 +90,7 @@ final class CommandModeService: ObservableObject {
self.content = content
self.toolCall = toolCall
self.stepType = stepType
- timestamp = Date()
+ self.timestamp = Date()
}
}
@@ -104,12 +104,12 @@ final class CommandModeService: ObservableObject {
// MARK: - Public Methods
func clearHistory() {
- conversationHistory.removeAll()
- pendingCommand = nil
- currentTurnCount = 0
+ self.conversationHistory.removeAll()
+ self.pendingCommand = nil
+ self.currentTurnCount = 0
// Clear in store as well
- chatStore.clearCurrentChat()
+ self.chatStore.clearCurrentChat()
// Also clear notch state
NotchContentState.shared.clearCommandOutput()
@@ -119,24 +119,24 @@ final class CommandModeService: ObservableObject {
/// Get recent chats for dropdown
func getRecentChats() -> [ChatSession] {
- return chatStore.getRecentChats(excludingCurrent: false)
+ return self.chatStore.getRecentChats(excludingCurrent: false)
}
/// Create a new chat and switch to it
func createNewChat() {
// Can't switch while processing
- guard !isProcessing else { return }
+ guard !self.isProcessing else { return }
// Save current chat first
- saveCurrentChat()
+ self.saveCurrentChat()
// Create new
- let newSession = chatStore.createNewChat()
- currentChatID = newSession.id
- conversationHistory = []
- pendingCommand = nil
- currentTurnCount = 0
- currentStep = nil
+ let newSession = self.chatStore.createNewChat()
+ self.currentChatID = newSession.id
+ self.conversationHistory = []
+ self.pendingCommand = nil
+ self.currentTurnCount = 0
+ self.currentStep = nil
// Clear notch state
NotchContentState.shared.clearCommandOutput()
@@ -148,25 +148,25 @@ final class CommandModeService: ObservableObject {
@discardableResult
func switchToChat(id: String) -> Bool {
// Can't switch while processing
- guard !isProcessing else { return false }
+ guard !self.isProcessing else { return false }
// Don't switch to current
- guard id != currentChatID else { return true }
+ guard id != self.currentChatID else { return true }
// Save current chat first
- saveCurrentChat()
+ self.saveCurrentChat()
// Load the target chat
guard let session = chatStore.switchToChat(id: id) else { return false }
- currentChatID = session.id
- conversationHistory = session.messages.map { self.chatMessageToMessage($0) }
- pendingCommand = nil
- currentTurnCount = 0
- currentStep = nil
+ self.currentChatID = session.id
+ self.conversationHistory = session.messages.map { self.chatMessageToMessage($0) }
+ self.pendingCommand = nil
+ self.currentTurnCount = 0
+ self.currentStep = nil
// Sync to notch state
- syncToNotchState()
+ self.syncToNotchState()
NotchContentState.shared.refreshRecentChats()
return true
@@ -175,21 +175,21 @@ final class CommandModeService: ObservableObject {
/// Delete current chat and switch to next
func deleteCurrentChat() {
// Can't delete while processing
- guard !isProcessing else { return }
+ guard !self.isProcessing else { return }
- chatStore.deleteCurrentChat()
+ self.chatStore.deleteCurrentChat()
// Load the new current chat
- loadCurrentChatFromStore()
+ self.loadCurrentChatFromStore()
NotchContentState.shared.refreshRecentChats()
}
/// Save current conversation to store
func saveCurrentChat() {
- guard currentChatID != nil else { return }
+ guard self.currentChatID != nil else { return }
- let messages = conversationHistory.map { self.messageToChatMessage($0) }
- chatStore.updateCurrentChat(messages: messages)
+ let messages = self.conversationHistory.map { self.messageToChatMessage($0) }
+ self.chatStore.updateCurrentChat(messages: messages)
}
// MARK: - Conversion Helpers
@@ -274,7 +274,7 @@ final class CommandModeService: ObservableObject {
private func syncToNotchState() {
NotchContentState.shared.clearCommandOutput()
- for msg in conversationHistory {
+ for msg in self.conversationHistory {
let role: NotchContentState.CommandOutputMessage.Role
switch msg.role {
case .user: role = .user
@@ -293,20 +293,20 @@ final class CommandModeService: ObservableObject {
func processUserCommand(_ text: String) async {
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
- isProcessing = true
- currentTurnCount = 0
- conversationHistory.append(Message(role: .user, content: text))
+ self.isProcessing = true
+ self.currentTurnCount = 0
+ self.conversationHistory.append(Message(role: .user, content: text))
// Auto-save after adding user message
- saveCurrentChat()
+ self.saveCurrentChat()
// Push to notch
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .user, content: text)
NotchContentState.shared.setCommandProcessing(true)
}
- await processNextTurn()
+ await self.processNextTurn()
}
/// Process follow-up command from notch input
@@ -314,69 +314,69 @@ final class CommandModeService: ObservableObject {
guard !text.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
// Add to both histories
- conversationHistory.append(Message(role: .user, content: text))
+ self.conversationHistory.append(Message(role: .user, content: text))
NotchContentState.shared.addCommandMessage(role: .user, content: text)
// Auto-save after adding user message
- saveCurrentChat()
+ self.saveCurrentChat()
- isProcessing = true
+ self.isProcessing = true
NotchContentState.shared.setCommandProcessing(true)
- await processNextTurn()
+ await self.processNextTurn()
}
/// Execute pending command (after user confirmation)
func confirmAndExecute() async {
guard let pending = pendingCommand else { return }
- pendingCommand = nil
- isProcessing = true
+ self.pendingCommand = nil
+ self.isProcessing = true
- await executeCommand(pending.command, workingDirectory: pending.workingDirectory, callId: pending.id)
+ await self.executeCommand(pending.command, workingDirectory: pending.workingDirectory, callId: pending.id)
}
/// Cancel pending command
func cancelPendingCommand() {
- pendingCommand = nil
- conversationHistory.append(Message(
+ self.pendingCommand = nil
+ self.conversationHistory.append(Message(
role: .assistant,
content: "Command cancelled.",
stepType: .failure
))
- isProcessing = false
- currentStep = nil
+ self.isProcessing = false
+ self.currentStep = nil
}
// MARK: - Agent Loop
private func processNextTurn() async {
- if currentTurnCount >= maxTurns {
+ if self.currentTurnCount >= self.maxTurns {
let errorMsg = "Reached maximum steps limit. Please review the progress and continue if needed."
- conversationHistory.append(Message(
+ self.conversationHistory.append(Message(
role: .assistant,
content: errorMsg,
stepType: .failure
))
- isProcessing = false
- currentStep = .completed(false)
+ self.isProcessing = false
+ self.currentStep = .completed(false)
// Auto-save on completion
- saveCurrentChat()
+ self.saveCurrentChat()
// Push to notch
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .assistant, content: errorMsg)
NotchContentState.shared.setCommandProcessing(false)
- showExpandedNotchIfNeeded()
+ self.showExpandedNotchIfNeeded()
}
return
}
- currentTurnCount += 1
- currentStep = .thinking("Analyzing...")
+ self.currentTurnCount += 1
+ self.currentStep = .thinking("Analyzing...")
// Push status to notch
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .status, content: "Thinking...")
}
@@ -385,13 +385,13 @@ final class CommandModeService: ObservableObject {
if let tc = response.toolCall {
// Determine step type based on command purpose
- let stepType = determineStepType(for: tc.command, purpose: tc.purpose)
- currentStep = stepType == .checking ? .checking(tc.command) : .executing(tc.command)
+ 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
- conversationHistory.append(Message(
+ self.conversationHistory.append(Message(
role: .assistant,
- content: response.content.isEmpty ? stepDescription(for: stepType) : response.content,
+ content: response.content.isEmpty ? self.stepDescription(for: stepType) : response.content,
toolCall: Message.ToolCall(
id: tc.id,
command: tc.command,
@@ -403,24 +403,24 @@ final class CommandModeService: ObservableObject {
))
// Push step to notch
- if enableNotchOutput {
- let statusText = tc.purpose ?? stepDescription(for: stepType)
+ if self.enableNotchOutput {
+ let statusText = tc.purpose ?? self.stepDescription(for: stepType)
NotchContentState.shared.addCommandMessage(role: .status, content: statusText)
}
// Check if we need confirmation for destructive commands
- if SettingsStore.shared.commandModeConfirmBeforeExecute, isDestructiveCommand(tc.command) {
- pendingCommand = PendingCommand(
+ if SettingsStore.shared.commandModeConfirmBeforeExecute, self.isDestructiveCommand(tc.command) {
+ self.pendingCommand = PendingCommand(
id: tc.id,
command: tc.command,
workingDirectory: tc.workingDirectory,
purpose: tc.purpose
)
- isProcessing = false
- currentStep = nil
+ self.isProcessing = false
+ self.currentStep = nil
// Push confirmation needed to notch
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.addCommandMessage(
role: .status,
content: "⚠️ Confirmation needed in Command Mode window"
@@ -431,7 +431,7 @@ final class CommandModeService: ObservableObject {
}
// Auto-execute
- await executeCommand(
+ await self.executeCommand(
tc.command,
workingDirectory: tc.workingDirectory,
callId: tc.id,
@@ -445,51 +445,51 @@ final class CommandModeService: ObservableObject {
response.content.lowercased().contains("success") ||
response.content.lowercased().contains("finished")
- conversationHistory.append(Message(
+ self.conversationHistory.append(Message(
role: .assistant,
content: response.content,
stepType: isFinal ? .success : .normal
))
- isProcessing = false
- currentStep = .completed(isFinal)
+ self.isProcessing = false
+ self.currentStep = .completed(isFinal)
// Auto-save on completion
- saveCurrentChat()
+ self.saveCurrentChat()
// Push final response to notch and show expanded view
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.updateCommandStreamingText("") // Clear streaming
NotchContentState.shared.addCommandMessage(role: .assistant, content: response.content)
NotchContentState.shared.setCommandProcessing(false)
- showExpandedNotchIfNeeded()
+ self.showExpandedNotchIfNeeded()
}
}
} catch {
let errorMsg = "Error: \(error.localizedDescription)"
- conversationHistory.append(Message(
+ self.conversationHistory.append(Message(
role: .assistant,
content: errorMsg,
stepType: .failure
))
- isProcessing = false
- currentStep = .completed(false)
+ self.isProcessing = false
+ self.currentStep = .completed(false)
// Auto-save on error
- saveCurrentChat()
+ self.saveCurrentChat()
// Push error to notch
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.addCommandMessage(role: .assistant, content: errorMsg)
NotchContentState.shared.setCommandProcessing(false)
- showExpandedNotchIfNeeded()
+ self.showExpandedNotchIfNeeded()
}
}
}
/// Show expanded notch output if there's content to display
private func showExpandedNotchIfNeeded() {
- guard enableNotchOutput else { return }
+ guard self.enableNotchOutput else { return }
guard !NotchContentState.shared.commandConversationHistory.isEmpty else { return }
// Show the expanded notch
@@ -576,7 +576,7 @@ final class CommandModeService: ObservableObject {
callId: String,
purpose: String? = nil
) async {
- currentStep = .executing(command)
+ self.currentStep = .executing(command)
let result = await terminalService.execute(
command: command,
@@ -595,14 +595,14 @@ final class CommandModeService: ObservableObject {
let resultStepType: Message.StepType = result.success ? .success : .failure
// Add tool result to conversation
- conversationHistory.append(Message(
+ self.conversationHistory.append(Message(
role: .tool,
content: resultJSON,
stepType: resultStepType
))
// Continue the loop - let the AI see the result and decide what to do next
- await processNextTurn()
+ await self.processNextTurn()
}
// MARK: - Enhanced Result
@@ -617,12 +617,12 @@ final class CommandModeService: ObservableObject {
let purpose: String?
init(result: TerminalService.CommandResult, purpose: String?) {
- success = result.success
- command = result.command
- output = result.output
- error = result.error
- exitCode = result.exitCode
- executionTimeMs = result.executionTimeMs
+ self.success = result.success
+ self.command = result.command
+ self.output = result.output
+ self.error = result.error
+ self.exitCode = result.exitCode
+ self.executionTimeMs = result.executionTimeMs
self.purpose = purpose
}
@@ -635,7 +635,7 @@ final class CommandModeService: ObservableObject {
return json
}
return """
- {"success": \(success), "output": "\(output)", "exitCode": \(exitCode)}
+ {"success": \(self.success), "output": "\(self.output)", "exitCode": \(self.exitCode)}
"""
}
}
@@ -759,7 +759,7 @@ final class CommandModeService: ObservableObject {
// Add conversation history
var lastToolCallId: String? = nil
- for msg in conversationHistory {
+ for msg in self.conversationHistory {
switch msg.role {
case .user:
messages.append(["role": "user", "content": msg.content])
@@ -842,9 +842,9 @@ final class CommandModeService: ObservableObject {
for attempt in 1...3 {
do {
if enableStreaming {
- return try await processStreamingLLMResponse(request: request)
+ return try await self.processStreamingLLMResponse(request: request)
} else {
- return try await processNonStreamingLLMResponse(request: request)
+ return try await self.processNonStreamingLLMResponse(request: request)
}
} catch let error as URLError where error.code == .notConnectedToInternet ||
error.code == .timedOut ||
@@ -887,15 +887,15 @@ final class CommandModeService: ObservableObject {
throw NSError(domain: "CommandMode", code: -1, userInfo: [NSLocalizedDescriptionKey: "Invalid response"])
}
- return parseMessageResponse(message)
+ return self.parseMessageResponse(message)
}
// MARK: - Streaming Response with Real-time UI Updates
private func processStreamingLLMResponse(request: URLRequest) async throws -> LLMResponse {
- streamingText = ""
- streamingBuffer = []
- lastUIUpdate = CFAbsoluteTimeGetCurrent()
+ self.streamingText = ""
+ self.streamingBuffer = []
+ self.lastUIUpdate = CFAbsoluteTimeGetCurrent()
let (bytes, response) = try await URLSession.shared.bytes(for: request)
@@ -938,10 +938,10 @@ final class CommandModeService: ObservableObject {
// Handle text content - use buffer to avoid O(n²) string concat
if let content = delta["content"] as? String {
- streamingBuffer.append(content)
+ self.streamingBuffer.append(content)
// Adaptive throttle: slower updates as content grows (reduces SwiftUI layout overhead)
- let bufferLength = streamingBuffer.count
+ let bufferLength = self.streamingBuffer.count
let updateInterval: CFAbsoluteTime
if bufferLength < 50 {
updateInterval = 0.016 // 60fps for first ~50 tokens
@@ -952,13 +952,13 @@ final class CommandModeService: ObservableObject {
}
let now = CFAbsoluteTimeGetCurrent()
- if now - lastUIUpdate >= updateInterval {
- lastUIUpdate = now
- let fullContent = streamingBuffer.joined()
- streamingText = fullContent
+ if now - self.lastUIUpdate >= updateInterval {
+ self.lastUIUpdate = now
+ let fullContent = self.streamingBuffer.joined()
+ self.streamingText = fullContent
// Push to notch for real-time display
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.updateCommandStreamingText(fullContent)
}
}
@@ -984,10 +984,10 @@ final class CommandModeService: ObservableObject {
}
// Final update - join buffer once at the end
- let fullContent = streamingBuffer.joined()
+ let fullContent = self.streamingBuffer.joined()
if !fullContent.isEmpty {
- streamingText = fullContent
- if enableNotchOutput {
+ self.streamingText = fullContent
+ if self.enableNotchOutput {
NotchContentState.shared.updateCommandStreamingText(fullContent)
}
}
@@ -995,11 +995,11 @@ final class CommandModeService: ObservableObject {
// Small delay to let the final content render, then clear
try? await Task.sleep(nanoseconds: 50_000_000) // 50ms
- streamingText = "" // Clear streaming text when done
- streamingBuffer = [] // Clear buffer
+ self.streamingText = "" // Clear streaming text when done
+ self.streamingBuffer = [] // Clear buffer
// Clear notch streaming text as well
- if enableNotchOutput {
+ if self.enableNotchOutput {
NotchContentState.shared.updateCommandStreamingText("")
}
diff --git a/Sources/Fluid/Services/DebugLogger.swift b/Sources/Fluid/Services/DebugLogger.swift
index e7c063a9..9079cae3 100644
--- a/Sources/Fluid/Services/DebugLogger.swift
+++ b/Sources/Fluid/Services/DebugLogger.swift
@@ -20,7 +20,7 @@ class DebugLogger: ObservableObject {
// Delay access to SettingsStore until after initial singleton setup
// Use UserDefaults directly to avoid the circular dependency
let enabled = UserDefaults.standard.bool(forKey: "EnableDebugLogs")
- _loggingEnabledCache = enabled
+ self._loggingEnabledCache = enabled
return enabled
}
@@ -69,13 +69,13 @@ class DebugLogger: ObservableObject {
/// Refresh the cached logging setting (call after SettingsStore is fully initialized)
func refreshLoggingEnabled() {
- _loggingEnabledCache = UserDefaults.standard.bool(forKey: "EnableDebugLogs")
+ self._loggingEnabledCache = UserDefaults.standard.bool(forKey: "EnableDebugLogs")
}
func log(_ message: String, level: LogLevel = .info, source: String = "App") {
let loggingEnabled = self.loggingEnabled
- queue.async {
+ self.queue.async {
let timestamp = Date()
let timestampString = Self.logFormatter.string(from: timestamp)
let entry: LogEntry? = loggingEnabled
@@ -120,13 +120,13 @@ class DebugLogger: ObservableObject {
}
func exportLogs() -> String {
- return logs.map { entry in
+ return self.logs.map { entry in
self.formatLogEntry(entry)
}.joined(separator: "\n")
}
private func formatLogEntry(_ entry: LogEntry) -> String {
- formatLogLine(
+ self.formatLogLine(
timestamp: entry.formattedTimestamp,
level: entry.level,
source: entry.source,
@@ -142,18 +142,18 @@ class DebugLogger: ObservableObject {
// Convenience functions for easier logging
extension DebugLogger {
func info(_ message: String, source: String = "App") {
- log(message, level: .info, source: source)
+ self.log(message, level: .info, source: source)
}
func warning(_ message: String, source: String = "App") {
- log(message, level: .warning, source: source)
+ self.log(message, level: .warning, source: source)
}
func error(_ message: String, source: String = "App") {
- log(message, level: .error, source: source)
+ self.log(message, level: .error, source: source)
}
func debug(_ message: String, source: String = "App") {
- log(message, level: .debug, source: source)
+ self.log(message, level: .debug, source: source)
}
}
diff --git a/Sources/Fluid/Services/FileLogger.swift b/Sources/Fluid/Services/FileLogger.swift
index 03e8fb0e..4dff7728 100644
--- a/Sources/Fluid/Services/FileLogger.swift
+++ b/Sources/Fluid/Services/FileLogger.swift
@@ -13,20 +13,20 @@ final class FileLogger {
private let maxLogFileAge: TimeInterval = 72 * 60 * 60 // Rotate every 72 hours
private init() {
- let baseDirectory = fileManager.urls(for: .libraryDirectory, in: .userDomainMask)
+ let baseDirectory = self.fileManager.urls(for: .libraryDirectory, in: .userDomainMask)
.first ?? URL(fileURLWithPath: NSTemporaryDirectory())
- logDirectory = baseDirectory.appendingPathComponent("Logs/Fluid", isDirectory: true)
- logFileURL = logDirectory.appendingPathComponent("fluid.log", isDirectory: false)
- backupLogURL = logDirectory.appendingPathComponent("fluid.log.1", isDirectory: false)
+ self.logDirectory = baseDirectory.appendingPathComponent("Logs/Fluid", isDirectory: true)
+ self.logFileURL = self.logDirectory.appendingPathComponent("fluid.log", isDirectory: false)
+ self.backupLogURL = self.logDirectory.appendingPathComponent("fluid.log.1", isDirectory: false)
- queue.sync {
+ self.queue.sync {
self.createLogDirectoryIfNeeded()
self.rotateIfNeeded(force: false)
}
}
func append(line: String) {
- queue.async { [weak self] in
+ self.queue.async { [weak self] in
guard let self = self else { return }
self.createLogDirectoryIfNeeded()
self.rotateIfNeeded(force: false)
@@ -46,43 +46,43 @@ final class FileLogger {
}
func currentLogFileURL() -> URL {
- return logFileURL
+ return self.logFileURL
}
// MARK: - Private helpers
private func createLogDirectoryIfNeeded() {
- guard !fileManager.fileExists(atPath: logDirectory.path) else { return }
+ guard !self.fileManager.fileExists(atPath: self.logDirectory.path) else { return }
do {
- try fileManager.createDirectory(at: logDirectory, withIntermediateDirectories: true)
+ try self.fileManager.createDirectory(at: self.logDirectory, withIntermediateDirectories: true)
} catch {
// If the directory cannot be created, fall back to /tmp
}
}
private func rotateIfNeeded(force: Bool) {
- guard fileManager.fileExists(atPath: logFileURL.path) else { return }
+ guard self.fileManager.fileExists(atPath: self.logFileURL.path) else { return }
let shouldRotate: Bool
if force {
shouldRotate = true
} else {
- let attributes = try? fileManager.attributesOfItem(atPath: logFileURL.path)
+ let attributes = try? self.fileManager.attributesOfItem(atPath: self.logFileURL.path)
let size = attributes?[.size] as? UInt64 ?? 0
let modifiedDate = attributes?[.modificationDate] as? Date ?? Date()
- let ageExceedsLimit = Date().timeIntervalSince(modifiedDate) >= maxLogFileAge
- shouldRotate = size >= maxLogFileSize || ageExceedsLimit
+ let ageExceedsLimit = Date().timeIntervalSince(modifiedDate) >= self.maxLogFileAge
+ shouldRotate = size >= self.maxLogFileSize || ageExceedsLimit
}
guard shouldRotate else { return }
// Remove existing backup if present
- if fileManager.fileExists(atPath: backupLogURL.path) {
- try? fileManager.removeItem(at: backupLogURL)
+ if self.fileManager.fileExists(atPath: self.backupLogURL.path) {
+ try? self.fileManager.removeItem(at: self.backupLogURL)
}
// Move current log to backup and create a fresh file
- try? fileManager.moveItem(at: logFileURL, to: backupLogURL)
- fileManager.createFile(atPath: logFileURL.path, contents: nil)
+ try? self.fileManager.moveItem(at: self.logFileURL, to: self.backupLogURL)
+ self.fileManager.createFile(atPath: self.logFileURL.path, contents: nil)
}
}
diff --git a/Sources/Fluid/Services/FluidAudioProvider.swift b/Sources/Fluid/Services/FluidAudioProvider.swift
index 112f64b8..7bd8c9ce 100644
--- a/Sources/Fluid/Services/FluidAudioProvider.swift
+++ b/Sources/Fluid/Services/FluidAudioProvider.swift
@@ -17,7 +17,7 @@ final class FluidAudioProvider: TranscriptionProvider {
private(set) var isReady: Bool = false
func prepare(progressHandler: ((Double) -> Void)? = nil) async throws {
- guard isReady == false else { return }
+ guard self.isReady == false else { return }
DebugLogger.shared.info("FluidAudioProvider: Starting model preparation", source: "FluidAudioProvider")
@@ -27,9 +27,9 @@ final class FluidAudioProvider: TranscriptionProvider {
// Initialize AsrManager
let manager = AsrManager(config: ASRConfig.default)
try await manager.initialize(models: models)
- asrManager = manager
+ self.asrManager = manager
- isReady = true
+ self.isReady = true
DebugLogger.shared.info("FluidAudioProvider: Models ready", source: "FluidAudioProvider")
}
@@ -67,14 +67,14 @@ final class FluidAudioProvider: TranscriptionProvider {
try FileManager.default.removeItem(at: v3CacheDir)
}
- isReady = false
- asrManager = nil
+ self.isReady = false
+ self.asrManager = nil
}
/// Provides direct access to the underlying AsrManager for advanced use cases
/// (e.g., MeetingTranscriptionService sharing)
var underlyingManager: AsrManager? {
- return asrManager
+ return self.asrManager
}
}
#else
diff --git a/Sources/Fluid/Services/GlobalHotkeyManager.swift b/Sources/Fluid/Services/GlobalHotkeyManager.swift
index 1391cf60..68dbf6dc 100644
--- a/Sources/Fluid/Services/GlobalHotkeyManager.swift
+++ b/Sources/Fluid/Services/GlobalHotkeyManager.swift
@@ -55,13 +55,13 @@ final class GlobalHotkeyManager: NSObject {
self.rewriteModeCallback = rewriteModeCallback
super.init()
- initializeWithDelay()
+ self.initializeWithDelay()
}
private func initializeWithDelay() {
DebugLogger.shared.debug("Starting delayed initialization...", source: "GlobalHotkeyManager")
- initializationTask = Task {
+ self.initializationTask = Task {
try? await Task.sleep(nanoseconds: 1_500_000_000) // 1.5 second delay
await MainActor.run {
@@ -71,36 +71,36 @@ final class GlobalHotkeyManager: NSObject {
}
func setStopAndProcessCallback(_ callback: @escaping () async -> Void) {
- stopAndProcessCallback = callback
+ self.stopAndProcessCallback = callback
}
func setCommandModeCallback(_ callback: @escaping () async -> Void) {
- commandModeCallback = callback
+ self.commandModeCallback = callback
}
func updateShortcut(_ newShortcut: HotkeyShortcut) {
- shortcut = newShortcut
+ self.shortcut = newShortcut
DebugLogger.shared.info("Updated transcription hotkey", source: "GlobalHotkeyManager")
}
func updateCommandModeShortcut(_ newShortcut: HotkeyShortcut) {
- commandModeShortcut = newShortcut
+ self.commandModeShortcut = newShortcut
DebugLogger.shared.info("Updated command mode hotkey", source: "GlobalHotkeyManager")
}
func setRewriteModeCallback(_ callback: @escaping () async -> Void) {
- rewriteModeCallback = callback
+ self.rewriteModeCallback = callback
}
func updateRewriteModeShortcut(_ newShortcut: HotkeyShortcut) {
- rewriteModeShortcut = newShortcut
+ self.rewriteModeShortcut = newShortcut
DebugLogger.shared.info("Updated rewrite mode hotkey", source: "GlobalHotkeyManager")
}
func updateCommandModeShortcutEnabled(_ enabled: Bool) {
- commandModeShortcutEnabled = enabled
+ self.commandModeShortcutEnabled = enabled
if !enabled {
- isCommandModeKeyPressed = false
+ self.isCommandModeKeyPressed = false
}
DebugLogger.shared.info(
"Command mode shortcut \(enabled ? "enabled" : "disabled")",
@@ -109,9 +109,9 @@ final class GlobalHotkeyManager: NSObject {
}
func updateRewriteModeShortcutEnabled(_ enabled: Bool) {
- rewriteModeShortcutEnabled = enabled
+ self.rewriteModeShortcutEnabled = enabled
if !enabled {
- isRewriteKeyPressed = false
+ self.isRewriteKeyPressed = false
}
DebugLogger.shared.info(
"Rewrite mode shortcut \(enabled ? "enabled" : "disabled")",
@@ -120,23 +120,23 @@ final class GlobalHotkeyManager: NSObject {
}
func setCancelCallback(_ callback: @escaping () -> Bool) {
- cancelCallback = callback
+ self.cancelCallback = callback
}
private func setupGlobalHotkeyWithRetry() {
- for attempt in 1...maxRetryAttempts {
- DebugLogger.shared.debug("Setup attempt \(attempt)/\(maxRetryAttempts)", source: "GlobalHotkeyManager")
+ for attempt in 1...self.maxRetryAttempts {
+ DebugLogger.shared.debug("Setup attempt \(attempt)/\(self.maxRetryAttempts)", source: "GlobalHotkeyManager")
- if setupGlobalHotkey() {
- isInitialized = true
+ if self.setupGlobalHotkey() {
+ self.isInitialized = true
DebugLogger.shared.info("Successfully initialized on attempt \(attempt)", source: "GlobalHotkeyManager")
- startHealthCheckTimer()
+ self.startHealthCheckTimer()
return
}
- if attempt < maxRetryAttempts {
+ if attempt < self.maxRetryAttempts {
DebugLogger.shared.warning(
- "Attempt \(attempt) failed, retrying in \(retryDelay) seconds...",
+ "Attempt \(attempt) failed, retrying in \(self.retryDelay) seconds...",
source: "GlobalHotkeyManager"
)
Task { [weak self] in
@@ -150,14 +150,14 @@ final class GlobalHotkeyManager: NSObject {
}
DebugLogger.shared.error(
- "Failed to initialize after \(maxRetryAttempts) attempts",
+ "Failed to initialize after \(self.maxRetryAttempts) attempts",
source: "GlobalHotkeyManager"
)
}
@discardableResult
private func setupGlobalHotkey() -> Bool {
- cleanupEventTap()
+ self.cleanupEventTap()
if !AXIsProcessTrusted() {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
@@ -170,7 +170,7 @@ final class GlobalHotkeyManager: NSObject {
| (1 << CGEventType.keyUp.rawValue)
| (1 << CGEventType.flagsChanged.rawValue)
- eventTap = CGEvent.tapCreate(
+ self.eventTap = CGEvent.tapCreate(
tap: .cgSessionEventTap,
place: .headInsertEventTap,
options: .defaultTap,
@@ -191,7 +191,7 @@ final class GlobalHotkeyManager: NSObject {
return false
}
- runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0)
+ self.runLoopSource = CFMachPortCreateRunLoopSource(kCFAllocatorDefault, tap, 0)
guard let source = runLoopSource else {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Failed to create CFRunLoopSource")
@@ -202,11 +202,11 @@ final class GlobalHotkeyManager: NSObject {
CFRunLoopAddSource(CFRunLoopGetMain(), source, .commonModes)
CGEvent.tapEnable(tap: tap, enable: true)
- if !isEventTapEnabled() {
+ if !self.isEventTapEnabled() {
if UserDefaults.standard.bool(forKey: "enableDebugLogs") {
print("[GlobalHotkeyManager] Event tap could not be enabled")
}
- cleanupEventTap()
+ self.cleanupEventTap()
return false
}
@@ -225,8 +225,8 @@ final class GlobalHotkeyManager: NSObject {
CFRunLoopRemoveSource(CFRunLoopGetMain(), source, .commonModes)
}
- eventTap = nil
- runLoopSource = nil
+ self.eventTap = nil
+ self.runLoopSource = nil
}
private func handleKeyEvent(proxy: CGEventTapProxy, type: CGEventType, event: CGEvent) -> Unmanaged<CGEvent>? {
@@ -246,7 +246,7 @@ final class GlobalHotkeyManager: NSObject {
if keyCode == 53, eventModifiers.isEmpty {
var handled = false
- if asrService.isRunning {
+ if self.asrService.isRunning {
DebugLogger.shared.info("Escape pressed - cancelling recording", source: "GlobalHotkeyManager")
Task { @MainActor in
self.asrService.stopWithoutTranscription()
@@ -266,126 +266,126 @@ final class GlobalHotkeyManager: NSObject {
}
// Check command mode hotkey first
- if commandModeShortcutEnabled, matchesCommandModeShortcut(
+ if self.commandModeShortcutEnabled, self.matchesCommandModeShortcut(
keyCode: keyCode,
modifiers: eventModifiers
) {
- if pressAndHoldMode {
+ if self.pressAndHoldMode {
// Press and hold: start on keyDown, stop on keyUp
- if !isCommandModeKeyPressed {
- isCommandModeKeyPressed = true
+ if !self.isCommandModeKeyPressed {
+ self.isCommandModeKeyPressed = true
DebugLogger.shared.info(
"Command mode shortcut pressed (hold mode) - starting",
source: "GlobalHotkeyManager"
)
- triggerCommandMode()
+ self.triggerCommandMode()
}
} else {
// Toggle mode: press to start, press again to stop
- if asrService.isRunning {
+ if self.asrService.isRunning {
DebugLogger.shared.info(
"Command mode shortcut pressed while recording - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
} else {
DebugLogger.shared.info(
"Command mode shortcut triggered - starting",
source: "GlobalHotkeyManager"
)
- triggerCommandMode()
+ self.triggerCommandMode()
}
}
return nil
}
// Check dedicated rewrite mode hotkey
- if rewriteModeShortcutEnabled, matchesRewriteModeShortcut(
+ if self.rewriteModeShortcutEnabled, self.matchesRewriteModeShortcut(
keyCode: keyCode,
modifiers: eventModifiers
) {
- if pressAndHoldMode {
+ if self.pressAndHoldMode {
// Press and hold: start on keyDown, stop on keyUp
- if !isRewriteKeyPressed {
- isRewriteKeyPressed = true
+ if !self.isRewriteKeyPressed {
+ self.isRewriteKeyPressed = true
DebugLogger.shared.info(
"Rewrite mode shortcut pressed (hold mode) - starting",
source: "GlobalHotkeyManager"
)
- triggerRewriteMode()
+ self.triggerRewriteMode()
}
} else {
// Toggle mode: press to start, press again to stop
- if asrService.isRunning {
+ if self.asrService.isRunning {
DebugLogger.shared.info(
"Rewrite mode shortcut pressed while recording - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
} else {
DebugLogger.shared.info(
"Rewrite mode shortcut triggered - starting",
source: "GlobalHotkeyManager"
)
- triggerRewriteMode()
+ self.triggerRewriteMode()
}
}
return nil
}
// Then check transcription hotkey
- if matchesShortcut(keyCode: keyCode, modifiers: eventModifiers) {
- if pressAndHoldMode {
- if !isKeyPressed {
- isKeyPressed = true
- startRecordingIfNeeded()
+ if self.matchesShortcut(keyCode: keyCode, modifiers: eventModifiers) {
+ if self.pressAndHoldMode {
+ if !self.isKeyPressed {
+ self.isKeyPressed = true
+ self.startRecordingIfNeeded()
}
} else {
- toggleRecording()
+ self.toggleRecording()
}
return nil
}
case .keyUp:
// Command mode key up (press and hold mode)
- if commandModeShortcutEnabled, pressAndHoldMode, isCommandModeKeyPressed,
- matchesCommandModeShortcut(
+ if self.commandModeShortcutEnabled, self.pressAndHoldMode, self.isCommandModeKeyPressed,
+ self.matchesCommandModeShortcut(
keyCode: keyCode,
modifiers: eventModifiers
)
{
- isCommandModeKeyPressed = false
+ self.isCommandModeKeyPressed = false
DebugLogger.shared.info(
"Command mode shortcut released (hold mode) - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
return nil
}
// Rewrite mode key up (press and hold mode)
- if rewriteModeShortcutEnabled, pressAndHoldMode, isRewriteKeyPressed,
- matchesRewriteModeShortcut(
+ if self.rewriteModeShortcutEnabled, self.pressAndHoldMode, self.isRewriteKeyPressed,
+ self.matchesRewriteModeShortcut(
keyCode: keyCode,
modifiers: eventModifiers
)
{
- isRewriteKeyPressed = false
+ self.isRewriteKeyPressed = false
DebugLogger.shared.info(
"Rewrite mode shortcut released (hold mode) - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
return nil
}
// Transcription key up
- if pressAndHoldMode, isKeyPressed, matchesShortcut(
+ if self.pressAndHoldMode, self.isKeyPressed, self.matchesShortcut(
keyCode: keyCode,
modifiers: eventModifiers
) {
- isKeyPressed = false
- stopRecordingIfNeeded()
+ self.isKeyPressed = false
+ self.stopRecordingIfNeeded()
return nil
}
@@ -397,105 +397,105 @@ final class GlobalHotkeyManager: NSObject {
|| flags.contains(.maskShift)
// Check command mode shortcut (if it's a modifier-only shortcut)
- if commandModeShortcutEnabled, commandModeShortcut.modifierFlags.isEmpty,
- keyCode == commandModeShortcut.keyCode
+ if self.commandModeShortcutEnabled, self.commandModeShortcut.modifierFlags.isEmpty,
+ keyCode == self.commandModeShortcut.keyCode
{
if isModifierPressed {
- if pressAndHoldMode {
- if !isCommandModeKeyPressed {
- isCommandModeKeyPressed = true
+ if self.pressAndHoldMode {
+ if !self.isCommandModeKeyPressed {
+ self.isCommandModeKeyPressed = true
DebugLogger.shared.info(
"Command mode modifier pressed (hold mode) - starting",
source: "GlobalHotkeyManager"
)
- triggerCommandMode()
+ self.triggerCommandMode()
}
} else {
// Toggle mode
- if asrService.isRunning {
+ if self.asrService.isRunning {
DebugLogger.shared.info(
"Command mode modifier pressed while recording - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
} else {
DebugLogger.shared.info(
"Command mode modifier pressed - starting",
source: "GlobalHotkeyManager"
)
- triggerCommandMode()
+ self.triggerCommandMode()
}
}
- } else if pressAndHoldMode, isCommandModeKeyPressed {
+ } else if self.pressAndHoldMode, self.isCommandModeKeyPressed {
// Key released in press-and-hold mode
- isCommandModeKeyPressed = false
+ self.isCommandModeKeyPressed = false
DebugLogger.shared.info(
"Command mode modifier released (hold mode) - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
}
return nil
}
// Check rewrite mode shortcut (if it's a modifier-only shortcut)
- if rewriteModeShortcutEnabled, rewriteModeShortcut.modifierFlags.isEmpty,
- keyCode == rewriteModeShortcut.keyCode
+ if self.rewriteModeShortcutEnabled, self.rewriteModeShortcut.modifierFlags.isEmpty,
+ keyCode == self.rewriteModeShortcut.keyCode
{
if isModifierPressed {
- if pressAndHoldMode {
- if !isRewriteKeyPressed {
- isRewriteKeyPressed = true
+ if self.pressAndHoldMode {
+ if !self.isRewriteKeyPressed {
+ self.isRewriteKeyPressed = true
DebugLogger.shared.info(
"Rewrite mode modifier pressed (hold mode) - starting",
source: "GlobalHotkeyManager"
)
- triggerRewriteMode()
+ self.triggerRewriteMode()
}
} else {
// Toggle mode
- if asrService.isRunning {
+ if self.asrService.isRunning {
DebugLogger.shared.info(
"Rewrite mode modifier pressed while recording - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
} else {
DebugLogger.shared.info(
"Rewrite mode modifier pressed - starting",
source: "GlobalHotkeyManager"
)
- triggerRewriteMode()
+ self.triggerRewriteMode()
}
}
- } else if pressAndHoldMode, isRewriteKeyPressed {
+ } else if self.pressAndHoldMode, self.isRewriteKeyPressed {
// Key released in press-and-hold mode
- isRewriteKeyPressed = false
+ self.isRewriteKeyPressed = false
DebugLogger.shared.info(
"Rewrite mode modifier released (hold mode) - stopping",
source: "GlobalHotkeyManager"
)
- stopRecordingIfNeeded()
+ self.stopRecordingIfNeeded()
}
return nil
}
// Check transcription shortcut (if it's a modifier-only shortcut)
- guard shortcut.modifierFlags.isEmpty else { break }
+ guard self.shortcut.modifierFlags.isEmpty else { break }
- if keyCode == shortcut.keyCode {
- if pressAndHoldMode {
+ if keyCode == self.shortcut.keyCode {
+ if self.pressAndHoldMode {
if isModifierPressed {
- if !isKeyPressed {
- isKeyPressed = true
- startRecordingIfNeeded()
+ if !self.isKeyPressed {
+ self.isKeyPressed = true
+ self.startRecordingIfNeeded()
}
- } else if isKeyPressed {
- isKeyPressed = false
- stopRecordingIfNeeded()
+ } else if self.isKeyPressed {
+ self.isKeyPressed = false
+ self.stopRecordingIfNeeded()
}
} else if isModifierPressed {
- toggleRecording()
+ self.toggleRecording()
}
return nil
}
@@ -524,19 +524,19 @@ final class GlobalHotkeyManager: NSObject {
}
func enablePressAndHoldMode(_ enable: Bool) {
- pressAndHoldMode = enable
- if !enable, isKeyPressed {
- isKeyPressed = false
- stopRecordingIfNeeded()
+ self.pressAndHoldMode = enable
+ if !enable, self.isKeyPressed {
+ self.isKeyPressed = false
+ self.stopRecordingIfNeeded()
} else if enable {
- isKeyPressed = false
+ self.isKeyPressed = false
}
}
private func toggleRecording() {
// Capture state at event time to prevent race conditions
- let shouldStop = asrService.isRunning
- let alreadyProcessing = isProcessingStop
+ let shouldStop = self.asrService.isRunning
+ let alreadyProcessing = self.isProcessingStop
Task { @MainActor [weak self] in
guard let self = self else { return }
@@ -562,8 +562,8 @@ final class GlobalHotkeyManager: NSObject {
private func startRecordingIfNeeded() {
// Capture state at event time
- let alreadyRunning = asrService.isRunning
- let alreadyProcessing = isProcessingStop
+ let alreadyRunning = self.asrService.isRunning
+ let alreadyProcessing = self.isProcessingStop
Task { @MainActor [weak self] in
guard let self = self else { return }
@@ -587,8 +587,8 @@ final class GlobalHotkeyManager: NSObject {
private func stopRecordingIfNeeded() {
// Capture state at event time
- let shouldStop = asrService.isRunning
- let alreadyProcessing = isProcessingStop
+ let shouldStop = self.asrService.isRunning
+ let alreadyProcessing = self.isProcessingStop
Task { @MainActor [weak self] in
guard let self = self else { return }
@@ -607,19 +607,19 @@ final class GlobalHotkeyManager: NSObject {
@MainActor
private func stopRecordingInternal() async {
- guard asrService.isRunning else { return }
- guard !isProcessingStop else {
+ guard self.asrService.isRunning else { return }
+ guard !self.isProcessingStop else {
DebugLogger.shared.debug("Stop already in progress, ignoring", source: "GlobalHotkeyManager")
return
}
- isProcessingStop = true
+ self.isProcessingStop = true
defer { isProcessingStop = false }
if let callback = stopAndProcessCallback {
await callback()
} else {
- asrService.stopWithoutTranscription()
+ self.asrService.stopWithoutTranscription()
}
}
@@ -631,14 +631,14 @@ final class GlobalHotkeyManager: NSObject {
.control,
.shift,
])
- let shortcutModifiers = shortcut.modifierFlags.intersection([
+ let shortcutModifiers = self.shortcut.modifierFlags.intersection([
.function,
.command,
.option,
.control,
.shift,
])
- return keyCode == shortcut.keyCode && relevantModifiers == shortcutModifiers
+ return keyCode == self.shortcut.keyCode && relevantModifiers == shortcutModifiers
}
private func matchesCommandModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool {
@@ -649,14 +649,14 @@ final class GlobalHotkeyManager: NSObject {
.control,
.shift,
])
- let shortcutModifiers = commandModeShortcut.modifierFlags.intersection([
+ let shortcutModifiers = self.commandModeShortcut.modifierFlags.intersection([
.function,
.command,
.option,
.control,
.shift,
])
- return keyCode == commandModeShortcut.keyCode && relevantModifiers == shortcutModifiers
+ return keyCode == self.commandModeShortcut.keyCode && relevantModifiers == shortcutModifiers
}
private func matchesRewriteModeShortcut(keyCode: UInt16, modifiers: NSEvent.ModifierFlags) -> Bool {
@@ -667,14 +667,14 @@ final class GlobalHotkeyManager: NSObject {
.control,
.shift,
])
- let shortcutModifiers = rewriteModeShortcut.modifierFlags.intersection([
+ let shortcutModifiers = self.rewriteModeShortcut.modifierFlags.intersection([
.function,
.command,
.option,
.control,
.shift,
])
- return keyCode == rewriteModeShortcut.keyCode && relevantModifiers == shortcutModifiers
+ return keyCode == self.rewriteModeShortcut.keyCode && relevantModifiers == shortcutModifiers
}
func isEventTapEnabled() -> Bool {
@@ -685,9 +685,9 @@ final class GlobalHotkeyManager: NSObject {
func validateEventTapHealth() -> Bool {
// Treat an enabled event tap as "healthy", even if our internal `isInitialized` flag drifted.
// This prevents false "initializing" UI while hotkeys are already working.
- let enabled = isEventTapEnabled()
- if enabled && !isInitialized {
- isInitialized = true
+ let enabled = self.isEventTapEnabled()
+ if enabled && !self.isInitialized {
+ self.isInitialized = true
}
return enabled
}
@@ -697,15 +697,15 @@ final class GlobalHotkeyManager: NSObject {
print("[GlobalHotkeyManager] Manual reinitialization requested")
}
- initializationTask?.cancel()
- healthCheckTask?.cancel()
- isInitialized = false
- initializeWithDelay()
+ self.initializationTask?.cancel()
+ self.healthCheckTask?.cancel()
+ self.isInitialized = false
+ self.initializeWithDelay()
}
private func startHealthCheckTimer() {
- healthCheckTask?.cancel()
- healthCheckTask = Task {
+ self.healthCheckTask?.cancel()
+ self.healthCheckTask = Task {
while !Task.isCancelled {
try? await Task.sleep(nanoseconds: UInt64(self.healthCheckInterval * 1_000_000_000))
diff --git a/Sources/Fluid/Services/MeetingTranscriptionService.swift b/Sources/Fluid/Services/MeetingTranscriptionService.swift
index 252cfe11..a908a207 100644
--- a/Sources/Fluid/Services/MeetingTranscriptionService.swift
+++ b/Sources/Fluid/Services/MeetingTranscriptionService.swift
@@ -59,16 +59,16 @@ final class MeetingTranscriptionService: ObservableObject {
/// Initialize the ASR models (reuses models from ASRService - no duplicate download!)
func initializeModels() async throws {
- guard !asrService.isAsrReady else { return }
+ guard !self.asrService.isAsrReady else { return }
- currentStatus = "Preparing ASR models..."
- progress = 0.1
+ self.currentStatus = "Preparing ASR models..."
+ self.progress = 0.1
do {
- try await asrService.ensureAsrReady()
+ try await self.asrService.ensureAsrReady()
- currentStatus = "Models ready"
- progress = 0.0
+ self.currentStatus = "Models ready"
+ self.progress = 0.0
} catch {
throw TranscriptionError.modelLoadFailed(error.localizedDescription)
}
@@ -78,9 +78,9 @@ final class MeetingTranscriptionService: ObservableObject {
/// - Parameters:
/// - fileURL: URL to the audio/video file
func transcribeFile(_ fileURL: URL) async throws -> TranscriptionResult {
- isTranscribing = true
+ self.isTranscribing = true
error = nil
- progress = 0.0
+ self.progress = 0.0
let startTime = Date()
defer {
@@ -90,8 +90,8 @@ final class MeetingTranscriptionService: ObservableObject {
do {
// Initialize models if not already done (reuses ASRService models)
- if !asrService.isAsrReady {
- try await initializeModels()
+ if !self.asrService.isAsrReady {
+ try await self.initializeModels()
}
#if arch(arm64)
@@ -100,8 +100,8 @@ final class MeetingTranscriptionService: ObservableObject {
}
// Convert audio to required format (16kHz mono Float32)
- currentStatus = "Converting audio..."
- progress = 0.3
+ self.currentStatus = "Converting audio..."
+ self.progress = 0.3
let converter = AudioConverter()
let samples: [Float]
@@ -124,13 +124,13 @@ final class MeetingTranscriptionService: ObservableObject {
let duration = Double(samples.count) / 16_000.0 // 16kHz sample rate
// Transcribe
- currentStatus = "Transcribing audio (\(Int(duration))s)..."
- progress = 0.6
+ self.currentStatus = "Transcribing audio (\(Int(duration))s)..."
+ self.progress = 0.6
let transcriptionResult = try await asrManager.transcribe(samples, source: .system)
- currentStatus = "Complete!"
- progress = 1.0
+ self.currentStatus = "Complete!"
+ self.progress = 1.0
let processingTime = Date().timeIntervalSince(startTime)
@@ -188,9 +188,9 @@ final class MeetingTranscriptionService: ObservableObject {
/// Reset the service state
func reset() {
- result = nil
- error = nil
- currentStatus = ""
- progress = 0.0
+ self.result = nil
+ self.error = nil
+ self.currentStatus = ""
+ self.progress = 0.0
}
}
diff --git a/Sources/Fluid/Services/MenuBarManager.swift b/Sources/Fluid/Services/MenuBarManager.swift
index 19307d00..fb500a2f 100644
--- a/Sources/Fluid/Services/MenuBarManager.swift
+++ b/Sources/Fluid/Services/MenuBarManager.swift
@@ -45,18 +45,18 @@ final class MenuBarManager: ObservableObject {
init() {
// Don't setup menu bar immediately - defer until app is ready
// Initialize from persisted setting
- aiProcessingEnabled = SettingsStore.shared.enableAIProcessing
+ self.aiProcessingEnabled = SettingsStore.shared.enableAIProcessing
// Reflect changes to menu when toggled from elsewhere (e.g., General tab)
- $aiProcessingEnabled
+ self.$aiProcessingEnabled
.receive(on: DispatchQueue.main)
.sink { [weak self] _ in
self?.updateMenu()
}
- .store(in: &cancellables)
+ .store(in: &self.cancellables)
}
func initializeMenuBar() {
- guard !isSetup else { return }
+ guard !self.isSetup else { return }
// Ensure we're on main thread and app is active
DispatchQueue.main.async { [weak self] in
@@ -82,7 +82,7 @@ final class MenuBarManager: ObservableObject {
// Handle overlay lifecycle (independent of window state)
self?.handleOverlayState(isRunning: isRunning, asrService: asrService)
}
- .store(in: &cancellables)
+ .store(in: &self.cancellables)
// Subscribe to partial transcription updates for streaming preview
asrService.$partialTranscription
@@ -95,40 +95,40 @@ final class MenuBarManager: ObservableObject {
NotchOverlayManager.shared.updateTranscriptionText(newText)
}
}
- .store(in: &cancellables)
+ .store(in: &self.cancellables)
// Subscribe to AI processing state
- aiProcessingEnabled = SettingsStore.shared.enableAIProcessing
+ self.aiProcessingEnabled = SettingsStore.shared.enableAIProcessing
}
private func handleOverlayState(isRunning: Bool, asrService: ASRService) {
// Prevent rapid state changes that could cause cycles
- guard overlayVisible != isRunning else { return }
+ guard self.overlayVisible != isRunning else { return }
let delay: DispatchTimeInterval = .milliseconds(150)
if isRunning {
// Cancel any pending hide operation
- pendingHideOperation?.cancel()
- pendingHideOperation = nil
+ self.pendingHideOperation?.cancel()
+ self.pendingHideOperation = nil
- overlayVisible = true
+ self.overlayVisible = true
// If expanded command output is showing, check if we should keep it or close it
if NotchOverlayManager.shared.isCommandOutputExpanded {
// Only keep expanded notch if this is a command mode recording (follow-up)
// For other modes (dictation, rewrite), close it and show regular notch
- if currentOverlayMode == .command {
+ if self.currentOverlayMode == .command {
// Enable recording visualization in the expanded notch
NotchContentState.shared.setRecordingInExpandedMode(true)
// Subscribe to audio levels and forward to expanded notch
- expandedModeAudioSubscription = asrService.audioLevelPublisher
+ self.expandedModeAudioSubscription = asrService.audioLevelPublisher
.receive(on: DispatchQueue.main)
.sink { level in
NotchContentState.shared.updateExpandedModeAudioLevel(level)
}
- pendingShowOperation = nil
+ self.pendingShowOperation = nil
return
} else {
// Close expanded command notch to transition to regular notch
@@ -154,23 +154,23 @@ final class MenuBarManager: ObservableObject {
self.pendingShowOperation = nil
}
- pendingShowOperation = showItem
+ self.pendingShowOperation = showItem
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: showItem)
} else {
// Cancel any pending show operation
- pendingShowOperation?.cancel()
- pendingShowOperation = nil
+ self.pendingShowOperation?.cancel()
+ self.pendingShowOperation = nil
- overlayVisible = false
+ self.overlayVisible = false
// If expanded command output is showing, don't hide it - let it stay visible
if NotchOverlayManager.shared.isCommandOutputExpanded {
// Stop recording visualization in expanded notch
NotchContentState.shared.setRecordingInExpandedMode(false)
- expandedModeAudioSubscription?.cancel()
- expandedModeAudioSubscription = nil
+ self.expandedModeAudioSubscription?.cancel()
+ self.expandedModeAudioSubscription = nil
- pendingHideOperation = nil
+ self.pendingHideOperation = nil
return
}
@@ -188,7 +188,7 @@ final class MenuBarManager: ObservableObject {
self.pendingHideOperation = nil
}
- pendingHideOperation = hideItem
+ self.pendingHideOperation = hideItem
DispatchQueue.main.asyncAfter(deadline: .now() + delay, execute: hideItem)
}
}
@@ -200,23 +200,23 @@ final class MenuBarManager: ObservableObject {
}
func setOverlayMode(_ mode: OverlayMode) {
- currentOverlayMode = mode
+ self.currentOverlayMode = mode
NotchOverlayManager.shared.setMode(mode)
}
func setProcessing(_ processing: Bool) {
if processing {
// Cancel any pending hide - we want to keep the overlay visible for AI processing
- pendingHideOperation?.cancel()
- pendingHideOperation = nil
- overlayVisible = true
+ self.pendingHideOperation?.cancel()
+ self.pendingHideOperation = nil
+ self.overlayVisible = true
} else {
// When processing ends, schedule the hide (unless expanded output is showing)
- overlayVisible = false
+ self.overlayVisible = false
// If expanded command output is showing, don't hide it
if NotchOverlayManager.shared.isCommandOutputExpanded {
- pendingHideOperation = nil
+ self.pendingHideOperation = nil
NotchOverlayManager.shared.setProcessing(processing)
return
}
@@ -233,7 +233,7 @@ final class MenuBarManager: ObservableObject {
NotchOverlayManager.shared.hide()
self.pendingHideOperation = nil
}
- pendingHideOperation = hideItem
+ self.pendingHideOperation = hideItem
DispatchQueue.main.asyncAfter(deadline: .now() + .milliseconds(100), execute: hideItem)
}
NotchOverlayManager.shared.setProcessing(processing)
@@ -250,8 +250,8 @@ final class MenuBarManager: ObservableObject {
}
do {
- try setupMenuBar()
- isSetup = true
+ try self.setupMenuBar()
+ self.isSetup = true
} catch {
// If setup fails, retry after delay
print("MenuBar setup failed, retrying: \(error)")
@@ -263,7 +263,7 @@ final class MenuBarManager: ObservableObject {
private func setupMenuBar() throws {
// Ensure we're not already set up
- guard !isSetup else { return }
+ guard !self.isSetup else { return }
// Create status item with error handling
statusItem = NSStatusBar.system.statusItem(withLength: NSStatusItem.squareLength)
@@ -277,20 +277,20 @@ final class MenuBarManager: ObservableObject {
}
// Set initial icon
- updateMenuBarIcon()
+ self.updateMenuBarIcon()
// Create menu
- menu = NSMenu()
- statusItem.menu = menu
+ self.menu = NSMenu()
+ statusItem.menu = self.menu
- updateMenu()
+ self.updateMenu()
}
private func updateMenuBarIcon() {
guard let statusItem = statusItem else { return }
// Use custom F icon instead of microphone
- let image = createFluidIcon(isRecording: isRecording)
+ let image = self.createFluidIcon(isRecording: self.isRecording)
statusItem.button?.image = image
statusItem.button?.imagePosition = .imageOnly
@@ -347,7 +347,7 @@ final class MenuBarManager: ObservableObject {
// Status indicator with hotkey info
let statusItem = NSMenuItem(title: "", action: nil, keyEquivalent: "")
statusItem.isEnabled = false
- statusMenuItem = statusItem
+ self.statusMenuItem = statusItem
menu.addItem(statusItem)
menu.addItem(.separator())
@@ -355,7 +355,7 @@ final class MenuBarManager: ObservableObject {
// AI Processing Toggle
let aiItem = NSMenuItem(title: "", action: #selector(toggleAIProcessing), keyEquivalent: "")
aiItem.target = self
- aiMenuItem = aiItem
+ self.aiMenuItem = aiItem
menu.addItem(aiItem)
menu.addItem(.separator())
@@ -392,16 +392,16 @@ final class MenuBarManager: ObservableObject {
menu.addItem(quitItem)
// Now update the text content
- updateMenuItemsText()
+ self.updateMenuItemsText()
}
private func updateMenu() {
// If menu structure hasn't been built yet, build it
- if statusMenuItem == nil {
- buildMenuStructure()
+ if self.statusMenuItem == nil {
+ self.buildMenuStructure()
} else {
// Just update the text of existing items
- updateMenuItemsText()
+ self.updateMenuItemsText()
}
}
@@ -409,20 +409,20 @@ final class MenuBarManager: ObservableObject {
// Update status text with hotkey info
let hotkeyShortcut = SettingsStore.shared.hotkeyShortcut
let hotkeyInfo = hotkeyShortcut.displayString.isEmpty ? "" : " (\(hotkeyShortcut.displayString))"
- let statusTitle = isRecording ? "Recording...\(hotkeyInfo)" : "Ready to Record\(hotkeyInfo)"
- statusMenuItem?.title = statusTitle
+ let statusTitle = self.isRecording ? "Recording...\(hotkeyInfo)" : "Ready to Record\(hotkeyInfo)"
+ self.statusMenuItem?.title = statusTitle
// Update AI toggle text
- let aiTitle = aiProcessingEnabled ? "Disable AI Processing" : "Enable AI Processing"
- aiMenuItem?.title = aiTitle
+ let aiTitle = self.aiProcessingEnabled ? "Disable AI Processing" : "Enable AI Processing"
+ self.aiMenuItem?.title = aiTitle
}
@objc private func toggleAIProcessing() {
- aiProcessingEnabled.toggle()
+ self.aiProcessingEnabled.toggle()
// Persist and broadcast change
- SettingsStore.shared.enableAIProcessing = aiProcessingEnabled
+ SettingsStore.shared.enableAIProcessing = self.aiProcessingEnabled
// If a ContentView has bound to MenuBarManager, its onChange sync will mirror this
- updateMenu()
+ self.updateMenu()
}
@objc private func checkForUpdates(_ sender: Any?) {
@@ -472,7 +472,7 @@ final class MenuBarManager: ObservableObject {
// Important: avoid programmatic deminiaturize() — it creates internal window transform animations
// (NSWindowTransformAnimation) that have been unstable on macOS 26.x for this app.
if let window = hostedWindow, window.isReleasedWhenClosed == false {
- ensureUsableMainWindow(window)
+ self.ensureUsableMainWindow(window)
window.animationBehavior = .none
window.makeKeyAndOrderFront(nil)
} else if let window = NSApp.windows.first(where: { win in
@@ -485,13 +485,13 @@ final class MenuBarManager: ObservableObject {
// Prefer our main window title when present (both SwiftUI and our fallback window use this)
return win.title == "FluidVoice" || win.title.contains("FluidVoice")
}) {
- ensureUsableMainWindow(window)
+ self.ensureUsableMainWindow(window)
window.animationBehavior = .none
window.makeKeyAndOrderFront(nil)
- hostedWindow = window
+ self.hostedWindow = window
} else {
// If there is no suitable window (or it's minimized), create a fresh one.
- createAndShowMainWindow()
+ self.createAndShowMainWindow()
}
// Final attempt: ensure app is active and visible
@@ -500,10 +500,10 @@ final class MenuBarManager: ObservableObject {
@objc private func openPreferences() {
// Ensure a fresh one-shot request every time the menu item is clicked.
- requestedNavigationDestination = nil
- requestedNavigationDestination = .preferences
+ self.requestedNavigationDestination = nil
+ self.requestedNavigationDestination = .preferences
- openMainWindow()
+ self.openMainWindow()
// Nudge again after the window is front-most, so an already-open ContentView
// will still switch tabs even if it consumed a previous preference request.
@@ -534,9 +534,9 @@ final class MenuBarManager: ObservableObject {
window.minSize = NSSize(width: 800, height: 500)
window.isReleasedWhenClosed = false
window.contentViewController = hostingController
- window.setFrame(defaultWindowFrame(), display: false)
+ window.setFrame(self.defaultWindowFrame(), display: false)
window.makeKeyAndOrderFront(nil)
- hostedWindow = window
+ self.hostedWindow = window
// Bring app to front in case we're running as an accessory app (no Dock)
NSApp.activate(ignoringOtherApps: true)
@@ -549,7 +549,7 @@ final class MenuBarManager: ObservableObject {
let frame = window.frame
if frame.height < minSize.height || frame.width < minSize.width {
- window.setFrame(defaultWindowFrame(), display: false)
+ window.setFrame(self.defaultWindowFrame(), display: false)
}
}
diff --git a/Sources/Fluid/Services/NotchOverlayManager.swift b/Sources/Fluid/Services/NotchOverlayManager.swift
index f2c3ec9e..86a66dc1 100644
--- a/Sources/Fluid/Services/NotchOverlayManager.swift
+++ b/Sources/Fluid/Services/NotchOverlayManager.swift
@@ -67,7 +67,7 @@ final class NotchOverlayManager {
private var localEscapeMonitor: Any?
private init() {
- setupEscapeKeyMonitors()
+ self.setupEscapeKeyMonitors()
}
deinit {
@@ -101,34 +101,34 @@ final class NotchOverlayManager {
}
// Global monitor - catches escape when OTHER apps have focus
- globalEscapeMonitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { event in
+ self.globalEscapeMonitor = NSEvent.addGlobalMonitorForEvents(matching: .keyDown) { event in
_ = escapeHandler(event)
}
// Local monitor - catches escape when OUR app/notch has focus
- localEscapeMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: escapeHandler)
+ self.localEscapeMonitor = NSEvent.addLocalMonitorForEvents(matching: .keyDown, handler: escapeHandler)
}
func show(audioLevelPublisher: AnyPublisher<CGFloat, Never>, mode: OverlayMode) {
// Don't show regular notch if expanded command output is visible
- if isCommandOutputExpanded {
+ if self.isCommandOutputExpanded {
// Just store the publisher for later use
- lastAudioPublisher = audioLevelPublisher
+ self.lastAudioPublisher = audioLevelPublisher
return
}
// Cancel any pending retry operations
- pendingRetryTask?.cancel()
- pendingRetryTask = nil
+ self.pendingRetryTask?.cancel()
+ self.pendingRetryTask = nil
// If already visible or in transition, wait for cleanup to complete
- if notch != nil || state != .idle {
+ if self.notch != nil || self.state != .idle {
// Increment generation to invalidate stale operations
- generation &+= 1
- let targetGeneration = generation
+ self.generation &+= 1
+ let targetGeneration = self.generation
// Start async cleanup and retry
- pendingRetryTask = Task { [weak self] in
+ self.pendingRetryTask = Task { [weak self] in
guard let self = self else { return }
// Perform cleanup synchronously first
@@ -146,21 +146,21 @@ final class NotchOverlayManager {
return
}
- showInternal(audioLevelPublisher: audioLevelPublisher, mode: mode)
+ self.showInternal(audioLevelPublisher: audioLevelPublisher, mode: mode)
}
private func showInternal(audioLevelPublisher: AnyPublisher<CGFloat, Never>, mode: OverlayMode) {
- guard state == .idle else { return }
+ guard self.state == .idle else { return }
// Store for potential re-show during processing
- lastAudioPublisher = audioLevelPublisher
+ self.lastAudioPublisher = audioLevelPublisher
// Increment generation for this operation
- generation &+= 1
- let currentGeneration = generation
+ self.generation &+= 1
+ let currentGeneration = self.generation
- state = .showing
- currentMode = mode
+ self.state = .showing
+ self.currentMode = mode
// Update shared content state immediately
NotchContentState.shared.mode = mode
@@ -178,7 +178,7 @@ final class NotchOverlayManager {
NotchCompactTrailingView()
}
- notch = newNotch
+ self.notch = newNotch
// Show in expanded state
Task { [weak self] in
@@ -191,24 +191,24 @@ final class NotchOverlayManager {
func hide() {
// Cancel any pending retry operations
- pendingRetryTask?.cancel()
- pendingRetryTask = nil
+ self.pendingRetryTask?.cancel()
+ self.pendingRetryTask = nil
// Safety: reset processing state when hiding
NotchContentState.shared.setProcessing(false)
// Increment generation to invalidate any pending show tasks
- generation &+= 1
- let currentGeneration = generation
+ self.generation &+= 1
+ let currentGeneration = self.generation
// Handle visible or showing states (can hide while still expanding)
- guard state == .visible || state == .showing, let currentNotch = notch else {
+ guard self.state == .visible || self.state == .showing, let currentNotch = notch else {
// Force cleanup if stuck or in inconsistent state
Task { [weak self] in await self?.performCleanup() }
return
}
- state = .hiding
+ self.state = .hiding
Task { [weak self] in
await currentNotch.hide()
@@ -222,20 +222,20 @@ final class NotchOverlayManager {
/// Async cleanup that properly waits for hide to complete
private func performCleanup() async {
// Cancel any pending retry operations
- pendingRetryTask?.cancel()
- pendingRetryTask = nil
+ self.pendingRetryTask?.cancel()
+ self.pendingRetryTask = nil
if let existingNotch = notch {
await existingNotch.hide()
}
- notch = nil
- state = .idle
+ self.notch = nil
+ self.state = .idle
}
func setMode(_ mode: OverlayMode) {
// Always update NotchContentState to ensure UI stays in sync
// (can get out of sync during show/hide transitions)
- currentMode = mode
+ self.currentMode = mode
NotchContentState.shared.mode = mode
}
@@ -247,16 +247,16 @@ final class NotchOverlayManager {
NotchContentState.shared.setProcessing(processing)
// If expanded command output is showing, don't mess with regular notch
- if isCommandOutputExpanded {
+ if self.isCommandOutputExpanded {
return
}
if processing {
// If notch isn't visible, re-show it for processing state
- if state == .idle || state == .hiding {
+ if self.state == .idle || self.state == .hiding {
// Use stored publisher or create empty one
- let publisher = lastAudioPublisher ?? Empty<CGFloat, Never>().eraseToAnyPublisher()
- show(audioLevelPublisher: publisher, mode: currentMode)
+ let publisher = self.lastAudioPublisher ?? Empty<CGFloat, Never>().eraseToAnyPublisher()
+ self.show(audioLevelPublisher: publisher, mode: self.currentMode)
}
}
}
@@ -266,8 +266,8 @@ final class NotchOverlayManager {
/// Show expanded command output notch
func showExpandedCommandOutput() {
// Hide regular notch first if visible
- if notch != nil {
- hide()
+ if self.notch != nil {
+ self.hide()
}
// Wait a bit for cleanup
@@ -278,19 +278,19 @@ final class NotchOverlayManager {
}
private func showExpandedCommandOutputInternal() async {
- guard commandOutputState == .idle else { return }
+ guard self.commandOutputState == .idle else { return }
- commandOutputGeneration &+= 1
- let currentGeneration = commandOutputGeneration
+ self.commandOutputGeneration &+= 1
+ let currentGeneration = self.commandOutputGeneration
- commandOutputState = .showing
- isCommandOutputExpanded = true
+ self.commandOutputState = .showing
+ self.isCommandOutputExpanded = true
// Update content state
NotchContentState.shared.mode = .command
NotchContentState.shared.isExpandedForCommandOutput = true
- let publisher = lastAudioPublisher ?? Empty<CGFloat, Never>().eraseToAnyPublisher()
+ let publisher = self.lastAudioPublisher ?? Empty<CGFloat, Never>().eraseToAnyPublisher()
let newNotch = DynamicNotch(
hoverBehavior: [], // No keepVisible - allows closing with X/Escape even when cursor
@@ -334,35 +334,35 @@ final class NotchOverlayManager {
NotchCompactTrailingView()
}
- commandOutputNotch = newNotch
+ self.commandOutputNotch = newNotch
await newNotch.expand()
- guard commandOutputGeneration == currentGeneration else { return }
- commandOutputState = .visible
+ guard self.commandOutputGeneration == currentGeneration else { return }
+ self.commandOutputState = .visible
}
/// Hide expanded command output notch - force close regardless of hover state
func hideExpandedCommandOutput() {
- commandOutputGeneration &+= 1
- let currentGeneration = commandOutputGeneration
+ self.commandOutputGeneration &+= 1
+ let currentGeneration = self.commandOutputGeneration
// Force cleanup state immediately
- isCommandOutputExpanded = false
+ self.isCommandOutputExpanded = false
NotchContentState.shared.collapseCommandOutput()
- guard commandOutputState == .visible || commandOutputState == .showing,
+ guard self.commandOutputState == .visible || self.commandOutputState == .showing,
let currentNotch = commandOutputNotch
else {
- commandOutputState = .idle
+ self.commandOutputState = .idle
return
}
- commandOutputState = .hiding
+ self.commandOutputState = .hiding
// Store reference and nil out immediately to prevent hover from keeping it alive
let notchToHide = currentNotch
- commandOutputNotch = nil
+ self.commandOutputNotch = nil
Task { [weak self] in
// Try to hide gracefully, but we've already removed our reference
@@ -374,22 +374,22 @@ final class NotchOverlayManager {
/// Toggle expanded command output (for hotkey handling)
func toggleExpandedCommandOutput() {
- if isCommandOutputExpanded {
- hideExpandedCommandOutput()
+ if self.isCommandOutputExpanded {
+ self.hideExpandedCommandOutput()
} else if NotchContentState.shared.commandConversationHistory.isEmpty == false {
// Only show if there's history to show
- showExpandedCommandOutput()
+ self.showExpandedCommandOutput()
}
}
/// Check if any notch (regular or expanded) is visible
var isAnyNotchVisible: Bool {
- return state == .visible || state == .showing || isCommandOutputExpanded
+ return self.state == .visible || self.state == .showing || self.isCommandOutputExpanded
}
/// Update audio publisher for expanded notch (when recording starts within it)
func updateAudioPublisher(_ publisher: AnyPublisher<CGFloat, Never>) {
- lastAudioPublisher = publisher
- currentAudioPublisher = publisher
+ self.lastAudioPublisher = publisher
+ self.currentAudioPublisher = publisher
}
}
diff --git a/Sources/Fluid/Services/RewriteModeService.swift b/Sources/Fluid/Services/RewriteModeService.swift
index a927d28a..48768901 100644
--- a/Sources/Fluid/Services/RewriteModeService.swift
+++ b/Sources/Fluid/Services/RewriteModeService.swift
@@ -26,10 +26,10 @@ final class RewriteModeService: ObservableObject {
func captureSelectedText() -> Bool {
if let text = textSelectionService.getSelectedText(), !text.isEmpty {
- originalText = text
- rewrittenText = ""
- conversationHistory = []
- isWriteMode = false
+ self.originalText = text
+ self.rewrittenText = ""
+ self.conversationHistory = []
+ self.isWriteMode = false
return true
}
return false
@@ -37,32 +37,32 @@ final class RewriteModeService: ObservableObject {
/// Start rewrite mode without selected text - user will provide text via voice
func startWithoutSelection() {
- originalText = ""
- rewrittenText = ""
- conversationHistory = []
- isWriteMode = true
+ self.originalText = ""
+ self.rewrittenText = ""
+ self.conversationHistory = []
+ self.isWriteMode = true
}
/// Set the original text directly (from voice input when no text was selected)
func setOriginalText(_ text: String) {
- originalText = text
- rewrittenText = ""
- conversationHistory = []
+ self.originalText = text
+ self.rewrittenText = ""
+ self.conversationHistory = []
}
func processRewriteRequest(_ prompt: String) async {
// If no original text, we're in "Write Mode" - generate content based on user's request
- if originalText.isEmpty {
- originalText = prompt
- isWriteMode = true
+ if self.originalText.isEmpty {
+ self.originalText = prompt
+ self.isWriteMode = true
// Write Mode: User is asking AI to write/generate something
- conversationHistory.append(Message(role: .user, content: prompt))
+ self.conversationHistory.append(Message(role: .user, content: prompt))
} else {
// Rewrite Mode: User has selected text and is giving instructions
- isWriteMode = false
+ self.isWriteMode = false
- if conversationHistory.isEmpty {
+ if self.conversationHistory.isEmpty {
let rewritePrompt = """
Here is the text to rewrite:
@@ -72,42 +72,42 @@ final class RewriteModeService: ObservableObject {
Rewrite the text according to the instruction. Output ONLY the rewritten text, nothing else.
"""
- conversationHistory.append(Message(role: .user, content: rewritePrompt))
+ self.conversationHistory.append(Message(role: .user, content: rewritePrompt))
} else {
// Follow-up request
- conversationHistory.append(Message(
+ self.conversationHistory.append(Message(
role: .user,
content: "Follow-up instruction: \(prompt)\n\nApply this to the previous result. Output ONLY the updated text."
))
}
}
- guard !conversationHistory.isEmpty else { return }
+ guard !self.conversationHistory.isEmpty else { return }
- isProcessing = true
+ self.isProcessing = true
do {
let response = try await callLLM(messages: conversationHistory, isWriteMode: isWriteMode)
- conversationHistory.append(Message(role: .assistant, content: response))
- rewrittenText = response
- isProcessing = false
+ self.conversationHistory.append(Message(role: .assistant, content: response))
+ self.rewrittenText = response
+ self.isProcessing = false
} catch {
- conversationHistory.append(Message(role: .assistant, content: "Error: \(error.localizedDescription)"))
- isProcessing = false
+ self.conversationHistory.append(Message(role: .assistant, content: "Error: \(error.localizedDescription)"))
+ self.isProcessing = false
}
}
func acceptRewrite() {
- guard !rewrittenText.isEmpty else { return }
+ guard !self.rewrittenText.isEmpty else { return }
NSApp.hide(nil) // Restore focus to the previous app
- typingService.typeTextInstantly(rewrittenText)
+ self.typingService.typeTextInstantly(self.rewrittenText)
}
func clearState() {
- originalText = ""
- rewrittenText = ""
- conversationHistory = []
- isWriteMode = false
+ self.originalText = ""
+ self.rewrittenText = ""
+ self.conversationHistory = []
+ self.isWriteMode = false
}
// MARK: - LLM Integration
@@ -219,7 +219,7 @@ final class RewriteModeService: ObservableObject {
if enableStreaming {
DebugLogger.shared.info("Using STREAMING mode for Write/Rewrite", source: "RewriteModeService")
- return try await processStreamingResponse(request: request)
+ return try await self.processStreamingResponse(request: request)
} else {
let (data, response) = try await URLSession.shared.data(for: request)
@@ -285,7 +285,7 @@ final class RewriteModeService: ObservableObject {
{
fullContent += content
// Update UI in real-time for streaming feedback
- rewrittenText = fullContent
+ self.rewrittenText = fullContent
}
}
diff --git a/Sources/Fluid/Services/SimpleUpdater.swift b/Sources/Fluid/Services/SimpleUpdater.swift
index 613c05b9..4b76aaac 100644
--- a/Sources/Fluid/Services/SimpleUpdater.swift
+++ b/Sources/Fluid/Services/SimpleUpdater.swift
@@ -106,12 +106,12 @@ final class SimpleUpdater {
}
let currentVersionString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0"
- let current = parseVersion(currentVersionString)
+ let current = self.parseVersion(currentVersionString)
let latestTag = latest.tag_name
- let latestVersion = parseVersion(latestTag)
+ let latestVersion = self.parseVersion(latestTag)
// Return whether update is available
- return (isVersion(latestVersion, greaterThan: current), latestTag)
+ return (self.isVersion(latestVersion, greaterThan: current), latestTag)
}
func checkAndUpdate(owner: String, repo: String) async throws {
@@ -137,17 +137,17 @@ final class SimpleUpdater {
}
let currentVersionString = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "0.0.0"
- let current = parseVersion(currentVersionString)
+ let current = self.parseVersion(currentVersionString)
let latestTag = latest.tag_name
- let latestVersion = parseVersion(latestTag)
+ let latestVersion = self.parseVersion(latestTag)
// up to date
- if !isVersion(latestVersion, greaterThan: current) {
+ if !self.isVersion(latestVersion, greaterThan: current) {
throw PMKError.cancelled // mimic AppUpdater semantics for up-to-date
}
// Find asset matching: "{repo-lower}-{version-no-v}.*" and zip preferred
- let verString = versionString(latestVersion)
+ let verString = self.versionString(latestVersion)
let prefix = "\(repo.lowercased())-\(verString)"
let asset = latest.assets.first { asset in
let base = (asset.name as NSString).deletingPathExtension.lowercased()
@@ -178,7 +178,7 @@ final class SimpleUpdater {
// unzip
let extractedBundleURL: URL
do {
- extractedBundleURL = try await unzip(at: downloadURL)
+ extractedBundleURL = try await self.unzip(at: downloadURL)
} catch {
throw SimpleUpdateError.unzipFailed
}
@@ -220,7 +220,7 @@ final class SimpleUpdater {
let sameTeam = (curTeam != nil && curTeam == newTeam)
let bothAllowed: Bool
if let curTeam, let newTeam {
- bothAllowed = allowedTeamIDs.contains(curTeam) && allowedTeamIDs.contains(newTeam)
+ bothAllowed = self.allowedTeamIDs.contains(curTeam) && self.allowedTeamIDs.contains(newTeam)
} else {
bothAllowed = false
}
@@ -233,7 +233,7 @@ final class SimpleUpdater {
#endif
// Replace and relaunch
- try performSwapAndRelaunch(installedAppURL: currentBundle.bundleURL, downloadedAppURL: extractedBundleURL)
+ try self.performSwapAndRelaunch(installedAppURL: currentBundle.bundleURL, downloadedAppURL: extractedBundleURL)
}
// MARK: - Helpers
diff --git a/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift b/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift
index a2433ff6..d0c0eca4 100644
--- a/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift
+++ b/Sources/Fluid/Services/ThreadSafeAudioBuffer.swift
@@ -8,37 +8,37 @@ final class ThreadSafeAudioBuffer {
/// Appends new samples to the buffer in a thread-safe manner
func append(_ newSamples: [Float]) {
- lock.lock()
+ self.lock.lock()
defer { lock.unlock() }
- buffer.append(contentsOf: newSamples)
+ self.buffer.append(contentsOf: newSamples)
}
/// Clears the buffer, optionally keeping capacity to optimize for reuse
func clear(keepingCapacity: Bool = false) {
- lock.lock()
+ self.lock.lock()
defer { lock.unlock() }
- buffer.removeAll(keepingCapacity: keepingCapacity)
+ self.buffer.removeAll(keepingCapacity: keepingCapacity)
}
/// Returns the current number of samples
var count: Int {
- lock.lock()
+ self.lock.lock()
defer { lock.unlock() }
- return buffer.count
+ return self.buffer.count
}
/// Returns a copy of the prefix of the buffer (thread-safe)
func getPrefix(_ length: Int) -> [Float] {
- lock.lock()
+ self.lock.lock()
defer { lock.unlock() }
let safeLength = min(length, buffer.count)
- return Array(buffer[0..<safeLength])
+ return Array(self.buffer[0..<safeLength])
}
/// Returns a copy of the entire buffer
func getAll() -> [Float] {
- lock.lock()
+ self.lock.lock()
defer { lock.unlock() }
- return buffer
+ return self.buffer
}
}
diff --git a/Sources/Fluid/Services/TypingService.swift b/Sources/Fluid/Services/TypingService.swift
index b3f018c6..8d2445c8 100644
--- a/Sources/Fluid/Services/TypingService.swift
+++ b/Sources/Fluid/Services/TypingService.swift
@@ -16,29 +16,29 @@ final class TypingService {
private var isCurrentlyTyping = false
func typeTextInstantly(_ text: String) {
- log("[TypingService] ENTRY: typeTextInstantly called with text length: \(text.count)")
- log("[TypingService] Text preview: \"\(String(text.prefix(100)))\"")
+ self.log("[TypingService] ENTRY: typeTextInstantly called with text length: \(text.count)")
+ self.log("[TypingService] Text preview: \"\(String(text.prefix(100)))\"")
guard text.isEmpty == false else {
- log("[TypingService] ERROR: Empty text provided, aborting")
+ self.log("[TypingService] ERROR: Empty text provided, aborting")
return
}
// Prevent concurrent typing operations
- guard !isCurrentlyTyping else {
- log("[TypingService] WARNING: Skipping text injection - already in progress")
+ guard !self.isCurrentlyTyping else {
+ self.log("[TypingService] WARNING: Skipping text injection - already in progress")
return
}
// Check accessibility permissions first
guard AXIsProcessTrusted() else {
- log("[TypingService] ERROR: Accessibility permissions required for text injection")
- log("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")
+ self.log("[TypingService] ERROR: Accessibility permissions required for text injection")
+ self.log("[TypingService] Current accessibility status: \(AXIsProcessTrusted())")
return
}
- log("[TypingService] Accessibility check passed, proceeding with text injection")
- isCurrentlyTyping = true
+ self.log("[TypingService] Accessibility check passed, proceeding with text injection")
+ self.isCurrentlyTyping = true
DispatchQueue.global(qos: .userInitiated).async {
defer {
@@ -55,94 +55,94 @@ final class TypingService {
}
private func insertTextInstantly(_ text: String) {
- log("[TypingService] insertTextInstantly called with \(text.count) characters")
- log("[TypingService] Attempting to type text: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"")
+ self.log("[TypingService] insertTextInstantly called with \(text.count) characters")
+ self.log("[TypingService] Attempting to type text: \"\(text.prefix(50))\(text.count > 50 ? "..." : "")\"")
// Get frontmost app info
if let frontApp = NSWorkspace.shared.frontmostApplication {
- log("[TypingService] Target app: \(frontApp.localizedName ?? "Unknown") (\(frontApp.bundleIdentifier ?? "Unknown"))")
+ self.log("[TypingService] Target app: \(frontApp.localizedName ?? "Unknown") (\(frontApp.bundleIdentifier ?? "Unknown"))")
} else {
- log("[TypingService] WARNING: Could not get frontmost application")
+ self.log("[TypingService] WARNING: Could not get frontmost application")
}
// Check if we have permission to create events
- log("[TypingService] Accessibility trusted: \(AXIsProcessTrusted())")
+ self.log("[TypingService] Accessibility trusted: \(AXIsProcessTrusted())")
// Try direct bulk CGEvent insertion (NO CLIPBOARD)
- log("[TypingService] Trying INSTANT bulk CGEvent insertion (no clipboard)")
- if insertTextBulkInstant(text) {
- log("[TypingService] SUCCESS: Instant bulk CGEvent completed")
+ self.log("[TypingService] Trying INSTANT bulk CGEvent insertion (no clipboard)")
+ if self.insertTextBulkInstant(text) {
+ self.log("[TypingService] SUCCESS: Instant bulk CGEvent completed")
} else {
- log("[TypingService] FAILED: Bulk CGEvent, trying character-by-character")
+ self.log("[TypingService] FAILED: Bulk CGEvent, trying character-by-character")
// Fallback to character-by-character if bulk fails
for (index, char) in text.enumerated() {
if index % 10 == 0 { // Log every 10th character to avoid spam
- log("[TypingService] Typing character \(index + 1)/\(text.count): '\(char)'")
+ self.log("[TypingService] Typing character \(index + 1)/\(text.count): '\(char)'")
}
- typeCharacter(char)
+ self.typeCharacter(char)
usleep(1000) // Small delay between characters (1ms)
}
- log("[TypingService] Character-by-character typing completed")
+ self.log("[TypingService] Character-by-character typing completed")
}
}
private func insertTextBulkInstant(_ text: String) -> Bool {
- log("[TypingService] Starting INSTANT bulk CGEvent insertion (NO CLIPBOARD)")
+ self.log("[TypingService] Starting INSTANT bulk CGEvent insertion (NO CLIPBOARD)")
// Create single CGEvent with entire text - truly instant
guard let event = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true) else {
- log("[TypingService] ERROR: Failed to create bulk CGEvent")
+ self.log("[TypingService] ERROR: Failed to create bulk CGEvent")
return false
}
// Convert entire text to UTF16
let utf16Array = Array(text.utf16)
- log("[TypingService] Converting \(text.count) characters to single CGEvent")
+ self.log("[TypingService] Converting \(text.count) characters to single CGEvent")
// Set the entire text as unicode string
event.keyboardSetUnicodeString(stringLength: utf16Array.count, unicodeString: utf16Array)
// Post single event - INSTANT insertion
event.post(tap: .cghidEventTap)
- log("[TypingService] Posted single CGEvent with entire text - INSTANT!")
+ self.log("[TypingService] Posted single CGEvent with entire text - INSTANT!")
return true
}
private func insertTextViaAccessibility(_ text: String) -> Bool {
- log("[TypingService] Starting Accessibility API insertion")
+ self.log("[TypingService] Starting Accessibility API insertion")
// Try multiple strategies to find text input element
// Strategy 1: Get focused element directly
- log("[TypingService] Strategy 1: Getting focused UI element...")
+ self.log("[TypingService] Strategy 1: Getting focused UI element...")
if let textElement = getFocusedTextElement() {
- log("[TypingService] Found focused text element")
- if tryAllTextInsertionMethods(textElement, text) {
+ self.log("[TypingService] Found focused text element")
+ if self.tryAllTextInsertionMethods(textElement, text) {
return true
}
}
// Strategy 2: Traverse frontmost app UI hierarchy to find text elements
- log("[TypingService] Strategy 2: Traversing app UI hierarchy...")
+ self.log("[TypingService] Strategy 2: Traversing app UI hierarchy...")
if let textElement = findTextElementInFrontmostApp() {
- log("[TypingService] Found text element in app hierarchy")
- if tryAllTextInsertionMethods(textElement, text) {
+ self.log("[TypingService] Found text element in app hierarchy")
+ if self.tryAllTextInsertionMethods(textElement, text) {
return true
}
}
// Strategy 3: Find element with keyboard focus
- log("[TypingService] Strategy 3: Looking for keyboard focus...")
+ self.log("[TypingService] Strategy 3: Looking for keyboard focus...")
if let textElement = findKeyboardFocusedElement() {
- log("[TypingService] Found keyboard focused element")
- if tryAllTextInsertionMethods(textElement, text) {
+ self.log("[TypingService] Found keyboard focused element")
+ if self.tryAllTextInsertionMethods(textElement, text) {
return true
}
}
- log("[TypingService] All Accessibility API strategies failed")
+ self.log("[TypingService] All Accessibility API strategies failed")
return false
}
@@ -160,11 +160,11 @@ final class TypingService {
guard CFGetTypeID(focusedElement) == AXUIElementGetTypeID() else { return nil }
let axElement = unsafeBitCast(focusedElement, to: AXUIElement.self)
if let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {
- log("[TypingService] Found focused element with role: \(role)")
+ self.log("[TypingService] Found focused element with role: \(role)")
return axElement
}
} else {
- log("[TypingService] Could not get focused UI element - result: \(result.rawValue)")
+ self.log("[TypingService] Could not get focused UI element - result: \(result.rawValue)")
}
return nil
@@ -172,12 +172,12 @@ final class TypingService {
private func findTextElementInFrontmostApp() -> AXUIElement? {
guard let frontmostApp = NSWorkspace.shared.frontmostApplication else {
- log("[TypingService] Could not get frontmost app")
+ self.log("[TypingService] Could not get frontmost app")
return nil
}
let appElement = AXUIElementCreateApplication(frontmostApp.processIdentifier)
- return findTextElementRecursively(appElement, depth: 0, maxDepth: 8)
+ return self.findTextElementRecursively(appElement, depth: 0, maxDepth: 8)
}
private func findTextElementRecursively(_ element: AXUIElement, depth: Int, maxDepth: Int) -> AXUIElement? {
@@ -187,7 +187,7 @@ final class TypingService {
if let role = getElementAttribute(element, kAXRoleAttribute as CFString) {
let textRoles = ["AXTextField", "AXTextArea", "AXComboBox", "AXSearchField", "AXStaticText"]
if textRoles.contains(role) {
- log("[TypingService] Found text element at depth \(depth) with role: \(role)")
+ self.log("[TypingService] Found text element at depth \(depth) with role: \(role)")
return element
}
}
@@ -223,7 +223,7 @@ final class TypingService {
guard CFGetTypeID(focusedElement) == AXUIElementGetTypeID() else { return nil }
let axElement = unsafeBitCast(focusedElement, to: AXUIElement.self)
if let role = getElementAttribute(axElement, kAXRoleAttribute as CFString) {
- log("[TypingService] Found app-level focused element with role: \(role)")
+ self.log("[TypingService] Found app-level focused element with role: \(role)")
return axElement
}
}
@@ -234,26 +234,26 @@ final class TypingService {
private func tryAllTextInsertionMethods(_ element: AXUIElement, _ text: String) -> Bool {
// Get element info for debugging
if let role = getElementAttribute(element, kAXRoleAttribute as CFString) {
- log("[TypingService] Trying insertion on element with role: \(role)")
+ self.log("[TypingService] Trying insertion on element with role: \(role)")
if let title = getElementAttribute(element, kAXTitleAttribute as CFString) {
- log("[TypingService] Element title: \(title)")
+ self.log("[TypingService] Element title: \(title)")
}
}
// Try multiple approaches for text insertion
- log("[TypingService] Trying approach 1: Direct kAXValueAttribute")
- if setTextViaValue(element, text) {
+ self.log("[TypingService] Trying approach 1: Direct kAXValueAttribute")
+ if self.setTextViaValue(element, text) {
return true
}
- log("[TypingService] Trying approach 2: kAXSelectedTextAttribute (replace selection)")
- if setTextViaSelection(element, text) {
+ self.log("[TypingService] Trying approach 2: kAXSelectedTextAttribute (replace selection)")
+ if self.setTextViaSelection(element, text) {
return true
}
- log("[TypingService] Trying approach 3: Insert text at insertion point")
- if insertTextAtInsertionPoint(element, text) {
+ self.log("[TypingService] Trying approach 3: Insert text at insertion point")
+ if self.insertTextAtInsertionPoint(element, text) {
return true
}
@@ -275,10 +275,10 @@ final class TypingService {
let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, cfText)
if result == .success {
- log("[TypingService] SUCCESS: Set text via kAXValueAttribute")
+ self.log("[TypingService] SUCCESS: Set text via kAXValueAttribute")
return true
} else {
- log("[TypingService] FAILED: kAXValueAttribute - error: \(result.rawValue)")
+ self.log("[TypingService] FAILED: kAXValueAttribute - error: \(result.rawValue)")
return false
}
}
@@ -290,17 +290,17 @@ final class TypingService {
kAXSelectedTextAttribute as CFString,
"" as CFString
)
- log("[TypingService] Select all result: \(selectAllResult.rawValue)")
+ self.log("[TypingService] Select all result: \(selectAllResult.rawValue)")
// Then replace the selection with our text
let cfText = text as CFString
let result = AXUIElementSetAttributeValue(element, kAXSelectedTextAttribute as CFString, cfText)
if result == .success {
- log("[TypingService] SUCCESS: Set text via kAXSelectedTextAttribute")
+ self.log("[TypingService] SUCCESS: Set text via kAXSelectedTextAttribute")
return true
} else {
- log("[TypingService] FAILED: kAXSelectedTextAttribute - error: \(result.rawValue)")
+ self.log("[TypingService] FAILED: kAXSelectedTextAttribute - error: \(result.rawValue)")
return false
}
}
@@ -313,52 +313,52 @@ final class TypingService {
kAXInsertionPointLineNumberAttribute as CFString,
&insertionPoint
)
- log("[TypingService] Get insertion point result: \(getResult.rawValue)")
+ self.log("[TypingService] Get insertion point result: \(getResult.rawValue)")
// Try to insert text using parameterized attribute
let cfText = text as CFString
let result = AXUIElementSetAttributeValue(element, kAXValueAttribute as CFString, cfText)
if result == .success {
- log("[TypingService] SUCCESS: Inserted text at insertion point")
+ self.log("[TypingService] SUCCESS: Inserted text at insertion point")
return true
} else {
- log("[TypingService] FAILED: Insertion point method - error: \(result.rawValue)")
+ self.log("[TypingService] FAILED: Insertion point method - error: \(result.rawValue)")
return false
}
}
private func insertTextBulk(_ text: String) -> Bool {
- log("[TypingService] Starting bulk CGEvent insertion")
+ self.log("[TypingService] Starting bulk CGEvent insertion")
// Get the frontmost application's PID for targeted event posting
guard let frontApp = NSWorkspace.shared.frontmostApplication else {
- log("[TypingService] ERROR: Could not get frontmost application for bulk insertion")
+ self.log("[TypingService] ERROR: Could not get frontmost application for bulk insertion")
return false
}
let targetPID = frontApp.processIdentifier
- log("[TypingService] Targeting PID \(targetPID) for bulk insertion")
+ self.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: " ")
- log("[TypingService] Splitting text into \(words.count) words for bulk insertion")
+ self.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 word
- if !insertWordViaCGEvent(wordToType, targetPID: targetPID) {
- log("[TypingService] Failed to insert word \(index + 1): '\(word)', falling back to character method")
+ if !self.insertWordViaCGEvent(wordToType, targetPID: targetPID) {
+ self.log("[TypingService] Failed to insert word \(index + 1): '\(word)', falling back to character method")
return false
}
if index % 5 == 0 && index > 0 {
- log("[TypingService] Bulk insertion progress: \(index + 1)/\(words.count) words")
+ self.log("[TypingService] Bulk insertion progress: \(index + 1)/\(words.count) words")
}
}
- log("[TypingService] Successfully completed bulk word-by-word insertion")
+ self.log("[TypingService] Successfully completed bulk word-by-word insertion")
return true
}
@@ -370,7 +370,7 @@ final class TypingService {
guard let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
else {
- log("[TypingService] ERROR: Failed to create CGEvents for word: '\(word)'")
+ self.log("[TypingService] ERROR: Failed to create CGEvents for word: '\(word)'")
return false
}
@@ -394,7 +394,7 @@ final class TypingService {
guard let keyDownEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: true),
let keyUpEvent = CGEvent(keyboardEventSource: nil, virtualKey: 0, keyDown: false)
else {
- log("[TypingService] ERROR: Failed to create CGEvents for character: \(char)")
+ self.log("[TypingService] ERROR: Failed to create CGEvents for character: \(char)")
return
}
diff --git a/Sources/Fluid/Services/WhisperProvider.swift b/Sources/Fluid/Services/WhisperProvider.swift
index d654a06e..3e1d2a07 100644
--- a/Sources/Fluid/Services/WhisperProvider.swift
+++ b/Sources/Fluid/Services/WhisperProvider.swift
@@ -25,46 +25,46 @@ final class WhisperProvider: TranscriptionProvider {
private var modelURL: URL {
let cacheDir = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first
?? FileManager.default.temporaryDirectory
- return cacheDir.appendingPathComponent("WhisperModels").appendingPathComponent(modelName)
+ return cacheDir.appendingPathComponent("WhisperModels").appendingPathComponent(self.modelName)
}
private var modelDirectory: URL {
- modelURL.deletingLastPathComponent()
+ self.modelURL.deletingLastPathComponent()
}
func prepare(progressHandler: ((Double) -> Void)? = nil) async throws {
// Detect model change: if a different model is now selected, force reload
- let currentModelName = modelName
- if isReady, loadedModelName != currentModelName {
+ let currentModelName = self.modelName
+ if self.isReady, self.loadedModelName != currentModelName {
DebugLogger.shared
.info(
- "WhisperProvider: Model changed from \(loadedModelName ?? "nil") to \(currentModelName), forcing reload",
+ "WhisperProvider: Model changed from \(self.loadedModelName ?? "nil") to \(currentModelName), forcing reload",
source: "WhisperProvider"
)
- isReady = false
- whisper = nil
- loadedModelName = nil
+ self.isReady = false
+ self.whisper = nil
+ self.loadedModelName = nil
}
- guard isReady == false else { return }
+ guard self.isReady == false else { return }
DebugLogger.shared.info("WhisperProvider: Starting model preparation", source: "WhisperProvider")
// Ensure model directory exists
- try FileManager.default.createDirectory(at: modelDirectory, withIntermediateDirectories: true)
+ try FileManager.default.createDirectory(at: self.modelDirectory, withIntermediateDirectories: true)
// Download model if not present
- if !FileManager.default.fileExists(atPath: modelURL.path) {
+ if !FileManager.default.fileExists(atPath: self.modelURL.path) {
DebugLogger.shared.info("WhisperProvider: Downloading Whisper model...", source: "WhisperProvider")
- try await downloadModel(progressHandler: progressHandler)
+ try await self.downloadModel(progressHandler: progressHandler)
}
// Load the model
DebugLogger.shared.info("WhisperProvider: Loading Whisper model...", source: "WhisperProvider")
- whisper = Whisper(fromFileURL: modelURL)
+ self.whisper = Whisper(fromFileURL: self.modelURL)
- loadedModelName = currentModelName
- isReady = true
+ self.loadedModelName = currentModelName
+ self.isReady = true
DebugLogger.shared.info("WhisperProvider: Model ready (\(currentModelName))", source: "WhisperProvider")
}
@@ -89,16 +89,16 @@ final class WhisperProvider: TranscriptionProvider {
}
func modelsExistOnDisk() -> Bool {
- return FileManager.default.fileExists(atPath: modelURL.path)
+ return FileManager.default.fileExists(atPath: self.modelURL.path)
}
func clearCache() async throws {
- if FileManager.default.fileExists(atPath: modelDirectory.path) {
- try FileManager.default.removeItem(at: modelDirectory)
+ if FileManager.default.fileExists(atPath: self.modelDirectory.path) {
+ try FileManager.default.removeItem(at: self.modelDirectory)
}
- isReady = false
- whisper = nil
- loadedModelName = nil
+ self.isReady = false
+ self.whisper = nil
+ self.loadedModelName = nil
}
// MARK: - Model Download
@@ -139,10 +139,10 @@ final class WhisperProvider: TranscriptionProvider {
}
// Move to final location
- if FileManager.default.fileExists(atPath: modelURL.path) {
- try FileManager.default.removeItem(at: modelURL)
+ if FileManager.default.fileExists(atPath: self.modelURL.path) {
+ try FileManager.default.removeItem(at: self.modelURL)
}
- try FileManager.default.moveItem(at: tempURL, to: modelURL)
+ try FileManager.default.moveItem(at: tempURL, to: self.modelURL)
DebugLogger.shared.info("WhisperProvider: Model downloaded successfully", source: "WhisperProvider")
} catch let error as NSError {
diff --git a/Sources/Fluid/TalkingAnimations.swift b/Sources/Fluid/TalkingAnimations.swift
index 78aec8f7..3885bb30 100644
--- a/Sources/Fluid/TalkingAnimations.swift
+++ b/Sources/Fluid/TalkingAnimations.swift
@@ -11,21 +11,21 @@ class ActiveAppTracker: ObservableObject {
private var timer: Timer?
init() {
- updateActiveApp()
- startTracking()
+ self.updateActiveApp()
+ self.startTracking()
}
private func startTracking() {
// Reduced frequency for app tracking - 2 FPS is sufficient for app name updates
- timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { _ in
+ self.timer = Timer.scheduledTimer(withTimeInterval: 2.0, repeats: true) { _ in
self.updateActiveApp()
}
}
private func updateActiveApp() {
if let frontmostApp = NSWorkspace.shared.frontmostApplication {
- activeAppName = frontmostApp.localizedName ?? "Unknown App"
- activeWindowTitle = fetchFrontmostWindowTitle(for: frontmostApp.processIdentifier) ?? ""
+ self.activeAppName = frontmostApp.localizedName ?? "Unknown App"
+ self.activeWindowTitle = self.fetchFrontmostWindowTitle(for: frontmostApp.processIdentifier) ?? ""
}
}
@@ -85,7 +85,7 @@ struct TalkingAudioVisualizationView: View {
// Dynamic config that updates with settings
private var config: TalkingAnimationConfig {
- TalkingAnimationConfig(noiseThreshold: dynamicNoiseThreshold)
+ TalkingAnimationConfig(noiseThreshold: self.dynamicNoiseThreshold)
}
init(audioLevelPublisher: AnyPublisher<CGFloat, Never>) {
@@ -94,9 +94,9 @@ struct TalkingAudioVisualizationView: View {
var body: some View {
SpokenlyWaveform(
- config: config,
- audioLevel: data.audioLevel,
- isActive: data.audioLevel > config.noiseThreshold
+ config: self.config,
+ audioLevel: self.data.audioLevel,
+ isActive: self.data.audioLevel > self.config.noiseThreshold
)
.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in
// Update threshold when UserDefaults changes
@@ -126,7 +126,7 @@ struct SpokenlyWaveform: View {
.autoconnect() // 30 FPS base timer - safer for CoreML concurrency
var body: some View {
- HStack(spacing: config.barSpacing) {
+ HStack(spacing: self.config.barSpacing) {
ForEach(0..<self.config.barCount, id: \.self) { index in
SpokenlyBar(
height: index < self.barHeights.count ? self.barHeights[index] : self.config.minBarHeight,
@@ -137,7 +137,7 @@ struct SpokenlyWaveform: View {
)
}
}
- .frame(width: config.containerWidth, height: config.containerHeight)
+ .frame(width: self.config.containerWidth, height: self.config.containerHeight)
.onAppear {
self.initializeBars()
self.isViewVisible = true
@@ -145,7 +145,7 @@ struct SpokenlyWaveform: View {
.onDisappear {
self.isViewVisible = false
}
- .onReceive(animationTimer) { _ in
+ .onReceive(self.animationTimer) { _ in
if self.isViewVisible {
self.updateBars()
}
@@ -153,49 +153,49 @@ struct SpokenlyWaveform: View {
}
private func initializeBars() {
- barHeights = Array(repeating: config.minBarHeight, count: config.barCount)
- barOpacities = Array(repeating: 0.4, count: config.barCount)
- animationPhases = (0..<config.barCount).map { _ in Double.random(in: 0...2 * Double.pi) }
+ self.barHeights = Array(repeating: self.config.minBarHeight, count: self.config.barCount)
+ self.barOpacities = Array(repeating: 0.4, count: self.config.barCount)
+ self.animationPhases = (0..<self.config.barCount).map { _ in Double.random(in: 0...2 * Double.pi) }
}
private func updateBars() {
let currentTime = Date().timeIntervalSince1970
// Adaptive frame limiting - reduce rate during active processing to prevent CoreML conflicts
- let targetFPS: Double = isActive ? 30.0 : 20.0 // Lower FPS to reduce state update conflicts
+ let targetFPS: Double = self.isActive ? 30.0 : 20.0 // Lower FPS to reduce state update conflicts
let frameTime = 1.0 / targetFPS
- if currentTime - lastUpdateTime < frameTime { return }
- lastUpdateTime = currentTime
+ if currentTime - self.lastUpdateTime < frameTime { return }
+ self.lastUpdateTime = currentTime
// Safety check
- guard barHeights.count == config.barCount,
- barOpacities.count == config.barCount else { return }
+ guard self.barHeights.count == self.config.barCount,
+ self.barOpacities.count == self.config.barCount else { return }
// Direct real-time animation based on current audio level
- if audioLevel <= config.noiseThreshold { // USE THE USER-CONTROLLABLE THRESHOLD!
+ if self.audioLevel <= self.config.noiseThreshold { // USE THE USER-CONTROLLABLE THRESHOLD!
// Complete stillness
- for i in 0..<min(config.barCount, barHeights.count) {
- barHeights[i] = config.minBarHeight
- barOpacities[i] = 0.3
+ for i in 0..<min(self.config.barCount, self.barHeights.count) {
+ self.barHeights[i] = self.config.minBarHeight
+ self.barOpacities[i] = 0.3
}
} else {
// Real-time responsive animation
let audioInfluence = Double(audioLevel) * 2.0
- for i in 0..<min(config.barCount, barHeights.count) {
+ for i in 0..<min(self.config.barCount, self.barHeights.count) {
// Fast frequency for immediate response
let frequency = 3.0 + Double(i) * 0.4
- let phase = animationPhases[i]
+ let phase = self.animationPhases[i]
let waveValue = sin(currentTime * frequency + phase)
let normalizedWave = (waveValue + 1) / 2
// Direct audio-responsive calculation
let heightMultiplier = normalizedWave * audioInfluence + 0.2
- let heightRange = config.maxBarHeight - config.minBarHeight
- let newHeight = config.minBarHeight + heightRange * CGFloat(min(heightMultiplier, 1.0))
+ let heightRange = self.config.maxBarHeight - self.config.minBarHeight
+ let newHeight = self.config.minBarHeight + heightRange * CGFloat(min(heightMultiplier, 1.0))
- barHeights[i] = newHeight
- barOpacities[i] = 0.6 + (audioInfluence * 0.4)
+ self.barHeights[i] = newHeight
+ self.barOpacities[i] = 0.6 + (audioInfluence * 0.4)
}
}
}
@@ -226,7 +226,7 @@ struct EnhancedTalkingAudioVisualizationView: View {
// Dynamic config that updates with settings
private var config: EnhancedTalkingAnimationConfig {
- EnhancedTalkingAnimationConfig(noiseThreshold: dynamicNoiseThreshold)
+ EnhancedTalkingAnimationConfig(noiseThreshold: self.dynamicNoiseThreshold)
}
init(audioLevelPublisher: AnyPublisher<CGFloat, Never>) {
@@ -234,7 +234,7 @@ struct EnhancedTalkingAudioVisualizationView: View {
}
var body: some View {
- HStack(spacing: config.particleSpacing) {
+ HStack(spacing: self.config.particleSpacing) {
ForEach(0..<self.config.particleCount, id: \.self) { index in
PremiumTalkingParticle(
audioLevel: self.data.audioLevel,
@@ -243,8 +243,8 @@ struct EnhancedTalkingAudioVisualizationView: View {
)
}
}
- .frame(width: CGFloat(config.particleCount) * (config.maxParticleSize + config.particleSpacing) -
- config.particleSpacing)
+ .frame(width: CGFloat(self.config.particleCount) * (self.config.maxParticleSize + self.config.particleSpacing) -
+ self.config.particleSpacing)
.onReceive(NotificationCenter.default.publisher(for: UserDefaults.didChangeNotification)) { _ in
// Update threshold when UserDefaults changes
let newThreshold = CGFloat(SettingsStore.shared.visualizerNoiseThreshold)
@@ -271,24 +271,24 @@ struct PremiumTalkingParticle: View {
private let particleTimer = Timer.publish(every: 0.033, on: .main, in: .common).autoconnect() // 30 FPS
private var isActive: Bool {
- audioLevel > config.noiseThreshold
+ self.audioLevel > self.config.noiseThreshold
}
private var particleSize: CGFloat {
- if !isActive { return config.minParticleSize }
+ if !self.isActive { return self.config.minParticleSize }
- let waveValue = sin(animationPhase + Double(index) * 0.8 + randomOffset)
+ let waveValue = sin(animationPhase + Double(self.index) * 0.8 + self.randomOffset)
let normalizedWave = (waveValue + 1) / 2
let audioMultiplier = pow(audioLevel, 0.6) * 1.5
- let sizeRange = config.maxParticleSize - config.minParticleSize
+ let sizeRange = self.config.maxParticleSize - self.config.minParticleSize
- return config.minParticleSize + (sizeRange * CGFloat(normalizedWave) * min(audioMultiplier, 1.0))
+ return self.config.minParticleSize + (sizeRange * CGFloat(normalizedWave) * min(audioMultiplier, 1.0))
}
private var particleOpacity: Double {
- if !isActive { return config.baseOpacity }
- let opacityRange = config.maxOpacity - config.baseOpacity
- return config.baseOpacity + (opacityRange * Double(audioLevel))
+ if !self.isActive { return self.config.baseOpacity }
+ let opacityRange = self.config.maxOpacity - self.config.baseOpacity
+ return self.config.baseOpacity + (opacityRange * Double(self.audioLevel))
}
var body: some View {
@@ -342,9 +342,9 @@ struct PremiumTalkingParticle: View {
.shadow(color: Color.purple.opacity(0.4), radius: 4, x: 0, y: 2)
.shadow(color: Color.indigo.opacity(0.3), radius: 8, x: 0, y: 0)
}
- .animation(.easeInOut(duration: 0.12), value: particleSize)
- .animation(.easeInOut(duration: 0.15), value: particleOpacity)
- .onReceive(particleTimer) { _ in
+ .animation(.easeInOut(duration: 0.12), value: self.particleSize)
+ .animation(.easeInOut(duration: 0.15), value: self.particleOpacity)
+ .onReceive(self.particleTimer) { _ in
if self.isParticleVisible {
self.updateParticleAnimation()
}
@@ -361,23 +361,23 @@ struct PremiumTalkingParticle: View {
let currentTime = Date().timeIntervalSince1970
// Simple frame limiting for consistent 30 FPS
- if currentTime - lastParticleUpdateTime < 0.033 { return }
- lastParticleUpdateTime = currentTime
+ if currentTime - self.lastParticleUpdateTime < 0.033 { return }
+ self.lastParticleUpdateTime = currentTime
- animationTrigger += 1
+ self.animationTrigger += 1
// Real-time responsive animation
- if audioLevel <= config.noiseThreshold { // USE THE USER-CONTROLLABLE THRESHOLD!
+ if self.audioLevel <= self.config.noiseThreshold { // USE THE USER-CONTROLLABLE THRESHOLD!
// Complete stillness during silence
- pulseScale = 1.0
- if animationTrigger % 10 == 0 {
- rotationAngle += 0.2
+ self.pulseScale = 1.0
+ if self.animationTrigger % 10 == 0 {
+ self.rotationAngle += 0.2
}
} else {
// Fast, responsive animation
- animationPhase += 0.3 // Much faster phase changes
- rotationAngle += 1.5 // Faster rotation
- pulseScale = 1.0 + (audioLevel * 0.15) // More pronounced pulsing
+ self.animationPhase += 0.3 // Much faster phase changes
+ self.rotationAngle += 1.5 // Faster rotation
+ self.pulseScale = 1.0 + (self.audioLevel * 0.15) // More pronounced pulsing
}
}
}
@@ -392,10 +392,10 @@ struct SpokenlyBar: View {
let isActive: Bool
var body: some View {
- RoundedRectangle(cornerRadius: config.barWidth / 2)
+ RoundedRectangle(cornerRadius: self.config.barWidth / 2)
.fill(Color.white)
- .frame(width: config.barWidth, height: height)
- .opacity(opacity)
+ .frame(width: self.config.barWidth, height: self.height)
+ .opacity(self.opacity)
.shadow(color: Color.black.opacity(0.2), radius: 1, x: 0, y: 1)
}
}
diff --git a/Sources/Fluid/Theme/Components/SetupComponents.swift b/Sources/Fluid/Theme/Components/SetupComponents.swift
index 6f90df55..ec3b0341 100644
--- a/Sources/Fluid/Theme/Components/SetupComponents.swift
+++ b/Sources/Fluid/Theme/Components/SetupComponents.swift
@@ -95,12 +95,12 @@ struct SetupStepView: View {
)))
}
.buttonStyle(.plain)
- .disabled(status == .completed || !showActionButton)
- .opacity(status == .completed ? 0.9 : 1.0)
+ .disabled(self.status == .completed || !self.showActionButton)
+ .opacity(self.status == .completed ? 0.9 : 1.0)
}
private var statusColor: Color {
- switch status {
+ switch self.status {
case .completed: return .green
case .inProgress: return .blue
case .pending: return .secondary
diff --git a/Sources/Fluid/Theme/Components/ThemedCard.swift b/Sources/Fluid/Theme/Components/ThemedCard.swift
index 0cb5b298..0a15fdc6 100644
--- a/Sources/Fluid/Theme/Components/ThemedCard.swift
+++ b/Sources/Fluid/Theme/Components/ThemedCard.swift
@@ -31,33 +31,33 @@ struct ThemedCard<Content: View>: View {
let configuration = CardConfiguration(style: style, theme: theme)
let shape = RoundedRectangle(cornerRadius: configuration.cornerRadius, style: .continuous)
- content
- .padding(padding ?? 14)
+ self.content
+ .padding(self.padding ?? 14)
.background(configuration.material, in: shape)
.background(shape
.fill(configuration.background)
.overlay(shape
.stroke(
configuration.border
- .opacity(isHovered && hoverEffect ? configuration.hoverBorderOpacity : configuration
+ .opacity(self.isHovered && self.hoverEffect ? configuration.hoverBorderOpacity : configuration
.borderOpacity),
lineWidth: configuration.borderWidth
))
.shadow(
- color: configuration.shadow.color.opacity(isHovered && hoverEffect ? min(
+ color: configuration.shadow.color.opacity(self.isHovered && self.hoverEffect ? min(
configuration.shadow.opacity + configuration.hoverShadowBoost,
1.0
) : configuration.shadow.opacity),
radius: configuration.shadow.radius,
x: configuration.shadow.x,
- y: isHovered && hoverEffect ? configuration.shadow.y + 1 : configuration.shadow.y
+ y: self.isHovered && self.hoverEffect ? configuration.shadow.y + 1 : configuration.shadow.y
))
- .scaleEffect(isHovered && hoverEffect ? 1.01 : 1.0)
+ .scaleEffect(self.isHovered && self.hoverEffect ? 1.01 : 1.0)
.onHover { hovering in
guard self.hoverEffect else { return }
self.isHovered = hovering
}
- .animation(.easeOut(duration: 0.18), value: isHovered)
+ .animation(.easeOut(duration: 0.18), value: self.isHovered)
}
}
@@ -78,35 +78,35 @@ private extension ThemedCard {
init(style: ThemedCardStyle, theme: AppTheme) {
switch style {
case .standard:
- background = theme.palette.cardBackground
- border = theme.palette.cardBorder
- borderOpacity = 0.28
- hoverBorderOpacity = 0.5
- borderWidth = 1
- material = theme.materials.card
- cornerRadius = theme.metrics.corners.lg
- shadow = theme.metrics.cardShadow
- hoverShadowBoost = 0.12
+ self.background = theme.palette.cardBackground
+ self.border = theme.palette.cardBorder
+ self.borderOpacity = 0.28
+ self.hoverBorderOpacity = 0.5
+ self.borderWidth = 1
+ self.material = theme.materials.card
+ self.cornerRadius = theme.metrics.corners.lg
+ self.shadow = theme.metrics.cardShadow
+ self.hoverShadowBoost = 0.12
case .prominent:
- background = theme.palette.elevatedCardBackground
- border = theme.palette.accent
- borderOpacity = 0.25
- hoverBorderOpacity = 0.55
- borderWidth = 1.2
- material = theme.materials.elevatedCard
- cornerRadius = theme.metrics.corners.lg
- shadow = theme.metrics.elevatedCardShadow
- hoverShadowBoost = 0.15
+ self.background = theme.palette.elevatedCardBackground
+ self.border = theme.palette.accent
+ self.borderOpacity = 0.25
+ self.hoverBorderOpacity = 0.55
+ self.borderWidth = 1.2
+ self.material = theme.materials.elevatedCard
+ self.cornerRadius = theme.metrics.corners.lg
+ self.shadow = theme.metrics.elevatedCardShadow
+ self.hoverShadowBoost = 0.15
case .subtle:
- background = theme.palette.contentBackground
- border = theme.palette.cardBorder
- borderOpacity = 0.18
- hoverBorderOpacity = 0.32
- borderWidth = 0.8
- material = theme.materials.card
- cornerRadius = theme.metrics.corners.md
- shadow = theme.metrics.cardShadow
- hoverShadowBoost = 0.08
+ self.background = theme.palette.contentBackground
+ self.border = theme.palette.cardBorder
+ self.borderOpacity = 0.18
+ self.hoverBorderOpacity = 0.32
+ self.borderWidth = 0.8
+ self.material = theme.materials.card
+ self.cornerRadius = theme.metrics.corners.md
+ self.shadow = theme.metrics.cardShadow
+ self.hoverShadowBoost = 0.08
}
}
}
diff --git a/Sources/Fluid/Theme/Components/ThemedGroupBox.swift b/Sources/Fluid/Theme/Components/ThemedGroupBox.swift
index ae4fd6da..1933b94e 100644
--- a/Sources/Fluid/Theme/Components/ThemedGroupBox.swift
+++ b/Sources/Fluid/Theme/Components/ThemedGroupBox.swift
@@ -21,7 +21,7 @@ struct ThemedGroupBox<Label: View, Content: View>: View {
}
var body: some View {
- ThemedCard(style: style, padding: 0, hoverEffect: hoverEffect) {
+ ThemedCard(style: self.style, padding: 0, hoverEffect: self.hoverEffect) {
VStack(alignment: .leading, spacing: self.theme.metrics.spacing.md) {
self.label
.font(.headline)
diff --git a/Sources/Fluid/Theme/NativeButtonStyles.swift b/Sources/Fluid/Theme/NativeButtonStyles.swift
index 0bf48c31..f356af2b 100644
--- a/Sources/Fluid/Theme/NativeButtonStyles.swift
+++ b/Sources/Fluid/Theme/NativeButtonStyles.swift
@@ -13,39 +13,39 @@ struct GlassButtonStyle: ButtonStyle {
let configuration: ButtonStyle.Configuration
private var shape: RoundedRectangle {
- RoundedRectangle(cornerRadius: theme.metrics.corners.md, style: .continuous)
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.md, style: .continuous)
}
var body: some View {
- configuration.label
+ self.configuration.label
.fontWeight(.semibold)
- .padding(.horizontal, theme.metrics.spacing.lg)
- .padding(.vertical, theme.metrics.spacing.md)
+ .padding(.horizontal, self.theme.metrics.spacing.lg)
+ .padding(.vertical, self.theme.metrics.spacing.md)
.frame(minHeight: 36)
- .foregroundStyle(theme.palette.primaryText)
- .background(theme.materials.card, in: shape)
- .background(shape
- .fill(theme.palette.cardBackground)
- .overlay(shape.stroke(
- theme.palette.cardBorder.opacity(isHovered ? 0.45 : 0.25),
+ .foregroundStyle(self.theme.palette.primaryText)
+ .background(self.theme.materials.card, in: self.shape)
+ .background(self.shape
+ .fill(self.theme.palette.cardBackground)
+ .overlay(self.shape.stroke(
+ self.theme.palette.cardBorder.opacity(self.isHovered ? 0.45 : 0.25),
lineWidth: 1
)))
- .overlay(shape
- .stroke(theme.palette.accent.opacity(isHovered ? 0.25 : 0.1), lineWidth: 1)
+ .overlay(self.shape
+ .stroke(self.theme.palette.accent.opacity(self.isHovered ? 0.25 : 0.1), lineWidth: 1)
.blendMode(.plusLighter))
.shadow(
- color: theme.palette.cardBorder.opacity(isHovered ? 0.45 : 0.22),
- radius: isHovered ? theme.metrics.cardShadow
+ color: self.theme.palette.cardBorder.opacity(self.isHovered ? 0.45 : 0.22),
+ radius: self.isHovered ? self.theme.metrics.cardShadow
.radius : max(
- theme.metrics.cardShadow.radius - 3,
+ self.theme.metrics.cardShadow.radius - 3,
2
),
x: 0,
- y: isHovered ? theme.metrics.cardShadow.y : theme.metrics.cardShadow.y - 2
+ y: self.isHovered ? self.theme.metrics.cardShadow.y : self.theme.metrics.cardShadow.y - 2
)
- .scaleEffect(configuration.isPressed ? 0.97 : (isHovered ? 1.01 : 1.0))
- .animation(.spring(response: 0.18, dampingFraction: 0.78), value: isHovered)
- .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)
+ .scaleEffect(self.configuration.isPressed ? 0.97 : (self.isHovered ? 1.01 : 1.0))
+ .animation(.spring(response: 0.18, dampingFraction: 0.78), value: self.isHovered)
+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: self.configuration.isPressed)
.onHover { self.isHovered = $0 }
}
}
@@ -58,7 +58,7 @@ struct PremiumButtonStyle: ButtonStyle {
var height: CGFloat = 44
func makeBody(configuration: Configuration) -> some View {
- PrimaryButton(configuration: configuration, isRecording: isRecording, height: height)
+ PrimaryButton(configuration: configuration, isRecording: self.isRecording, height: self.height)
}
private struct PrimaryButton: View {
@@ -69,11 +69,11 @@ struct PremiumButtonStyle: ButtonStyle {
let height: CGFloat
private var shape: RoundedRectangle {
- RoundedRectangle(cornerRadius: theme.metrics.corners.lg, style: .continuous)
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg, style: .continuous)
}
private var baseGradient: LinearGradient {
- if isRecording {
+ if self.isRecording {
return LinearGradient(
colors: [
Color(nsColor: .systemRed),
@@ -86,8 +86,8 @@ struct PremiumButtonStyle: ButtonStyle {
return LinearGradient(
colors: [
- theme.palette.accent.opacity(0.95),
- theme.palette.accent.opacity(0.75),
+ self.theme.palette.accent.opacity(0.95),
+ self.theme.palette.accent.opacity(0.75),
],
startPoint: .topLeading,
endPoint: .bottomTrailing
@@ -95,31 +95,31 @@ struct PremiumButtonStyle: ButtonStyle {
}
var body: some View {
- configuration.label
+ self.configuration.label
.fontWeight(.semibold)
.frame(maxWidth: .infinity)
- .frame(height: height)
- .foregroundStyle(isRecording ? Color.white : theme.palette.primaryText)
- .background(shape
- .fill(baseGradient)
- .overlay(shape.stroke(
- Color.white.opacity(isHovered ? 0.35 : 0.2),
+ .frame(height: self.height)
+ .foregroundStyle(self.isRecording ? Color.white : self.theme.palette.primaryText)
+ .background(self.shape
+ .fill(self.baseGradient)
+ .overlay(self.shape.stroke(
+ Color.white.opacity(self.isHovered ? 0.35 : 0.2),
lineWidth: 1
)))
.shadow(
- color: (isRecording ? Color(nsColor: .systemRed) : theme.palette.accent)
- .opacity(isHovered ? 0.45 : 0.25),
- radius: isHovered ? theme.metrics.elevatedCardShadow
+ color: (self.isRecording ? Color(nsColor: .systemRed) : self.theme.palette.accent)
+ .opacity(self.isHovered ? 0.45 : 0.25),
+ radius: self.isHovered ? self.theme.metrics.elevatedCardShadow
.radius : max(
- theme.metrics.cardShadow.radius - 2,
+ self.theme.metrics.cardShadow.radius - 2,
2
),
x: 0,
- y: isHovered ? theme.metrics.elevatedCardShadow.y : theme.metrics.cardShadow.y
+ y: self.isHovered ? self.theme.metrics.elevatedCardShadow.y : self.theme.metrics.cardShadow.y
)
- .scaleEffect(configuration.isPressed ? 0.98 : (isHovered ? 1.01 : 1.0))
- .animation(.spring(response: 0.18, dampingFraction: 0.75), value: isHovered)
- .animation(.spring(response: 0.18, dampingFraction: 0.75), value: configuration.isPressed)
+ .scaleEffect(self.configuration.isPressed ? 0.98 : (self.isHovered ? 1.01 : 1.0))
+ .animation(.spring(response: 0.18, dampingFraction: 0.75), value: self.isHovered)
+ .animation(.spring(response: 0.18, dampingFraction: 0.75), value: self.configuration.isPressed)
.onHover { self.isHovered = $0 }
}
}
@@ -138,35 +138,35 @@ struct SecondaryButtonStyle: ButtonStyle {
let configuration: ButtonStyle.Configuration
private var shape: RoundedRectangle {
- RoundedRectangle(cornerRadius: theme.metrics.corners.lg, style: .continuous)
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.lg, style: .continuous)
}
var body: some View {
- configuration.label
+ self.configuration.label
.fontWeight(.semibold)
.frame(maxWidth: .infinity)
.frame(height: 42)
- .foregroundStyle(theme.palette.primaryText)
- .background(theme.materials.card, in: shape)
- .background(shape
- .fill(theme.palette.cardBackground)
- .overlay(shape.stroke(
- theme.palette.cardBorder.opacity(isHovered ? 0.45 : 0.25),
+ .foregroundStyle(self.theme.palette.primaryText)
+ .background(self.theme.materials.card, in: self.shape)
+ .background(self.shape
+ .fill(self.theme.palette.cardBackground)
+ .overlay(self.shape.stroke(
+ self.theme.palette.cardBorder.opacity(self.isHovered ? 0.45 : 0.25),
lineWidth: 1
)))
.shadow(
- color: theme.palette.cardBorder.opacity(isHovered ? 0.35 : 0.15),
- radius: isHovered ? theme.metrics.cardShadow
+ color: self.theme.palette.cardBorder.opacity(self.isHovered ? 0.35 : 0.15),
+ radius: self.isHovered ? self.theme.metrics.cardShadow
.radius : max(
- theme.metrics.cardShadow.radius - 4,
+ self.theme.metrics.cardShadow.radius - 4,
1
),
x: 0,
- y: isHovered ? theme.metrics.cardShadow.y : theme.metrics.cardShadow.y - 2
+ y: self.isHovered ? self.theme.metrics.cardShadow.y : self.theme.metrics.cardShadow.y - 2
)
- .scaleEffect(configuration.isPressed ? 0.98 : (isHovered ? 1.01 : 1.0))
- .animation(.spring(response: 0.18, dampingFraction: 0.78), value: isHovered)
- .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)
+ .scaleEffect(self.configuration.isPressed ? 0.98 : (self.isHovered ? 1.01 : 1.0))
+ .animation(.spring(response: 0.18, dampingFraction: 0.78), value: self.isHovered)
+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: self.configuration.isPressed)
.onHover { self.isHovered = $0 }
}
}
@@ -178,7 +178,7 @@ struct CompactButtonStyle: ButtonStyle {
var isReady: Bool = false
func makeBody(configuration: Configuration) -> some View {
- CompactButton(configuration: configuration, isReady: isReady)
+ CompactButton(configuration: configuration, isReady: self.isReady)
}
private struct CompactButton: View {
@@ -188,34 +188,34 @@ struct CompactButtonStyle: ButtonStyle {
let isReady: Bool
private var shape: RoundedRectangle {
- RoundedRectangle(cornerRadius: theme.metrics.corners.sm, style: .continuous)
+ RoundedRectangle(cornerRadius: self.theme.metrics.corners.sm, style: .continuous)
}
var body: some View {
- configuration.label
+ self.configuration.label
.fontWeight(.medium)
.frame(maxWidth: .infinity)
.frame(height: 34)
- .foregroundStyle(theme.palette.primaryText)
- .background(theme.materials.card, in: shape)
- .background(shape
- .fill(theme.palette.cardBackground)
- .overlay(shape
+ .foregroundStyle(self.theme.palette.primaryText)
+ .background(self.theme.materials.card, in: self.shape)
+ .background(self.shape
+ .fill(self.theme.palette.cardBackground)
+ .overlay(self.shape
.stroke(
- (isReady ? theme.palette.accent : theme.palette.cardBorder)
- .opacity(isHovered ? 0.45 : 0.25),
+ (self.isReady ? self.theme.palette.accent : self.theme.palette.cardBorder)
+ .opacity(self.isHovered ? 0.45 : 0.25),
lineWidth: 1
)))
.shadow(
- color: (isReady ? theme.palette.accent : theme.palette.cardBorder)
- .opacity(isHovered ? 0.3 : 0.12),
- radius: isHovered ? theme.metrics.cardShadow.radius - 2 : 2,
+ color: (self.isReady ? self.theme.palette.accent : self.theme.palette.cardBorder)
+ .opacity(self.isHovered ? 0.3 : 0.12),
+ radius: self.isHovered ? self.theme.metrics.cardShadow.radius - 2 : 2,
x: 0,
- y: isHovered ? theme.metrics.cardShadow.y - 1 : 1
+ y: self.isHovered ? self.theme.metrics.cardShadow.y - 1 : 1
)
- .scaleEffect(configuration.isPressed ? 0.97 : (isHovered ? 1.01 : 1.0))
- .animation(.spring(response: 0.18, dampingFraction: 0.78), value: isHovered)
- .animation(.spring(response: 0.2, dampingFraction: 0.8), value: configuration.isPressed)
+ .scaleEffect(self.configuration.isPressed ? 0.97 : (self.isHovered ? 1.01 : 1.0))
+ .animation(.spring(response: 0.18, dampingFraction: 0.78), value: self.isHovered)
+ .animation(.spring(response: 0.2, dampingFraction: 0.8), value: self.configuration.isPressed)
.onHover { self.isHovered = $0 }
}
}
@@ -238,23 +238,23 @@ struct InlineButtonStyle: ButtonStyle {
}
var body: some View {
- configuration.label
+ self.configuration.label
.font(.caption)
.fontWeight(.medium)
- .padding(.horizontal, theme.metrics.spacing.md)
- .padding(.vertical, theme.metrics.spacing.xs)
+ .padding(.horizontal, self.theme.metrics.spacing.md)
+ .padding(.vertical, self.theme.metrics.spacing.xs)
.foregroundStyle(Color.white)
- .background(shape
- .fill(theme.palette.accent.opacity(isHovered ? 0.9 : 0.8)))
+ .background(self.shape
+ .fill(self.theme.palette.accent.opacity(self.isHovered ? 0.9 : 0.8)))
.shadow(
- color: theme.palette.accent.opacity(isHovered ? 0.45 : 0.25),
- radius: isHovered ? 6 : 3,
+ color: self.theme.palette.accent.opacity(self.isHovered ? 0.45 : 0.25),
+ radius: self.isHovered ? 6 : 3,
x: 0,
- y: isHovered ? 3 : 1
+ y: self.isHovered ? 3 : 1
)
- .scaleEffect(configuration.isPressed ? 0.96 : (isHovered ? 1.03 : 1.0))
- .animation(.easeOut(duration: 0.15), value: isHovered)
- .animation(.easeOut(duration: 0.15), value: configuration.isPressed)
+ .scaleEffect(self.configuration.isPressed ? 0.96 : (self.isHovered ? 1.03 : 1.0))
+ .animation(.easeOut(duration: 0.15), value: self.isHovered)
+ .animation(.easeOut(duration: 0.15), value: self.configuration.isPressed)
.onHover { self.isHovered = $0 }
}
}
diff --git a/Sources/Fluid/UI/AISettingsView.swift b/Sources/Fluid/UI/AISettingsView.swift
index ac13ee33..dccc0dcd 100644
--- a/Sources/Fluid/UI/AISettingsView.swift
+++ b/Sources/Fluid/UI/AISettingsView.swift
@@ -21,7 +21,7 @@ struct AISettingsView: View {
@EnvironmentObject private var menuBarManager: MenuBarManager
@Environment(\.theme) private var theme
- private var asr: ASRService { appServices.asr }
+ private var asr: ASRService { self.appServices.asr }
// MARK: - State Variables (moved from ContentView)
@@ -92,21 +92,21 @@ struct AISettingsView: View {
// This ensures the speech recognition card shows current download status
self.asr.checkIfModelsExist()
}
- .onChange(of: enableAIProcessing) { _, newValue in
+ .onChange(of: self.enableAIProcessing) { _, newValue in
SettingsStore.shared.enableAIProcessing = newValue
// Keep menu bar UI in sync when toggled from this screen
self.menuBarManager.aiProcessingEnabled = newValue
}
- .onChange(of: selectedModel) { _, newValue in
+ .onChange(of: self.selectedModel) { _, newValue in
if newValue != "__ADD_MODEL__" {
self.selectedModelByProvider[self.currentProvider] = newValue
SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
}
}
- .onChange(of: selectedProviderID) { _, newValue in
+ .onChange(of: self.selectedProviderID) { _, newValue in
SettingsStore.shared.selectedProviderID = newValue
}
- .onChange(of: showKeychainPermissionAlert) { _, isPresented in
+ .onChange(of: self.showKeychainPermissionAlert) { _, isPresented in
guard isPresented else { return }
self.presentKeychainAccessAlert(message: self.keychainPermissionMessage)
self.showKeychainPermissionAlert = false
@@ -116,18 +116,18 @@ struct AISettingsView: View {
// MARK: - Load Settings
private func loadSettings() {
- selectedProviderID = SettingsStore.shared.selectedProviderID
- updateCurrentProvider()
+ self.selectedProviderID = SettingsStore.shared.selectedProviderID
+ self.updateCurrentProvider()
- enableAIProcessing = SettingsStore.shared.enableAIProcessing
- availableModelsByProvider = SettingsStore.shared.availableModelsByProvider
- selectedModelByProvider = SettingsStore.shared.selectedModelByProvider
- providerAPIKeys = SettingsStore.shared.providerAPIKeys
- savedProviders = SettingsStore.shared.savedProviders
+ 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
// Normalize provider keys
var normalized: [String: [String]] = [:]
- for (key, models) in availableModelsByProvider {
+ for (key, models) in self.availableModelsByProvider {
let lower = key.lowercased()
let newKey: String
if lower == "openai" || lower == "groq" {
@@ -138,35 +138,35 @@ struct AISettingsView: View {
let clean = Array(Set(models.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) })).sorted()
if !clean.isEmpty { normalized[newKey] = clean }
}
- availableModelsByProvider = normalized
+ self.availableModelsByProvider = normalized
SettingsStore.shared.availableModelsByProvider = normalized
// Normalize selected model by provider
var normalizedSel: [String: String] = [:]
- for (key, model) in selectedModelByProvider {
+ for (key, model) in self.selectedModelByProvider {
let lower = key.lowercased()
let newKey: String = (lower == "openai" || lower == "groq") ? lower :
(key.hasPrefix("custom:") ? key : "custom:\(key)")
if let list = normalized[newKey], list.contains(model) { normalizedSel[newKey] = model }
}
- selectedModelByProvider = normalizedSel
+ self.selectedModelByProvider = normalizedSel
SettingsStore.shared.selectedModelByProvider = normalizedSel
// Determine initial model list
if let saved = savedProviders.first(where: { $0.id == selectedProviderID }) {
- availableModels = saved.models
- openAIBaseURL = saved.baseURL
+ self.availableModels = saved.models
+ self.openAIBaseURL = saved.baseURL
} else if let stored = availableModelsByProvider[currentProvider], !stored.isEmpty {
- availableModels = stored
+ self.availableModels = stored
} else {
- availableModels = defaultModels(for: providerKey(for: selectedProviderID))
+ self.availableModels = self.defaultModels(for: self.providerKey(for: self.selectedProviderID))
}
// Restore selected model
if let sel = selectedModelByProvider[currentProvider], availableModels.contains(sel) {
- selectedModel = sel
+ self.selectedModel = sel
} else if let first = availableModels.first {
- selectedModel = first
+ self.selectedModel = first
}
}
@@ -346,7 +346,7 @@ struct AISettingsView: View {
private func downloadModels() async {
do {
- try await asr.ensureAsrReady()
+ try await self.asr.ensureAsrReady()
} catch {
DebugLogger.shared.error("Failed to download models: \(error)", source: "AISettingsView")
}
@@ -354,7 +354,7 @@ struct AISettingsView: View {
private func deleteModels() async {
do {
- try await asr.clearModelCache()
+ try await self.asr.clearModelCache()
} catch {
DebugLogger.shared.error("Failed to delete models: \(error)", source: "AISettingsView")
}
@@ -364,7 +364,7 @@ struct AISettingsView: View {
private func providerKey(for providerID: String) -> String {
if providerID == "openai" || providerID == "groq" { return providerID }
- return providerID.isEmpty ? currentProvider : "custom:\(providerID)"
+ return providerID.isEmpty ? self.currentProvider : "custom:\(providerID)"
}
private func providerDisplayName(for providerID: String) -> String {
@@ -373,7 +373,7 @@ struct AISettingsView: View {
case "groq": return "Groq"
case "apple-intelligence": return "Apple Intelligence"
default:
- return savedProviders.first(where: { $0.id == providerID })?.name ?? providerID.capitalized
+ return self.savedProviders.first(where: { $0.id == providerID })?.name ?? providerID.capitalized
}
}
@@ -386,18 +386,18 @@ struct AISettingsView: View {
}
private func saveProviderAPIKeys() {
- SettingsStore.shared.providerAPIKeys = providerAPIKeys
+ SettingsStore.shared.providerAPIKeys = self.providerAPIKeys
}
private func updateCurrentProvider() {
- let url = openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
- if url.contains("openai.com") { currentProvider = "openai"; return }
- if url.contains("groq.com") { currentProvider = "groq"; return }
- currentProvider = providerKey(for: selectedProviderID)
+ let url = self.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ if url.contains("openai.com") { self.currentProvider = "openai"; return }
+ if url.contains("groq.com") { self.currentProvider = "groq"; return }
+ self.currentProvider = self.providerKey(for: self.selectedProviderID)
}
private func saveSavedProviders() {
- SettingsStore.shared.savedProviders = savedProviders
+ SettingsStore.shared.savedProviders = self.savedProviders
}
private func isLocalEndpoint(_ urlString: String) -> Bool {
@@ -415,13 +415,13 @@ struct AISettingsView: View {
}
private func hasReasoningConfigForCurrentModel() -> Bool {
- let pKey = providerKey(for: selectedProviderID)
- if SettingsStore.shared.hasCustomReasoningConfig(forModel: selectedModel, provider: pKey) {
+ let pKey = self.providerKey(for: self.selectedProviderID)
+ if SettingsStore.shared.hasCustomReasoningConfig(forModel: self.selectedModel, provider: pKey) {
if let config = SettingsStore.shared.getReasoningConfig(forModel: selectedModel, provider: pKey) {
return config.isEnabled
}
}
- let modelLower = selectedModel.lowercased()
+ 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/") ||
@@ -429,35 +429,35 @@ struct AISettingsView: View {
}
private func addNewModel() {
- guard !newModelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
- let modelName = newModelName.trimmingCharacters(in: .whitespacesAndNewlines)
- let key = providerKey(for: selectedProviderID)
+ guard !self.newModelName.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty else { return }
+ let modelName = self.newModelName.trimmingCharacters(in: .whitespacesAndNewlines)
+ let key = self.providerKey(for: self.selectedProviderID)
- var list = availableModelsByProvider[key] ?? availableModels
+ var list = self.availableModelsByProvider[key] ?? self.availableModels
if !list.contains(modelName) {
list.append(modelName)
- availableModelsByProvider[key] = list
- SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
+ self.availableModelsByProvider[key] = list
+ SettingsStore.shared.availableModelsByProvider = self.availableModelsByProvider
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
let updatedProvider = SettingsStore.SavedProvider(
- id: savedProviders[providerIndex].id,
- name: savedProviders[providerIndex].name,
- baseURL: savedProviders[providerIndex].baseURL,
+ id: self.savedProviders[providerIndex].id,
+ name: self.savedProviders[providerIndex].name,
+ baseURL: self.savedProviders[providerIndex].baseURL,
models: list
)
- savedProviders[providerIndex] = updatedProvider
- saveSavedProviders()
+ self.savedProviders[providerIndex] = updatedProvider
+ self.saveSavedProviders()
}
- availableModels = list
- selectedModel = modelName
- selectedModelByProvider[key] = modelName
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
+ self.availableModels = list
+ self.selectedModel = modelName
+ self.selectedModelByProvider[key] = modelName
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
}
- showingAddModel = false
- newModelName = ""
+ self.showingAddModel = false
+ self.newModelName = ""
}
// MARK: - Keychain Access Helpers
@@ -468,13 +468,13 @@ struct AISettingsView: View {
}
private func handleAPIKeyButtonTapped() {
- switch probeKeychainAccess() {
+ switch self.probeKeychainAccess() {
case .granted:
- newProviderApiKey = providerAPIKeys[currentProvider] ?? ""
- showAPIKeyEditor = true
+ self.newProviderApiKey = self.providerAPIKeys[self.currentProvider] ?? ""
+ self.showAPIKeyEditor = true
case let .denied(status):
- keychainPermissionMessage = keychainPermissionExplanation(for: status)
- showKeychainPermissionAlert = true
+ self.keychainPermissionMessage = self.keychainPermissionExplanation(for: status)
+ self.showKeychainPermissionAlert = true
}
}
@@ -558,11 +558,11 @@ struct AISettingsView: View {
// MARK: - API Connection Testing
private func testAPIConnection() async {
- guard !isTestingConnection else { return }
+ guard !self.isTestingConnection else { return }
- let apiKey = providerAPIKeys[currentProvider] ?? ""
- let baseURL = openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
- let isLocal = isLocalEndpoint(baseURL)
+ let apiKey = self.providerAPIKeys[self.currentProvider] ?? ""
+ let baseURL = self.openAIBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ let isLocal = self.isLocalEndpoint(baseURL)
if isLocal {
guard !baseURL.isEmpty else {
@@ -607,13 +607,13 @@ struct AISettingsView: View {
return
}
- let provKey = providerKey(for: selectedProviderID)
+ let provKey = self.providerKey(for: self.selectedProviderID)
let reasoningConfig = SettingsStore.shared.getReasoningConfig(
- forModel: selectedModel,
+ forModel: self.selectedModel,
provider: provKey
)
- let modelLower = selectedModel.lowercased()
+ let modelLower = self.selectedModel.lowercased()
let usesMaxCompletionTokens = modelLower.hasPrefix("gpt-5") || modelLower.contains("gpt-5.") ||
modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3")
@@ -841,9 +841,9 @@ struct AISettingsView: View {
}
}
.padding(14)
- .background(theme.palette.accent.opacity(0.08))
+ .background(self.theme.palette.accent.opacity(0.08))
.cornerRadius(12)
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(theme.palette.accent.opacity(0.2), lineWidth: 1))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(self.theme.palette.accent.opacity(0.2), lineWidth: 1))
.padding(.horizontal, 4)
.transition(.opacity)
}
@@ -974,57 +974,57 @@ struct AISettingsView: View {
private func handleProviderChange(_ newValue: String) {
switch newValue {
case "openai":
- openAIBaseURL = "https://api.openai.com/v1"
- updateCurrentProvider()
+ self.openAIBaseURL = "https://api.openai.com/v1"
+ self.updateCurrentProvider()
let key = "openai"
- availableModels = availableModelsByProvider[key] ?? defaultModels(for: key)
- selectedModel = selectedModelByProvider[key] ?? availableModels.first ?? selectedModel
+ self.availableModels = self.availableModelsByProvider[key] ?? self.defaultModels(for: key)
+ self.selectedModel = self.selectedModelByProvider[key] ?? self.availableModels.first ?? self.selectedModel
case "groq":
- openAIBaseURL = "https://api.groq.com/openai/v1"
- updateCurrentProvider()
+ self.openAIBaseURL = "https://api.groq.com/openai/v1"
+ self.updateCurrentProvider()
let key = "groq"
- availableModels = availableModelsByProvider[key] ?? defaultModels(for: key)
- selectedModel = selectedModelByProvider[key] ?? availableModels.first ?? selectedModel
+ self.availableModels = self.availableModelsByProvider[key] ?? self.defaultModels(for: key)
+ self.selectedModel = self.selectedModelByProvider[key] ?? self.availableModels.first ?? self.selectedModel
case "apple-intelligence":
- openAIBaseURL = ""
- updateCurrentProvider()
- availableModels = ["System Model"]
- selectedModel = "System Model"
+ self.openAIBaseURL = ""
+ self.updateCurrentProvider()
+ self.availableModels = ["System Model"]
+ self.selectedModel = "System Model"
default:
if let provider = savedProviders.first(where: { $0.id == newValue }) {
- openAIBaseURL = provider.baseURL
- updateCurrentProvider()
- let key = providerKey(for: newValue)
- availableModels = provider.models.isEmpty ? (availableModelsByProvider[key] ?? []) : provider
+ self.openAIBaseURL = provider.baseURL
+ self.updateCurrentProvider()
+ let key = self.providerKey(for: newValue)
+ self.availableModels = provider.models.isEmpty ? (self.availableModelsByProvider[key] ?? []) : provider
.models
- selectedModel = selectedModelByProvider[key] ?? availableModels.first ?? selectedModel
+ self.selectedModel = self.selectedModelByProvider[key] ?? self.availableModels.first ?? self.selectedModel
}
}
}
private func startEditingProvider() {
if let provider = savedProviders.first(where: { $0.id == selectedProviderID }) {
- editProviderName = provider.name
- editProviderBaseURL = provider.baseURL
- showingEditProvider = true
+ self.editProviderName = provider.name
+ self.editProviderBaseURL = provider.baseURL
+ self.showingEditProvider = true
}
}
private func deleteCurrentProvider() {
- savedProviders.removeAll { $0.id == self.selectedProviderID }
- saveSavedProviders()
- let key = providerKey(for: selectedProviderID)
- availableModelsByProvider.removeValue(forKey: key)
- selectedModelByProvider.removeValue(forKey: key)
- providerAPIKeys.removeValue(forKey: key)
- saveProviderAPIKeys()
- SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
- selectedProviderID = "openai"
- openAIBaseURL = "https://api.openai.com/v1"
- updateCurrentProvider()
- availableModels = defaultModels(for: "openai")
- selectedModel = availableModels.first ?? selectedModel
+ self.savedProviders.removeAll { $0.id == self.selectedProviderID }
+ self.saveSavedProviders()
+ let key = self.providerKey(for: self.selectedProviderID)
+ self.availableModelsByProvider.removeValue(forKey: key)
+ self.selectedModelByProvider.removeValue(forKey: key)
+ self.providerAPIKeys.removeValue(forKey: key)
+ self.saveProviderAPIKeys()
+ SettingsStore.shared.availableModelsByProvider = self.availableModelsByProvider
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
+ self.selectedProviderID = "openai"
+ self.openAIBaseURL = "https://api.openai.com/v1"
+ self.updateCurrentProvider()
+ self.availableModels = self.defaultModels(for: "openai")
+ self.selectedModel = self.availableModels.first ?? self.selectedModel
}
private var editProviderSection: some View {
@@ -1056,33 +1056,33 @@ struct AISettingsView: View {
}
}
.padding(12)
- .background(theme.palette.cardBackground.opacity(0.5))
+ .background(self.theme.palette.cardBackground.opacity(0.5))
.cornerRadius(12)
- .overlay(RoundedRectangle(cornerRadius: 12).stroke(theme.palette.accent.opacity(0.3), lineWidth: 1))
+ .overlay(RoundedRectangle(cornerRadius: 12).stroke(self.theme.palette.accent.opacity(0.3), lineWidth: 1))
.padding(.vertical, 8)
.transition(.move(edge: .top).combined(with: .opacity))
}
private func saveEditedProvider() {
- let name = editProviderName.trimmingCharacters(in: .whitespacesAndNewlines)
- let base = editProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ let name = self.editProviderName.trimmingCharacters(in: .whitespacesAndNewlines)
+ let base = self.editProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty, !base.isEmpty else { return }
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
- let oldProvider = savedProviders[providerIndex]
+ let oldProvider = self.savedProviders[providerIndex]
let updatedProvider = SettingsStore.SavedProvider(
id: oldProvider.id,
name: name,
baseURL: base,
models: oldProvider.models
)
- savedProviders[providerIndex] = updatedProvider
- saveSavedProviders()
- openAIBaseURL = base
- updateCurrentProvider()
+ self.savedProviders[providerIndex] = updatedProvider
+ self.saveSavedProviders()
+ self.openAIBaseURL = base
+ self.updateCurrentProvider()
}
- showingEditProvider = false
- editProviderName = ""; editProviderBaseURL = ""
+ self.showingEditProvider = false
+ self.editProviderName = ""; self.editProviderBaseURL = ""
}
private var appleIntelligenceBadge: some View {
@@ -1167,49 +1167,49 @@ struct AISettingsView: View {
}
private func deleteSelectedModel() {
- let key = providerKey(for: selectedProviderID)
- var list = availableModelsByProvider[key] ?? availableModels
+ let key = self.providerKey(for: self.selectedProviderID)
+ var list = self.availableModelsByProvider[key] ?? self.availableModels
list.removeAll { $0 == self.selectedModel }
- if list.isEmpty { list = defaultModels(for: key) }
- availableModelsByProvider[key] = list
- SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
+ if list.isEmpty { list = self.defaultModels(for: key) }
+ self.availableModelsByProvider[key] = list
+ SettingsStore.shared.availableModelsByProvider = self.availableModelsByProvider
if let providerIndex = savedProviders.firstIndex(where: { $0.id == selectedProviderID }) {
let updatedProvider = SettingsStore.SavedProvider(
- id: savedProviders[providerIndex].id,
- name: savedProviders[providerIndex].name,
- baseURL: savedProviders[providerIndex].baseURL,
+ id: self.savedProviders[providerIndex].id,
+ name: self.savedProviders[providerIndex].name,
+ baseURL: self.savedProviders[providerIndex].baseURL,
models: list
)
- savedProviders[providerIndex] = updatedProvider
- saveSavedProviders()
+ self.savedProviders[providerIndex] = updatedProvider
+ self.saveSavedProviders()
}
- availableModels = list
- selectedModel = list.first ?? ""
- selectedModelByProvider[key] = selectedModel
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
+ self.availableModels = list
+ self.selectedModel = list.first ?? ""
+ self.selectedModelByProvider[key] = self.selectedModel
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
}
private func openReasoningConfig() {
- let pKey = providerKey(for: selectedProviderID)
+ let pKey = self.providerKey(for: self.selectedProviderID)
if let config = SettingsStore.shared.getReasoningConfig(forModel: selectedModel, provider: pKey) {
- editingReasoningParamName = config.parameterName
- editingReasoningParamValue = config.parameterValue
- editingReasoningEnabled = config.isEnabled
+ self.editingReasoningParamName = config.parameterName
+ self.editingReasoningParamValue = config.parameterValue
+ self.editingReasoningEnabled = config.isEnabled
} else {
- let modelLower = selectedModel.lowercased()
+ let modelLower = self.selectedModel.lowercased()
if modelLower.hasPrefix("gpt-5") || modelLower.hasPrefix("o1") || modelLower.hasPrefix("o3") || modelLower
.contains("gpt-oss")
{
- editingReasoningParamName = "reasoning_effort"; editingReasoningParamValue = "low"; editingReasoningEnabled = true
+ self.editingReasoningParamName = "reasoning_effort"; self.editingReasoningParamValue = "low"; self.editingReasoningEnabled = true
} else if modelLower.contains("deepseek"), modelLower.contains("reasoner") {
- editingReasoningParamName = "enable_thinking"; editingReasoningParamValue = "true"; editingReasoningEnabled = true
+ self.editingReasoningParamName = "enable_thinking"; self.editingReasoningParamValue = "true"; self.editingReasoningEnabled = true
} else {
- editingReasoningParamName = "reasoning_effort"; editingReasoningParamValue = "low"; editingReasoningEnabled = false
+ self.editingReasoningParamName = "reasoning_effort"; self.editingReasoningParamValue = "low"; self.editingReasoningEnabled = false
}
}
- showingReasoningConfig = true
+ self.showingReasoningConfig = true
}
private var addModelSection: some View {
@@ -1272,9 +1272,9 @@ struct AISettingsView: View {
}
}
.padding(12)
- .background(RoundedRectangle(cornerRadius: 8).fill(theme.palette.accent.opacity(0.08))
+ .background(RoundedRectangle(cornerRadius: 8).fill(self.theme.palette.accent.opacity(0.08))
.overlay(RoundedRectangle(cornerRadius: 8).stroke(
- theme.palette.accent.opacity(0.2),
+ self.theme.palette.accent.opacity(0.2),
lineWidth: 1
)))
.padding(.leading, 122)
@@ -1282,19 +1282,19 @@ struct AISettingsView: View {
}
private func saveReasoningConfig() {
- let pKey = providerKey(for: selectedProviderID)
- if editingReasoningEnabled {
+ let pKey = self.providerKey(for: self.selectedProviderID)
+ if self.editingReasoningEnabled {
let config = SettingsStore.ModelReasoningConfig(
- parameterName: editingReasoningParamName,
- parameterValue: editingReasoningParamValue,
+ parameterName: self.editingReasoningParamName,
+ parameterValue: self.editingReasoningParamValue,
isEnabled: true
)
- SettingsStore.shared.setReasoningConfig(config, forModel: selectedModel, provider: pKey)
+ SettingsStore.shared.setReasoningConfig(config, forModel: self.selectedModel, provider: pKey)
} else {
let config = SettingsStore.ModelReasoningConfig(parameterName: "", parameterValue: "", isEnabled: false)
- SettingsStore.shared.setReasoningConfig(config, forModel: selectedModel, provider: pKey)
+ SettingsStore.shared.setReasoningConfig(config, forModel: self.selectedModel, provider: pKey)
}
- showingReasoningConfig = false
+ self.showingReasoningConfig = false
}
private var connectionTestSection: some View {
@@ -1398,36 +1398,36 @@ struct AISettingsView: View {
}
private func saveNewProvider() {
- let name = newProviderName.trimmingCharacters(in: .whitespacesAndNewlines)
- let base = newProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
- let api = newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines)
+ let name = self.newProviderName.trimmingCharacters(in: .whitespacesAndNewlines)
+ let base = self.newProviderBaseURL.trimmingCharacters(in: .whitespacesAndNewlines)
+ let api = self.newProviderApiKey.trimmingCharacters(in: .whitespacesAndNewlines)
guard !name.isEmpty, !base.isEmpty else { return }
- let modelsList = newProviderModels.split(separator: ",")
+ let modelsList = self.newProviderModels.split(separator: ",")
.map { $0.trimmingCharacters(in: .whitespacesAndNewlines) }.filter { !$0.isEmpty }
- let models = modelsList.isEmpty ? defaultModels(for: "openai") : modelsList
+ let models = modelsList.isEmpty ? self.defaultModels(for: "openai") : modelsList
let newProvider = SettingsStore.SavedProvider(name: name, baseURL: base, models: models)
- savedProviders.removeAll { $0.name.lowercased() == name.lowercased() }
- savedProviders.append(newProvider)
- saveSavedProviders()
-
- let key = providerKey(for: newProvider.id)
- providerAPIKeys[key] = api
- availableModelsByProvider[key] = models
- selectedModelByProvider[key] = models.first ?? selectedModel
- SettingsStore.shared.providerAPIKeys = providerAPIKeys
- SettingsStore.shared.availableModelsByProvider = availableModelsByProvider
- SettingsStore.shared.selectedModelByProvider = selectedModelByProvider
-
- selectedProviderID = newProvider.id
- openAIBaseURL = base
- updateCurrentProvider()
- availableModels = models
- selectedModel = models.first ?? selectedModel
-
- showingSaveProvider = false
- newProviderName = ""; newProviderBaseURL = ""; newProviderApiKey = ""; newProviderModels = ""
+ self.savedProviders.removeAll { $0.name.lowercased() == name.lowercased() }
+ self.savedProviders.append(newProvider)
+ self.saveSavedProviders()
+
+ let key = self.providerKey(for: newProvider.id)
+ self.providerAPIKeys[key] = api
+ self.availableModelsByProvider[key] = models
+ self.selectedModelByProvider[key] = models.first ?? self.selectedModel
+ SettingsStore.shared.providerAPIKeys = self.providerAPIKeys
+ SettingsStore.shared.availableModelsByProvider = self.availableModelsByProvider
+ SettingsStore.shared.selectedModelByProvider = self.selectedModelByProvider
+
+ self.selectedProviderID = newProvider.id
+ self.openAIBaseURL = base
+ self.updateCurrentProvider()
+ self.availableModels = models
+ self.selectedModel = models.first ?? self.selectedModel
+
+ self.showingSaveProvider = false
+ self.newProviderName = ""; self.newProviderBaseURL = ""; self.newProviderApiKey = ""; self.newProviderModels = ""
}
private var apiKeysGuideCard: some View {
@@ -1487,6 +1487,6 @@ struct AISettingsView: View {
}
.padding(14)
}
- .modifier(CardAppearAnimation(delay: 0.2, appear: $appear))
+ .modifier(CardAppearAnimation(delay: 0.2, appear: self.$appear))
}
}
diff --git a/Sources/Fluid/UI/FeedbackView.swift b/Sources/Fluid/UI/FeedbackView.swift
index f6dadd38..27c56ca9 100644
--- a/Sources/Fluid/UI/FeedbackView.swift
+++ b/Sources/Fluid/UI/FeedbackView.swift
@@ -187,12 +187,12 @@ struct FeedbackView: View {
.onAppear {
self.appear = true
}
- .alert("Feedback Sent", isPresented: $showFeedbackConfirmation) {
+ .alert("Feedback Sent", isPresented: self.$showFeedbackConfirmation) {
Button("OK") {}
} message: {
Text("Thank you for helping us improve FluidVoice.")
}
- .alert("Feedback Failed", isPresented: $showFeedbackError) {
+ .alert("Feedback Failed", isPresented: self.$showFeedbackError) {
Button("Try Again") {
Task {
await self.sendFeedback()
@@ -207,8 +207,8 @@ struct FeedbackView: View {
// MARK: - Feedback Functions
private func sendFeedback() async {
- guard !feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
- !feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
+ guard !self.feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty,
+ !self.feedbackText.trimmingCharacters(in: .whitespacesAndNewlines).isEmpty
else {
return
}
@@ -217,7 +217,7 @@ struct FeedbackView: View {
self.isSendingFeedback = true
}
- let feedbackData = createFeedbackData()
+ let feedbackData = self.createFeedbackData()
let success = await submitFeedback(data: feedbackData)
await MainActor.run {
@@ -237,9 +237,9 @@ struct FeedbackView: View {
}
private func createFeedbackData() -> [String: Any] {
- var feedbackContent = feedbackText.trimmingCharacters(in: .whitespacesAndNewlines)
+ var feedbackContent = self.feedbackText.trimmingCharacters(in: .whitespacesAndNewlines)
- if includeDebugLogs {
+ if self.includeDebugLogs {
feedbackContent += "\n\n--- Debug Information ---\n"
feedbackContent += "App Version: \(Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String ?? "Unknown")\n"
feedbackContent += "Build: \(Bundle.main.infoDictionary?["CFBundleVersion"] as? String ?? "Unknown")\n"
@@ -262,7 +262,7 @@ struct FeedbackView: View {
}
return [
- "email_id": feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines),
+ "email_id": self.feedbackEmail.trimmingCharacters(in: .whitespacesAndNewlines),
"feedback": feedbackContent,
]
}
diff --git a/Sources/Fluid/UI/FluidIcon.swift b/Sources/Fluid/UI/FluidIcon.swift
index 73fbdab7..5b30598b 100644
--- a/Sources/Fluid/UI/FluidIcon.swift
+++ b/Sources/Fluid/UI/FluidIcon.swift
@@ -89,7 +89,7 @@ struct FluidIcon: View {
context.fill(highlightPath, with: .color(self.color.opacity(0.3)))
}
}
- .frame(width: size, height: size)
+ .frame(width: self.size, height: self.size)
}
}
@@ -194,7 +194,7 @@ struct FluidIconAdvanced: View {
context.fill(glowPath, with: .color(self.color.opacity(0.4)))
}
- .frame(width: size, height: size)
+ .frame(width: self.size, height: self.size)
}
}
diff --git a/Sources/Fluid/UI/GlossyEffects.swift b/Sources/Fluid/UI/GlossyEffects.swift
index 440752cc..6977141e 100644
--- a/Sources/Fluid/UI/GlossyEffects.swift
+++ b/Sources/Fluid/UI/GlossyEffects.swift
@@ -16,10 +16,10 @@ struct HoverableGlossyCard<Content: View>: View {
var body: some View {
let shape = RoundedRectangle(cornerRadius: theme.metrics.corners.lg, style: .continuous)
- let cardShadow = theme.metrics.cardShadow
+ let cardShadow = self.theme.metrics.cardShadow
- return content
- .background(theme.materials.card, in: shape)
+ return self.content
+ .background(self.theme.materials.card, in: shape)
.background {
shape
.fill(self.theme.palette.cardBackground)
@@ -36,11 +36,11 @@ struct HoverableGlossyCard<Content: View>: View {
y: self.isHovered ? cardShadow.y + 1 : cardShadow.y
)
}
- .scaleEffect(isHovered && !excludeInteractiveElements ? 1.02 : 1.0)
+ .scaleEffect(self.isHovered && !self.excludeInteractiveElements ? 1.02 : 1.0)
.onHover { hovering in
self.isHovered = hovering
}
- .animation(.easeOut(duration: 0.18), value: isHovered)
+ .animation(.easeOut(duration: 0.18), value: self.isHovered)
}
}
@@ -58,17 +58,17 @@ struct ButtonHoverModifier: ViewModifier {
func body(content: Content) -> some View {
content
- .scaleEffect(isHovered ? 1.05 : 1.0)
+ .scaleEffect(self.isHovered ? 1.05 : 1.0)
.shadow(
- color: theme.palette.accent.opacity(isHovered ? 0.35 : 0.0),
- radius: isHovered ? 8 : 0,
+ color: self.theme.palette.accent.opacity(self.isHovered ? 0.35 : 0.0),
+ radius: self.isHovered ? 8 : 0,
x: 0,
- y: isHovered ? 3 : 0
+ y: self.isHovered ? 3 : 0
)
.onHover { hovering in
self.isHovered = hovering
}
- .animation(.spring(response: 0.2, dampingFraction: 0.7), value: isHovered)
+ .animation(.spring(response: 0.2, dampingFraction: 0.7), value: self.isHovered)
}
}
diff --git a/Sources/Fluid/UI/MeetingTranscriptionView.swift b/Sources/Fluid/UI/MeetingTranscriptionView.swift
index c9cc830d..3779b06b 100644
--- a/Sources/Fluid/UI/MeetingTranscriptionView.swift
+++ b/Sources/Fluid/UI/MeetingTranscriptionView.swift
@@ -167,7 +167,7 @@ struct MeetingTranscriptionView: View {
}
}
.fileImporter(
- isPresented: $showingFilePicker,
+ isPresented: self.$showingFilePicker,
allowedContentTypes: {
var types: [UTType] = [.audio, .movie, .mpeg4Movie]
["wav", "mp3", "m4a"]
@@ -271,14 +271,14 @@ struct MeetingTranscriptionView: View {
.background(Color(nsColor: .controlBackgroundColor))
.cornerRadius(12)
.fileExporter(
- isPresented: $showingExportDialog,
+ isPresented: self.$showingExportDialog,
document: TranscriptionDocument(
result: result,
- format: exportFormat,
- service: transcriptionService
+ format: self.exportFormat,
+ service: self.transcriptionService
),
- contentType: exportFormat == .text ? .plainText : .json,
- defaultFilename: "\(result.fileName)_transcript.\(exportFormat.fileExtension)"
+ contentType: self.exportFormat == .text ? .plainText : .json,
+ defaultFilename: "\(result.fileName)_transcript.\(self.exportFormat.fileExtension)"
) { result in
switch result {
case .success:
@@ -317,7 +317,7 @@ struct MeetingTranscriptionView: View {
guard let fileURL = selectedFileURL else { return }
do {
- _ = try await transcriptionService.transcribeFile(fileURL)
+ _ = try await self.transcriptionService.transcribeFile(fileURL)
} catch {
print("Transcription error: \(error)")
}
@@ -375,13 +375,13 @@ struct TranscriptionDocument: FileDocument {
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
- let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("temp.\(format.fileExtension)")
+ let tempURL = FileManager.default.temporaryDirectory.appendingPathComponent("temp.\(self.format.fileExtension)")
- switch format {
+ switch self.format {
case .text:
- try service.exportToText(result, to: tempURL)
+ try self.service.exportToText(self.result, to: tempURL)
case .json:
- try service.exportToJSON(result, to: tempURL)
+ try self.service.exportToJSON(self.result, to: tempURL)
}
let data = try Data(contentsOf: tempURL)
diff --git a/Sources/Fluid/UI/MouseTracker.swift b/Sources/Fluid/UI/MouseTracker.swift
index 9289e1a0..8c283651 100644
--- a/Sources/Fluid/UI/MouseTracker.swift
+++ b/Sources/Fluid/UI/MouseTracker.swift
@@ -12,10 +12,10 @@ class MousePositionTracker: ObservableObject {
private let frameUpdateInterval: TimeInterval = 0.1 // Debounce frame updates during scroll
var relativePosition: CGPoint {
- guard windowFrame.width > 0 && windowFrame.height > 0 else { return .zero }
+ guard self.windowFrame.width > 0 && self.windowFrame.height > 0 else { return .zero }
return CGPoint(
- x: (mousePosition.x - windowFrame.minX) / windowFrame.width,
- y: (mousePosition.y - windowFrame.minY) / windowFrame.height
+ x: (self.mousePosition.x - self.windowFrame.minX) / self.windowFrame.width,
+ y: (self.mousePosition.y - self.windowFrame.minY) / self.windowFrame.height
)
}
@@ -25,10 +25,10 @@ class MousePositionTracker: ObservableObject {
guard position.x >= 0, position.y >= 0 else { return }
let now = CACurrentMediaTime()
- guard now - lastUpdateTime >= updateInterval else { return }
+ guard now - self.lastUpdateTime >= self.updateInterval else { return }
- mousePosition = position
- lastUpdateTime = now
+ self.mousePosition = position
+ self.lastUpdateTime = now
}
func updateWindowFrame(_ frame: CGRect) {
@@ -39,10 +39,10 @@ class MousePositionTracker: ObservableObject {
// Debounce frame updates during scroll to prevent rapid invalid geometry
let now = CACurrentMediaTime()
- guard now - lastFrameUpdateTime >= frameUpdateInterval else { return }
+ guard now - self.lastFrameUpdateTime >= self.frameUpdateInterval else { return }
- windowFrame = frame
- lastFrameUpdateTime = now
+ self.windowFrame = frame
+ self.lastFrameUpdateTime = now
}
}
diff --git a/Sources/Fluid/UI/RecordingView.swift b/Sources/Fluid/UI/RecordingView.swift
index 6508152f..48bdb9dc 100644
--- a/Sources/Fluid/UI/RecordingView.swift
+++ b/Sources/Fluid/UI/RecordingView.swift
@@ -3,7 +3,7 @@ import SwiftUI
struct RecordingView: View {
@EnvironmentObject var appServices: AppServices
- private var asr: ASRService { appServices.asr }
+ private var asr: ASRService { self.appServices.asr }
@Environment(\.theme) private var theme
@Binding var appear: Bool
diff --git a/Sources/Fluid/UI/SettingsView.swift b/Sources/Fluid/UI/SettingsView.swift
index d4f565f3..1ff5f30e 100644
--- a/Sources/Fluid/UI/SettingsView.swift
+++ b/Sources/Fluid/UI/SettingsView.swift
@@ -4,7 +4,7 @@ import SwiftUI
struct SettingsView: View {
@EnvironmentObject var appServices: AppServices
- private var asr: ASRService { appServices.asr }
+ private var asr: ASRService { self.appServices.asr }
@Environment(\.theme) private var theme
@Binding var appear: Bool
@Binding var visualizerNoiseThreshold: Double
@@ -611,7 +611,7 @@ struct SettingsView: View {
self.cachedDefaultOutputName = AudioDevice.getDefaultOutputDevice()?.name ?? ""
}
}
- .onChange(of: visualizerNoiseThreshold) { _, newValue in
+ .onChange(of: self.visualizerNoiseThreshold) { _, newValue in
SettingsStore.shared.visualizerNoiseThreshold = newValue
}
}
@@ -708,7 +708,7 @@ struct SettingsView: View {
}
.padding(12)
.background(RoundedRectangle(cornerRadius: 8, style: .continuous)
- .fill((warningStyle ? theme.palette.warning : theme.palette.accent).opacity(0.12)))
+ .fill((warningStyle ? self.theme.palette.warning : self.theme.palette.accent).opacity(0.12)))
}
@ViewBuilder
@@ -843,16 +843,16 @@ struct FillerWordsEditor: View {
}
private func addWord() {
- let word = newWord.trimmingCharacters(in: .whitespaces).lowercased()
- guard !word.isEmpty, !fillerWords.contains(word) else { return }
- fillerWords.append(word)
- SettingsStore.shared.fillerWords = fillerWords
- newWord = ""
+ let word = self.newWord.trimmingCharacters(in: .whitespaces).lowercased()
+ guard !word.isEmpty, !self.fillerWords.contains(word) else { return }
+ self.fillerWords.append(word)
+ SettingsStore.shared.fillerWords = self.fillerWords
+ self.newWord = ""
}
private func removeWord(_ word: String) {
- fillerWords.removeAll { $0 == word }
- SettingsStore.shared.fillerWords = fillerWords
+ self.fillerWords.removeAll { $0 == word }
+ SettingsStore.shared.fillerWords = self.fillerWords
}
}
@@ -862,12 +862,12 @@ struct FlowLayout: Layout {
var spacing: CGFloat = 8
func sizeThatFits(proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) -> CGSize {
- let result = arrangeSubviews(proposal: proposal, subviews: subviews)
+ let result = self.arrangeSubviews(proposal: proposal, subviews: subviews)
return result.size
}
func placeSubviews(in bounds: CGRect, proposal: ProposedViewSize, subviews: Subviews, cache: inout ()) {
- let result = arrangeSubviews(proposal: proposal, subviews: subviews)
+ let result = self.arrangeSubviews(proposal: proposal, subviews: subviews)
for (index, position) in result.positions.enumerated() {
subviews[index].place(
at: CGPoint(x: bounds.minX + position.x, y: bounds.minY + position.y),
@@ -890,12 +890,12 @@ struct FlowLayout: Layout {
let size = subview.sizeThatFits(.unspecified)
if x + size.width > maxWidth, x > 0 {
x = 0
- y += rowHeight + spacing
+ y += rowHeight + self.spacing
rowHeight = 0
}
positions.append(CGPoint(x: x, y: y))
rowHeight = max(rowHeight, size.height)
- x += size.width + spacing
+ x += size.width + self.spacing
}
return (CGSize(width: maxWidth, height: y + rowHeight), positions)
diff --git a/Sources/Fluid/UI/StatsView.swift b/Sources/Fluid/UI/StatsView.swift
index 53ba30fc..d1467cf7 100644
--- a/Sources/Fluid/UI/StatsView.swift
+++ b/Sources/Fluid/UI/StatsView.swift
@@ -68,7 +68,7 @@ struct StatsView: View {
.buttonStyle(.plain)
}
}
- .popover(isPresented: $showWPMEditor) {
+ .popover(isPresented: self.$showWPMEditor) {
self.wpmEditorPopover
}
}
@@ -450,7 +450,7 @@ struct StatsView: View {
.frame(maxWidth: .infinity, alignment: .leading)
.padding(10)
.background(RoundedRectangle(cornerRadius: 8)
- .fill(theme.palette.accent.opacity(0.08)))
+ .fill(self.theme.palette.accent.opacity(0.08)))
}
// MARK: - Reset Section
@@ -473,7 +473,7 @@ struct StatsView: View {
Spacer()
}
.padding(.top, 8)
- .alert("Reset All Stats", isPresented: $showResetConfirmation) {
+ .alert("Reset All Stats", isPresented: self.$showResetConfirmation) {
Button("Cancel", role: .cancel) {}
Button("Reset Everything", role: .destructive) {
self.historyStore.clearAllHistory()
diff --git a/Sources/Fluid/UI/TranscriptionHistoryView.swift b/Sources/Fluid/UI/TranscriptionHistoryView.swift
index a51f060e..acb88ca4 100644
--- a/Sources/Fluid/UI/TranscriptionHistoryView.swift
+++ b/Sources/Fluid/UI/TranscriptionHistoryView.swift
@@ -9,12 +9,12 @@ struct TranscriptionHistoryView: View {
@State private var selectedEntryID: UUID?
private var filteredEntries: [TranscriptionHistoryEntry] {
- historyStore.search(query: searchQuery)
+ self.historyStore.search(query: self.searchQuery)
}
private var selectedEntry: TranscriptionHistoryEntry? {
- guard let id = selectedEntryID else { return filteredEntries.first }
- return filteredEntries.first(where: { $0.id == id })
+ guard let id = selectedEntryID else { return self.filteredEntries.first }
+ return self.filteredEntries.first(where: { $0.id == id })
}
var body: some View {
@@ -57,7 +57,7 @@ struct TranscriptionHistoryView: View {
self.selectedEntryID = self.filteredEntries.first?.id
}
}
- .alert("Clear All History", isPresented: $showClearConfirmation) {
+ .alert("Clear All History", isPresented: self.$showClearConfirmation) {
Button("Cancel", role: .cancel) {}
Button("Clear All", role: .destructive) {
withAnimation(.easeInOut(duration: 0.2)) {
@@ -116,7 +116,7 @@ struct TranscriptionHistoryView: View {
}
private func entryRow(_ entry: TranscriptionHistoryEntry) -> some View {
- let isSelected = selectedEntryID == entry.id
+ let isSelected = self.selectedEntryID == entry.id
return Button {
withAnimation(.easeInOut(duration: 0.15)) {
@@ -335,7 +335,7 @@ struct TranscriptionHistoryView: View {
}
.padding(24)
}
- .background(theme.palette.cardBackground.opacity(0.15))
+ .background(self.theme.palette.cardBackground.opacity(0.15))
}
private func detailSection(
@@ -442,7 +442,7 @@ struct TranscriptionHistoryView: View {
.foregroundStyle(.secondary)
}
.frame(maxWidth: .infinity, maxHeight: .infinity)
- .background(theme.palette.cardBackground.opacity(0.15))
+ .background(self.theme.palette.cardBackground.opacity(0.15))
}
}
diff --git a/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift b/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift
index fb30a8ce..560ab9c8 100644
--- a/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift
+++ b/Sources/Fluid/UI/Visualization/AudioVisualizationShared.swift
@@ -12,7 +12,7 @@ final class AudioVisualizationData: ObservableObject {
private var cancellable: AnyCancellable?
init(audioLevelPublisher: AnyPublisher<CGFloat, Never>) {
- cancellable = audioLevelPublisher
+ self.cancellable = audioLevelPublisher
.receive(on: RunLoop.main)
.sink { [weak self] level in
self?.audioLevel = level
diff --git a/Sources/Fluid/UI/WelcomeView.swift b/Sources/Fluid/UI/WelcomeView.swift
index 36c5b8d1..5f2ee92b 100644
--- a/Sources/Fluid/UI/WelcomeView.swift
+++ b/Sources/Fluid/UI/WelcomeView.swift
@@ -4,7 +4,7 @@ import SwiftUI
struct WelcomeView: View {
@EnvironmentObject var appServices: AppServices
- private var asr: ASRService { appServices.asr }
+ private var asr: ASRService { self.appServices.asr }
@ObservedObject private var settings = SettingsStore.shared
@Binding var selectedSidebarItem: SidebarItem?
@Binding var playgroundUsed: Bool
@@ -24,11 +24,11 @@ struct WelcomeView: View {
let openAccessibilitySettings: () -> Void
private var commandModeShortcutDisplay: String {
- settings.commandModeHotkeyShortcut.displayString
+ self.settings.commandModeHotkeyShortcut.displayString
}
private var writeModeShortcutDisplay: String {
- settings.rewriteModeHotkeyShortcut.displayString
+ self.settings.rewriteModeHotkeyShortcut.displayString
}
var body: some View {
diff --git a/Sources/Fluid/Views/CommandModeView.swift b/Sources/Fluid/Views/CommandModeView.swift
index 3253d5f2..967a4761 100644
--- a/Sources/Fluid/Views/CommandModeView.swift
+++ b/Sources/Fluid/Views/CommandModeView.swift
@@ -3,7 +3,7 @@ import SwiftUI
struct CommandModeView: View {
@ObservedObject var service: CommandModeService
@EnvironmentObject var appServices: AppServices
- private var asr: ASRService { appServices.asr }
+ private var asr: ASRService { self.appServices.asr }
@ObservedObject var settings = SettingsStore.shared
@EnvironmentObject var menuBarManager: MenuBarManager
var onClose: (() -> Void)?
@@ -51,12 +51,12 @@ struct CommandModeView: View {
// Re-enable notch output when leaving in-app UI
self.service.enableNotchOutput = true
}
- .onChange(of: asr.finalText) { _, newText in
+ .onChange(of: self.asr.finalText) { _, newText in
if !newText.isEmpty {
self.inputText = newText
}
}
- .onChange(of: settings.commandModeSelectedProviderID) { _, _ in
+ .onChange(of: self.settings.commandModeSelectedProviderID) { _, _ in
self.updateAvailableModels()
}
.onExitCommand {
@@ -156,7 +156,7 @@ struct CommandModeView: View {
.background(Color(nsColor: .windowBackgroundColor))
.confirmationDialog(
"Delete this chat?",
- isPresented: $showingClearConfirmation,
+ isPresented: self.$showingClearConfirmation,
titleVisibility: .visible
) {
Button("Delete", role: .destructive) {
@@ -169,7 +169,7 @@ struct CommandModeView: View {
// MARK: - How To Section
private var shortcutDisplay: String {
- settings.commandModeHotkeyShortcut.displayString
+ self.settings.commandModeHotkeyShortcut.displayString
}
private var howToSection: some View {
@@ -315,7 +315,7 @@ struct CommandModeView: View {
// MARK: - Processing Indicator (Minimal with Shimmer)
private var processingIndicator: some View {
- CommandShimmerText(text: currentStepLabel)
+ CommandShimmerText(text: self.currentStepLabel)
.padding(.horizontal, 12)
.padding(.vertical, 8)
.background(Color(nsColor: .controlBackgroundColor).opacity(0.6))
@@ -326,7 +326,7 @@ struct CommandModeView: View {
private var streamingTextView: some View {
// Use fixedSize to prevent expensive re-layout on every update
- Text(service.streamingText)
+ Text(self.service.streamingText)
.font(.system(size: 13))
.foregroundStyle(.primary.opacity(0.9))
.padding(.horizontal, 12)
@@ -342,8 +342,8 @@ struct CommandModeView: View {
guard let step = service.currentStep else { return "Working..." }
switch step {
case .thinking: return "Thinking..."
- case let .checking(cmd): return "Checking \(truncateCommand(cmd, to: 30))"
- case let .executing(cmd): return "Running \(truncateCommand(cmd, to: 30))"
+ case let .checking(cmd): return "Checking \(self.truncateCommand(cmd, to: 30))"
+ case let .executing(cmd): return "Running \(self.truncateCommand(cmd, to: 30))"
case .verifying: return "Verifying..."
case let .completed(success): return success ? "Done" : "Stopped"
}
@@ -504,41 +504,41 @@ struct CommandModeView: View {
// MARK: - Actions
private func toggleRecording() {
- if asr.isRunning {
+ if self.asr.isRunning {
Task { await self.asr.stop() }
} else {
- asr.start()
+ self.asr.start()
}
}
private func submitCommand() {
- guard !inputText.isEmpty else { return }
- let text = inputText
- inputText = ""
+ guard !self.inputText.isEmpty else { return }
+ let text = self.inputText
+ self.inputText = ""
Task {
await self.service.processUserCommand(text)
}
}
private func updateAvailableModels() {
- let currentProviderID = settings.commandModeSelectedProviderID
- let currentModel = settings.commandModeSelectedModel ?? "gpt-4o"
+ let currentProviderID = self.settings.commandModeSelectedProviderID
+ let currentModel = self.settings.commandModeSelectedModel ?? "gpt-4o"
// Pull models from the shared pool configured in AI Settings
- let possibleKeys = providerKeys(for: currentProviderID)
+ let possibleKeys = self.providerKeys(for: currentProviderID)
let storedList = possibleKeys.lazy
.compactMap { SettingsStore.shared.availableModelsByProvider[$0] }
.first { !$0.isEmpty }
if let stored = storedList {
- availableModels = stored
+ self.availableModels = stored
} else {
- availableModels = defaultModels(for: currentProviderID)
+ self.availableModels = self.defaultModels(for: currentProviderID)
}
// If current model not in list, select first available
- if !availableModels.contains(currentModel) {
- settings.commandModeSelectedModel = availableModels.first ?? "gpt-4o"
+ if !self.availableModels.contains(currentModel) {
+ self.settings.commandModeSelectedModel = self.availableModels.first ?? "gpt-4o"
}
}
@@ -586,7 +586,7 @@ struct CommandShimmerText: View {
@State private var shimmerPhase: CGFloat = 0
var body: some View {
- Text(text)
+ Text(self.text)
.font(.system(size: 11, weight: .medium))
.foregroundStyle(LinearGradient(
colors: [
@@ -596,8 +596,8 @@ struct CommandShimmerText: View {
Color.primary.opacity(0.4),
Color.primary.opacity(0.4),
],
- startPoint: UnitPoint(x: shimmerPhase - 0.3, y: 0.5),
- endPoint: UnitPoint(x: shimmerPhase + 0.3, y: 0.5)
+ startPoint: UnitPoint(x: self.shimmerPhase - 0.3, y: 0.5),
+ endPoint: UnitPoint(x: self.shimmerPhase + 0.3, y: 0.5)
))
.onAppear {
withAnimation(.linear(duration: 1.2).repeatForever(autoreverses: false)) {
@@ -627,7 +627,7 @@ struct MessageBubble: View {
// MARK: - User Message
private var userMessageView: some View {
- Text(message.content)
+ Text(self.message.content)
.font(.system(size: 13))
.padding(.horizontal, 12)
.padding(.vertical, 8)
@@ -689,7 +689,7 @@ struct MessageBubble: View {
// MARK: - Tool Output View (Minimal)
private var toolOutputView: some View {
- let parsed = parseToolOutput(message.content)
+ let parsed = self.parseToolOutput(self.message.content)
return VStack(alignment: .leading, spacing: 0) {
// Minimal header - just status and time
@@ -744,7 +744,7 @@ struct MessageBubble: View {
// MARK: - Text Content View (Minimal)
private var textContentView: some View {
- Text(markdownAttributedString(from: message.content))
+ Text(self.markdownAttributedString(from: self.message.content))
.font(.system(size: 13))
.textSelection(.enabled)
}
diff --git a/Sources/Fluid/Views/NotchContentViews.swift b/Sources/Fluid/Views/NotchContentViews.swift
index f724102b..a2a350e6 100644
--- a/Sources/Fluid/Views/NotchContentViews.swift
+++ b/Sources/Fluid/Views/NotchContentViews.swift
@@ -50,23 +50,23 @@ class NotchContentState: ObservableObject {
/// Set AI processing state
func setProcessing(_ processing: Bool) {
- isProcessing = processing
+ self.isProcessing = processing
}
/// Update transcription and recompute cached lines
func updateTranscription(_ text: String) {
- guard text != transcriptionText else { return }
- transcriptionText = text
- recomputeTranscriptionLines()
+ guard text != self.transcriptionText else { return }
+ self.transcriptionText = text
+ self.recomputeTranscriptionLines()
}
/// Recompute cached transcription lines (called only when text changes)
private func recomputeTranscriptionLines() {
- let text = transcriptionText
+ let text = self.transcriptionText
guard !text.isEmpty else {
- cachedLine1 = ""
- cachedLine2 = ""
+ self.cachedLine1 = ""
+ self.cachedLine2 = ""
return
}
@@ -79,13 +79,13 @@ class NotchContentState: ObservableObject {
if words.count <= 6 {
// Short: only line 2
- cachedLine1 = ""
- cachedLine2 = displayText
+ self.cachedLine1 = ""
+ self.cachedLine2 = displayText
} else {
// Long: split roughly in half
let midPoint = words.count / 2
- cachedLine1 = words[..<midPoint].joined(separator: " ")
- cachedLine2 = words[midPoint...].joined(separator: " ")
+ self.cachedLine1 = words[..<midPoint].joined(separator: " ")
+ self.cachedLine2 = words[midPoint...].joined(separator: " ")
}
}
@@ -96,66 +96,66 @@ class NotchContentState: ObservableObject {
/// Set recording state (for waveform visibility in expanded view)
func setRecordingInExpandedMode(_ recording: Bool) {
- isRecordingInExpandedMode = recording
+ self.isRecordingInExpandedMode = recording
if !recording {
- expandedModeAudioLevel = 0
+ self.expandedModeAudioLevel = 0
}
}
/// Update audio level for expanded mode waveform
func updateExpandedModeAudioLevel(_ level: CGFloat) {
- guard isRecordingInExpandedMode else { return }
- expandedModeAudioLevel = level
+ guard self.isRecordingInExpandedMode else { return }
+ self.expandedModeAudioLevel = level
}
// MARK: - Command Output Methods
/// Show expanded output view with content
func showExpandedCommandOutput(output: String) {
- commandOutput = output
- commandStreamingText = ""
- isExpandedForCommandOutput = true
- isRecordingInExpandedMode = false // Not recording when first showing output
+ self.commandOutput = output
+ self.commandStreamingText = ""
+ self.isExpandedForCommandOutput = true
+ self.isRecordingInExpandedMode = false // Not recording when first showing output
}
/// Update streaming text in real-time
func updateCommandStreamingText(_ text: String) {
- commandStreamingText = text
+ self.commandStreamingText = text
}
/// Add a message to the conversation history
func addCommandMessage(role: CommandOutputMessage.Role, content: String) {
let message = CommandOutputMessage(role: role, content: content)
- commandConversationHistory.append(message)
+ self.commandConversationHistory.append(message)
}
/// Set command processing state
func setCommandProcessing(_ processing: Bool) {
- isCommandProcessing = processing
+ self.isCommandProcessing = processing
}
/// Clear command output and hide expanded view
func clearCommandOutput() {
- isExpandedForCommandOutput = false
- commandOutput = ""
- commandStreamingText = ""
- commandInputText = ""
- commandConversationHistory.removeAll()
- isCommandProcessing = false
+ self.isExpandedForCommandOutput = false
+ self.commandOutput = ""
+ self.commandStreamingText = ""
+ self.commandInputText = ""
+ self.commandConversationHistory.removeAll()
+ self.isCommandProcessing = false
}
/// Hide expanded view but keep history
func collapseCommandOutput() {
- isExpandedForCommandOutput = false
+ self.isExpandedForCommandOutput = false
}
// MARK: - Chat History Methods
/// Refresh recent chats from store
func refreshRecentChats() {
- recentChats = ChatHistoryStore.shared.getRecentChats(excludingCurrent: false)
+ self.recentChats = ChatHistoryStore.shared.getRecentChats(excludingCurrent: false)
if let current = ChatHistoryStore.shared.currentSession {
- currentChatTitle = current.title
+ self.currentChatTitle = current.title
}
}
}
@@ -187,18 +187,18 @@ struct ShimmerText: View {
@State private var shimmerPhase: CGFloat = 0
var body: some View {
- Text(text)
+ Text(self.text)
.font(.system(size: 9, weight: .medium))
.foregroundStyle(LinearGradient(
colors: [
- color.opacity(0.4),
- color.opacity(0.4),
- color.opacity(1.0),
- color.opacity(0.4),
- color.opacity(0.4),
+ self.color.opacity(0.4),
+ self.color.opacity(0.4),
+ self.color.opacity(1.0),
+ self.color.opacity(0.4),
+ self.color.opacity(0.4),
],
- startPoint: UnitPoint(x: shimmerPhase - 0.3, y: 0.5),
- endPoint: UnitPoint(x: shimmerPhase + 0.3, y: 0.5)
+ startPoint: UnitPoint(x: self.shimmerPhase - 0.3, y: 0.5),
+ endPoint: UnitPoint(x: self.shimmerPhase + 0.3, y: 0.5)
))
.onAppear {
withAnimation(.linear(duration: 1.2).repeatForever(autoreverses: false)) {
@@ -215,11 +215,11 @@ struct NotchExpandedView: View {
@ObservedObject private var contentState = NotchContentState.shared
private var modeColor: Color {
- contentState.mode.notchColor
+ self.contentState.mode.notchColor
}
private var modeLabel: String {
- switch contentState.mode {
+ switch self.contentState.mode {
case .dictation: return "Dictate"
case .rewrite: return "Rewrite"
case .write: return "Write"
@@ -228,7 +228,7 @@ struct NotchExpandedView: View {
}
private var processingLabel: String {
- switch contentState.mode {
+ switch self.contentState.mode {
case .dictation: return "Refining..."
case .rewrite: return "Thinking..."
case .write: return "Thinking..."
@@ -237,12 +237,12 @@ struct NotchExpandedView: View {
}
private var hasTranscription: Bool {
- !contentState.transcriptionText.isEmpty
+ !self.contentState.transcriptionText.isEmpty
}
// Check if there's command history that can be expanded
private var canExpandCommandHistory: Bool {
- contentState.mode == .command && !contentState.commandConversationHistory.isEmpty
+ self.contentState.mode == .command && !self.contentState.commandConversationHistory.isEmpty
}
var body: some View {
@@ -287,9 +287,9 @@ struct NotchExpandedView: View {
NotchOverlayManager.shared.onNotchClicked?()
}
}
- .animation(.spring(response: 0.25, dampingFraction: 0.8), value: hasTranscription)
- .animation(.easeInOut(duration: 0.2), value: contentState.mode)
- .animation(.easeInOut(duration: 0.25), value: contentState.isProcessing)
+ .animation(.spring(response: 0.25, dampingFraction: 0.8), value: self.hasTranscription)
+ .animation(.easeInOut(duration: 0.2), value: self.contentState.mode)
+ .animation(.easeInOut(duration: 0.25), value: self.contentState.isProcessing)
}
}
@@ -314,15 +314,15 @@ struct NotchWaveformView: View {
// Computed glow values based on phase (sine wave for smooth pulsing)
private var currentGlowIntensity: CGFloat {
- contentState.isProcessing ? 0.4 + 0.4 * sin(glowPhase * .pi * 2) : 0.4
+ self.contentState.isProcessing ? 0.4 + 0.4 * sin(self.glowPhase * .pi * 2) : 0.4
}
private var currentGlowRadius: CGFloat {
- contentState.isProcessing ? 2 + 4 * sin(glowPhase * .pi * 2) : 2
+ self.contentState.isProcessing ? 2 + 4 * sin(self.glowPhase * .pi * 2) : 2
}
private var currentOuterGlowRadius: CGFloat {
- contentState.isProcessing ? 6 * sin(glowPhase * .pi * 2) : 0
+ self.contentState.isProcessing ? 6 * sin(self.glowPhase * .pi * 2) : 0
}
init(audioPublisher: AnyPublisher<CGFloat, Never>, color: Color, isProcessing: Bool = false) {
@@ -332,7 +332,7 @@ struct NotchWaveformView: View {
}
var body: some View {
- HStack(spacing: barSpacing) {
+ HStack(spacing: self.barSpacing) {
ForEach(0..<self.barCount, id: \.self) { index in
RoundedRectangle(cornerRadius: self.barWidth / 2)
.fill(self.color)
@@ -351,12 +351,12 @@ struct NotchWaveformView: View {
)
}
}
- .onChange(of: data.audioLevel) { _, level in
+ .onChange(of: self.data.audioLevel) { _, level in
if !self.contentState.isProcessing {
self.updateBars(level: level)
}
}
- .onChange(of: contentState.isProcessing) { _, processing in
+ .onChange(of: self.contentState.isProcessing) { _, processing in
if processing {
self.setStaticProcessingBars()
self.startGlowAnimation()
@@ -385,11 +385,11 @@ struct NotchWaveformView: View {
}
private func startGlowAnimation() {
- stopGlowAnimation() // Clean up any existing timer
- glowPhase = 0
+ self.stopGlowAnimation() // Clean up any existing timer
+ self.glowPhase = 0
// Timer-based animation for explicit control
- glowTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30.0, repeats: true) { _ in
+ self.glowTimer = Timer.scheduledTimer(withTimeInterval: 1.0 / 30.0, repeats: true) { _ in
withAnimation(.linear(duration: 1.0 / 30.0)) {
self.glowPhase += 1.0 / 30.0 / 1.5 // Complete cycle in 1.5 seconds
if self.glowPhase >= 1.0 {
@@ -400,9 +400,9 @@ struct NotchWaveformView: View {
}
private func stopGlowAnimation() {
- glowTimer?.invalidate()
- glowTimer = nil
- glowPhase = 0
+ self.glowTimer?.invalidate()
+ self.glowTimer = nil
+ self.glowPhase = 0
}
private func setStaticProcessingBars() {
@@ -418,7 +418,7 @@ struct NotchWaveformView: View {
private func updateBars(level: CGFloat) {
let normalizedLevel = min(max(level, 0), 1)
- let isActive = normalizedLevel > noiseThreshold // Use user's sensitivity setting
+ let isActive = normalizedLevel > self.noiseThreshold // Use user's sensitivity setting
withAnimation(.spring(response: 0.15, dampingFraction: 0.6)) {
for i in 0..<self.barCount {
@@ -449,9 +449,9 @@ struct NotchCompactLeadingView: View {
var body: some View {
Image(systemName: "waveform")
.font(.system(size: 9, weight: .medium))
- .foregroundStyle(contentState.mode.notchColor)
- .scaleEffect(isPulsing ? 1.1 : 1.0)
- .animation(.easeInOut(duration: 0.8).repeatForever(autoreverses: true), value: isPulsing)
+ .foregroundStyle(self.contentState.mode.notchColor)
+ .scaleEffect(self.isPulsing ? 1.1 : 1.0)
+ .animation(.easeInOut(duration: 0.8).repeatForever(autoreverses: true), value: self.isPulsing)
.onAppear { self.isPulsing = true }
.onDisappear { self.isPulsing = false }
}
@@ -463,11 +463,11 @@ struct NotchCompactTrailingView: View {
var body: some View {
Circle()
- .fill(contentState.mode.notchColor)
+ .fill(self.contentState.mode.notchColor)
.frame(width: 5, height: 5)
- .opacity(isPulsing ? 0.5 : 1.0)
- .scaleEffect(isPulsing ? 0.85 : 1.0)
- .animation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true), value: isPulsing)
+ .opacity(self.isPulsing ? 0.5 : 1.0)
+ .scaleEffect(self.isPulsing ? 0.85 : 1.0)
+ .animation(.easeInOut(duration: 1.0).repeatForever(autoreverses: true), value: self.isPulsing)
.onAppear { self.isPulsing = true }
.onDisappear { self.isPulsing = false }
}
@@ -497,7 +497,7 @@ struct NotchCommandOutputExpandedView: View {
// Dynamic height based on content (max half screen)
private var dynamicHeight: CGFloat {
let baseHeight: CGFloat = 120 // Minimum height
- let contentHeight = estimateContentHeight()
+ let contentHeight = self.estimateContentHeight()
let maxHeight = (NSScreen.main?.frame.height ?? 800) * 0.45 // 45% of screen
return min(max(baseHeight, contentHeight), maxHeight)
}
@@ -506,13 +506,13 @@ struct NotchCommandOutputExpandedView: View {
var height: CGFloat = 80 // Header + input area
// Estimate based on conversation history
- for message in contentState.commandConversationHistory {
+ for message in self.contentState.commandConversationHistory {
let lineCount = max(1, message.content.count / 60) // ~60 chars per line
height += CGFloat(lineCount) * 18 + 16 // Line height + padding
}
// Add streaming text height
- if !contentState.commandStreamingText.isEmpty {
+ if !self.contentState.commandStreamingText.isEmpty {
let lineCount = max(1, contentState.commandStreamingText.count / 60)
height += CGFloat(lineCount) * 18 + 16
}
@@ -537,15 +537,15 @@ struct NotchCommandOutputExpandedView: View {
// Input area for follow-up commands
self.inputArea
}
- .frame(width: 380, height: dynamicHeight)
+ .frame(width: 380, height: self.dynamicHeight)
.background(Color.black)
.clipShape(RoundedRectangle(cornerRadius: 16))
.animation(
.spring(response: 0.3, dampingFraction: 0.8),
- value: contentState.commandConversationHistory.count
+ value: self.contentState.commandConversationHistory.count
)
// No animation on streamingText - it updates too frequently, animations add overhead
- .animation(.spring(response: 0.25, dampingFraction: 0.8), value: contentState.isRecordingInExpandedMode)
+ .animation(.spring(response: 0.25, dampingFraction: 0.8), value: self.contentState.isRecordingInExpandedMode)
}
// MARK: - Header
@@ -727,8 +727,8 @@ struct NotchCommandOutputExpandedView: View {
.transition(.opacity.combined(with: .scale(scale: 0.98)))
}
}
- .animation(.easeInOut(duration: 0.2), value: contentState.isRecordingInExpandedMode)
- .animation(.easeInOut(duration: 0.15), value: contentState.transcriptionText)
+ .animation(.easeInOut(duration: 0.2), value: self.contentState.isRecordingInExpandedMode)
+ .animation(.easeInOut(duration: 0.15), value: self.contentState.transcriptionText)
}
// MARK: - Conversation Area
@@ -866,7 +866,7 @@ struct NotchCommandOutputExpandedView: View {
private func processingOffset(for index: Int) -> CGFloat {
// Offset varies by index for staggered animation effect
_ = Double(index) * 0.15 // Reserved for future animation timing
- return processingAnimation ? -3 : 3
+ return self.processingAnimation ? -3 : 3
}
// MARK: - Input Area
@@ -900,9 +900,9 @@ struct NotchCommandOutputExpandedView: View {
}
private func submitFollowUp() {
- guard !inputText.isEmpty else { return }
- let text = inputText
- inputText = ""
+ guard !self.inputText.isEmpty else { return }
+ let text = self.inputText
+ self.inputText = ""
Task {
await self.onSubmit(text)
@@ -926,7 +926,7 @@ struct ExpandedModeWaveformView: View {
private let noiseThreshold: CGFloat = 0.05
var body: some View {
- HStack(spacing: barSpacing) {
+ HStack(spacing: self.barSpacing) {
ForEach(0..<self.barCount, id: \.self) { index in
RoundedRectangle(cornerRadius: self.barWidth / 2)
.fill(self.color)
@@ -934,7 +934,7 @@ struct ExpandedModeWaveformView: View {
.shadow(color: self.color.opacity(0.4), radius: 2, x: 0, y: 0)
}
}
- .onChange(of: contentState.expandedModeAudioLevel) { _, level in
+ .onChange(of: self.contentState.expandedModeAudioLevel) { _, level in
self.updateBars(level: level)
}
.onAppear {
@@ -944,7 +944,7 @@ struct ExpandedModeWaveformView: View {
private func updateBars(level: CGFloat) {
let normalizedLevel = min(max(level, 0), 1)
- let isActive = normalizedLevel > noiseThreshold
+ let isActive = normalizedLevel > self.noiseThreshold
withAnimation(.spring(response: 0.12, dampingFraction: 0.6)) {
for i in 0..<self.barCount {
diff --git a/Sources/Fluid/Views/RewriteModeView.swift b/Sources/Fluid/Views/RewriteModeView.swift
index 6f1d2f71..c34b20cc 100644
--- a/Sources/Fluid/Views/RewriteModeView.swift
+++ b/Sources/Fluid/Views/RewriteModeView.swift
@@ -3,7 +3,7 @@ import SwiftUI
struct RewriteModeView: View {
@ObservedObject var service: RewriteModeService
@EnvironmentObject var appServices: AppServices
- private var asr: ASRService { appServices.asr }
+ private var asr: ASRService { self.appServices.asr }
@ObservedObject var settings = SettingsStore.shared
@EnvironmentObject var menuBarManager: MenuBarManager
var onClose: (() -> Void)?
@@ -226,7 +226,7 @@ struct RewriteModeView: View {
.padding()
.background(Color(nsColor: .windowBackgroundColor))
}
- .onChange(of: asr.finalText) { _, newText in
+ .onChange(of: self.asr.finalText) { _, newText in
if !newText.isEmpty {
self.inputText = newText
}
@@ -242,17 +242,17 @@ struct RewriteModeView: View {
}
private func toggleRecording() {
- if asr.isRunning {
+ if self.asr.isRunning {
Task { await self.asr.stop() }
} else {
- asr.start()
+ self.asr.start()
}
}
private func submitRequest() {
- guard !inputText.isEmpty else { return }
- let prompt = inputText
- inputText = ""
+ guard !self.inputText.isEmpty else { return }
+ let prompt = self.inputText
+ self.inputText = ""
Task {
await self.service.processRewriteRequest(prompt)
}
@@ -261,30 +261,30 @@ struct RewriteModeView: View {
// MARK: - Model Management (pulls from shared AI Settings pool)
private func updateAvailableModels() {
- let currentProviderID = settings.rewriteModeSelectedProviderID
- let currentModel = settings.rewriteModeSelectedModel ?? "gpt-4o"
+ let currentProviderID = self.settings.rewriteModeSelectedProviderID
+ let currentModel = self.settings.rewriteModeSelectedModel ?? "gpt-4o"
// Apple Intelligence has only one model
if currentProviderID == "apple-intelligence" {
- availableModels = ["System Model"]
+ self.availableModels = ["System Model"]
return
}
// Pull models from the shared pool configured in AI Settings
- let possibleKeys = providerKeys(for: currentProviderID)
+ let possibleKeys = self.providerKeys(for: currentProviderID)
let storedList = possibleKeys.lazy
.compactMap { SettingsStore.shared.availableModelsByProvider[$0] }
.first { !$0.isEmpty }
if let stored = storedList {
- availableModels = stored
+ self.availableModels = stored
} else {
- availableModels = defaultModels(for: currentProviderID)
+ self.availableModels = self.defaultModels(for: currentProviderID)
}
// If current model not in list, select first available
- if !availableModels.contains(currentModel) {
- settings.rewriteModeSelectedModel = availableModels.first ?? "gpt-4o"
+ if !self.availableModels.contains(currentModel) {
+ self.settings.rewriteModeSelectedModel = self.availableModels.first ?? "gpt-4o"
}
}
@@ -323,7 +323,7 @@ struct RewriteModeView: View {
// MARK: - How To Section
private var shortcutDisplay: String {
- settings.rewriteModeHotkeyShortcut.displayString
+ self.settings.rewriteModeHotkeyShortcut.displayString
}
private var howToSection: some View {